org.el 804 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2019 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; Homepage: https://orgmode.org
  8. ;; Version: 9.3
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar org-inlinetask-min-level)
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (eq this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (eval-and-compile (require 'org-macs))
  81. (require 'org-compat)
  82. (require 'org-keys)
  83. (require 'ol)
  84. (require 'org-table)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  111. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  112. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  113. (declare-function org-clock-cancel "org-clock" ())
  114. (declare-function org-clock-display "org-clock" (&optional arg))
  115. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  116. (declare-function org-clock-goto "org-clock" (&optional select))
  117. (declare-function org-clock-in "org-clock" (&optional select start-time))
  118. (declare-function org-clock-in-last "org-clock" (&optional arg))
  119. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  120. (declare-function org-clock-out-if-current "org-clock" ())
  121. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  122. (declare-function org-clock-report "org-clock" (&optional arg))
  123. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  124. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  125. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  126. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  127. (declare-function org-clock-update-time-maybe "org-clock" ())
  128. (declare-function org-clocking-buffer "org-clock" ())
  129. (declare-function org-clocktable-shift "org-clock" (dir n))
  130. (declare-function org-columns-insert-dblock "org-colview" ())
  131. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  132. (declare-function org-element-at-point "org-element" ())
  133. (declare-function org-element-cache-refresh "org-element" (pos))
  134. (declare-function org-element-cache-reset "org-element" (&optional all))
  135. (declare-function org-element-contents "org-element" (element))
  136. (declare-function org-element-context "org-element" (&optional element))
  137. (declare-function org-element-copy "org-element" (datum))
  138. (declare-function org-element-create "org-element" (type &optional props &rest children))
  139. (declare-function org-element-interpret-data "org-element" (data))
  140. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  141. (declare-function org-element-link-parser "org-element" ())
  142. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  143. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  144. (declare-function org-element-property "org-element" (property element))
  145. (declare-function org-element-put-property "org-element" (element property value))
  146. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  147. (declare-function org-element-timestamp-parser "org-element" ())
  148. (declare-function org-element-type "org-element" (element))
  149. (declare-function org-export-dispatch "ox" (&optional arg))
  150. (declare-function org-export-get-backend "ox" (name))
  151. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  152. (declare-function org-feed-goto-inbox "org-feed" (feed))
  153. (declare-function org-feed-update-all "org-feed" ())
  154. (declare-function org-goto "org-goto" (&optional alternative-interface))
  155. (declare-function org-id-find-id-file "org-id" (id))
  156. (declare-function org-id-get-create "org-id" (&optional force))
  157. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  158. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  159. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  160. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  161. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  162. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  163. (declare-function org-timer "org-timer" (&optional restart no-insert))
  164. (declare-function org-timer-item "org-timer" (&optional arg))
  165. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  166. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  167. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  168. (declare-function org-timer-start "org-timer" (&optional offset))
  169. (declare-function org-timer-stop "org-timer" ())
  170. (declare-function org-timer-stop "org-timer" ())
  171. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  172. (declare-function org-update-radio-target-regexp "ol" ())
  173. (defvar ffap-url-regexp)
  174. (defvar org-element-paragraph-separate)
  175. (defvar org-indent-indentation-per-level)
  176. (defvar org-radio-target-regexp)
  177. (defvar org-target-link-regexp)
  178. (defvar org-target-regexp)
  179. ;; load languages based on value of `org-babel-load-languages'
  180. (defvar org-babel-load-languages)
  181. ;;;###autoload
  182. (defun org-babel-do-load-languages (sym value)
  183. "Load the languages defined in `org-babel-load-languages'."
  184. (set-default sym value)
  185. (dolist (pair org-babel-load-languages)
  186. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  187. (if active
  188. (require (intern (concat "ob-" lang)))
  189. (fmakunbound
  190. (intern (concat "org-babel-execute:" lang)))
  191. (fmakunbound
  192. (intern (concat "org-babel-expand-body:" lang)))))))
  193. ;;;###autoload
  194. (defun org-babel-load-file (file &optional compile)
  195. "Load Emacs Lisp source code blocks in the Org FILE.
  196. This function exports the source code using `org-babel-tangle'
  197. and then loads the resulting file using `load-file'. With
  198. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  199. byte-compiled before it is loaded."
  200. (interactive "fFile to load: \nP")
  201. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  202. ;; Tangle only if the Org file is newer than the Elisp file.
  203. (unless (org-file-newer-than-p
  204. tangled-file
  205. (file-attribute-modification-time (file-attributes file)))
  206. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  207. (if compile
  208. (progn
  209. (byte-compile-file tangled-file 'load)
  210. (message "Compiled and loaded %s" tangled-file))
  211. (load-file tangled-file)
  212. (message "Loaded %s" tangled-file))))
  213. (defcustom org-babel-load-languages '((emacs-lisp . t))
  214. "Languages which can be evaluated in Org buffers.
  215. \\<org-mode-map>
  216. This list can be used to load support for any of the languages
  217. below. Each language will depend on a different set of system
  218. executables and/or Emacs modes.
  219. When a language is \"loaded\", code blocks in that language can
  220. be evaluated with `org-babel-execute-src-block', which is bound
  221. by default to \\[org-ctrl-c-ctrl-c].
  222. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  223. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  224. default, only Emacs Lisp is loaded, since it has no specific
  225. requirement."
  226. :group 'org-babel
  227. :set 'org-babel-do-load-languages
  228. :version "24.1"
  229. :type '(alist :tag "Babel Languages"
  230. :key-type
  231. (choice
  232. (const :tag "Awk" awk)
  233. (const :tag "C" C)
  234. (const :tag "R" R)
  235. (const :tag "Asymptote" asymptote)
  236. (const :tag "Calc" calc)
  237. (const :tag "Clojure" clojure)
  238. (const :tag "CSS" css)
  239. (const :tag "Ditaa" ditaa)
  240. (const :tag "Dot" dot)
  241. (const :tag "Ebnf2ps" ebnf2ps)
  242. (const :tag "Emacs Lisp" emacs-lisp)
  243. (const :tag "Forth" forth)
  244. (const :tag "Fortran" fortran)
  245. (const :tag "Gnuplot" gnuplot)
  246. (const :tag "Haskell" haskell)
  247. (const :tag "hledger" hledger)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "Vala" vala))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Block
  326. (defconst org-block-regexp
  327. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  328. "Regular expression for hiding blocks.")
  329. (defconst org-dblock-start-re
  330. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  331. "Matches the start line of a dynamic block, with parameters.")
  332. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  333. "Matches the end of a dynamic block.")
  334. ;;;; Clock and Planning
  335. (defconst org-clock-string "CLOCK:"
  336. "String used as prefix for timestamps clocking work hours on an item.")
  337. (defvar org-closed-string "CLOSED:"
  338. "String used as the prefix for timestamps logging closing a TODO entry.")
  339. (defvar org-deadline-string "DEADLINE:"
  340. "String to mark deadline entries.
  341. \\<org-mode-map>
  342. A deadline is this string, followed by a time stamp. It must be
  343. a word, terminated by a colon. You can insert a schedule keyword
  344. and a timestamp with `\\[org-deadline]'.")
  345. (defvar org-scheduled-string "SCHEDULED:"
  346. "String to mark scheduled TODO entries.
  347. \\<org-mode-map>
  348. A schedule is this string, followed by a time stamp. It must be
  349. a word, terminated by a colon. You can insert a schedule keyword
  350. and a timestamp with `\\[org-schedule]'.")
  351. (defconst org-ds-keyword-length
  352. (+ 2
  353. (apply #'max
  354. (mapcar #'length
  355. (list org-deadline-string org-scheduled-string
  356. org-clock-string org-closed-string))))
  357. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  358. (defconst org-planning-line-re
  359. (concat "^[ \t]*"
  360. (regexp-opt
  361. (list org-closed-string org-deadline-string org-scheduled-string)
  362. t))
  363. "Matches a line with planning info.
  364. Matched keyword is in group 1.")
  365. (defconst org-clock-line-re
  366. (concat "^[ \t]*" org-clock-string)
  367. "Matches a line with clock info.")
  368. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  369. "Matches the DEADLINE keyword.")
  370. (defconst org-deadline-time-regexp
  371. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  372. "Matches the DEADLINE keyword together with a time stamp.")
  373. (defconst org-deadline-time-hour-regexp
  374. (concat "\\<" org-deadline-string
  375. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy \t.-]*\\)>")
  376. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  377. (defconst org-deadline-line-regexp
  378. (concat "\\<\\(" org-deadline-string "\\).*")
  379. "Matches the DEADLINE keyword and the rest of the line.")
  380. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  381. "Matches the SCHEDULED keyword.")
  382. (defconst org-scheduled-time-regexp
  383. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  384. "Matches the SCHEDULED keyword together with a time stamp.")
  385. (defconst org-scheduled-time-hour-regexp
  386. (concat "\\<" org-scheduled-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy \t.-]*\\)>")
  388. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  389. (defconst org-closed-time-regexp
  390. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  391. "Matches the CLOSED keyword together with a time stamp.")
  392. (defconst org-keyword-time-regexp
  393. (concat "\\<"
  394. (regexp-opt
  395. (list org-scheduled-string org-deadline-string org-closed-string
  396. org-clock-string)
  397. t)
  398. " *[[<]\\([^]>]+\\)[]>]")
  399. "Matches any of the 4 keywords, together with the time stamp.")
  400. (defconst org-keyword-time-not-clock-regexp
  401. (concat
  402. "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string) t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 3 keywords, together with the time stamp.")
  407. (defconst org-maybe-keyword-time-regexp
  408. (concat "\\(\\<"
  409. (regexp-opt
  410. (list org-scheduled-string org-deadline-string org-closed-string
  411. org-clock-string)
  412. t)
  413. "\\)?"
  414. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  415. "\\|"
  416. "<%%([^\r\n>]*>\\)")
  417. "Matches a timestamp, possibly preceded by a keyword.")
  418. (defconst org-all-time-keywords
  419. (mapcar (lambda (w) (substring w 0 -1))
  420. (list org-scheduled-string org-deadline-string
  421. org-clock-string org-closed-string))
  422. "List of time keywords.")
  423. ;;;; Drawer
  424. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  425. "Matches first or last line of a hidden block.
  426. Group 1 contains drawer's name or \"END\".")
  427. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  428. "Regular expression matching the first line of a property drawer.")
  429. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  430. "Regular expression matching the last line of a property drawer.")
  431. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  432. "Regular expression matching the first line of a clock drawer.")
  433. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a clock drawer.")
  435. (defconst org-property-drawer-re
  436. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  437. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  438. "[ \t]*:END:[ \t]*$")
  439. "Matches an entire property drawer.")
  440. (defconst org-clock-drawer-re
  441. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  442. org-clock-drawer-end-re "\\)\n?")
  443. "Matches an entire clock drawer.")
  444. ;;;; Headline
  445. (defconst org-heading-keyword-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline with some keyword.
  448. This regexp will match the headline of any node which has the
  449. exact keyword that is put into the format. The keyword isn't in
  450. any group by default, but the stars and the body are.")
  451. (defconst org-heading-keyword-maybe-regexp-format
  452. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  453. "Printf format for a regexp matching a headline, possibly with some keyword.
  454. This regexp can match any headline with the specified keyword, or
  455. without a keyword. The keyword isn't in any group by default,
  456. but the stars and the body are.")
  457. (defconst org-archive-tag "ARCHIVE"
  458. "The tag that marks a subtree as archived.
  459. An archived subtree does not open during visibility cycling, and does
  460. not contribute to the agenda listings.")
  461. (defconst org-tag-re "[[:alnum:]_@#%]+"
  462. "Regexp matching a single tag.")
  463. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  464. "Regexp matching the tag group at the end of a line, with leading spaces.
  465. Tags are stored in match group 1. Match group 2 stores the tags
  466. without the enclosing colons.")
  467. (defconst org-tag-line-re
  468. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  469. "Regexp matching tags in a headline.
  470. Tags are stored in match group 1. Match group 2 stores the tags
  471. without the enclosing colons.")
  472. (eval-and-compile
  473. (defconst org-comment-string "COMMENT"
  474. "Entries starting with this keyword will never be exported.
  475. \\<org-mode-map>
  476. An entry can be toggled between COMMENT and normal with
  477. `\\[org-toggle-comment]'."))
  478. ;;;; LaTeX Environments and Fragments
  479. (defconst org-latex-regexps
  480. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  481. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  482. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  483. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  484. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  485. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  486. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  487. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  488. "Regular expressions for matching embedded LaTeX.")
  489. ;;;; Node Property
  490. (defconst org-effort-property "Effort"
  491. "The property that is being used to keep track of effort estimates.
  492. Effort estimates given in this property need to have the format H:MM.")
  493. ;;;; Timestamp
  494. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  495. "Regular expression for fast time stamp matching.")
  496. (defconst org-ts-regexp-inactive
  497. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  498. "Regular expression for fast inactive time stamp matching.")
  499. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  500. "Regular expression for fast time stamp matching.")
  501. (defconst org-ts-regexp0
  502. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  503. "Regular expression matching time strings for analysis.
  504. This one does not require the space after the date, so it can be used
  505. on a string that terminates immediately after the date.")
  506. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  507. "Regular expression matching time strings for analysis.")
  508. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  509. "Regular expression matching time stamps, with groups.")
  510. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  511. "Regular expression matching time stamps (also [..]), with groups.")
  512. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  513. "Regular expression matching a time stamp range.")
  514. (defconst org-tr-regexp-both
  515. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  518. org-ts-regexp "\\)?")
  519. "Regular expression matching a time stamp or time stamp range.")
  520. (defconst org-tsr-regexp-both
  521. (concat org-ts-regexp-both "\\(--?-?"
  522. org-ts-regexp-both "\\)?")
  523. "Regular expression matching a time stamp or time stamp range.
  524. The time stamps may be either active or inactive.")
  525. (defconst org-repeat-re
  526. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  527. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  528. "Regular expression for specifying repeated events.
  529. After a match, group 1 contains the repeat expression.")
  530. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  531. "Formats for `format-time-string' which are used for time stamps.")
  532. ;;; The custom variables
  533. (defgroup org nil
  534. "Outline-based notes management and organizer."
  535. :tag "Org"
  536. :group 'outlines
  537. :group 'calendar)
  538. (defcustom org-mode-hook nil
  539. "Mode hook for Org mode, run after the mode was turned on."
  540. :group 'org
  541. :type 'hook)
  542. (defcustom org-load-hook nil
  543. "Hook that is run after org.el has been loaded."
  544. :group 'org
  545. :type 'hook)
  546. (defcustom org-log-buffer-setup-hook nil
  547. "Hook that is run after an Org log buffer is created."
  548. :group 'org
  549. :version "24.1"
  550. :type 'hook)
  551. (defvar org-modules) ; defined below
  552. (defvar org-modules-loaded nil
  553. "Have the modules been loaded already?")
  554. (defun org-load-modules-maybe (&optional force)
  555. "Load all extensions listed in `org-modules'."
  556. (when (or force (not org-modules-loaded))
  557. (dolist (ext org-modules)
  558. (condition-case nil (require ext)
  559. (error (message "Problems while trying to load feature `%s'" ext))))
  560. (setq org-modules-loaded t)))
  561. (defun org-set-modules (var value)
  562. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  563. (set var value)
  564. (when (featurep 'org)
  565. (org-load-modules-maybe 'force)
  566. (org-element-cache-reset 'all)))
  567. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  568. "Modules that should always be loaded together with org.el.
  569. If a description starts with <C>, the file is not part of Emacs
  570. and loading it will require that you have downloaded and properly
  571. installed the Org mode distribution.
  572. You can also use this system to load external packages (i.e. neither Org
  573. core modules, nor modules from the CONTRIB directory). Just add symbols
  574. to the end of the list. If the package is called org-xyz.el, then you need
  575. to add the symbol `xyz', and the package must have a call to:
  576. (provide \\='org-xyz)
  577. For export specific modules, see also `org-export-backends'."
  578. :group 'org
  579. :set 'org-set-modules
  580. :version "26.1"
  581. :package-version '(Org . "9.2")
  582. :type
  583. '(set :greedy t
  584. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  585. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  586. (const :tag " crypt: Encryption of subtrees" org-crypt)
  587. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  588. (const :tag " docview: Links to Docview buffers" ol-docview)
  589. (const :tag " eww: Store link to URL of Eww" ol-eww)
  590. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  591. (const :tag " habit: Track your consistency with habits" org-habit)
  592. (const :tag " id: Global IDs for identifying entries" org-id)
  593. (const :tag " info: Links to Info nodes" ol-info)
  594. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  595. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  596. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  597. (const :tag " mouse: Additional mouse support" org-mouse)
  598. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  599. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  600. (const :tag " tempo: Fast completion for structures" org-tempo)
  601. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  602. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  603. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  604. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  605. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  606. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  607. (const :tag "C collector: Collect properties into tables" org-collector)
  608. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  609. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  610. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  611. (const :tag "C eval: Include command output as text" org-eval)
  612. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  613. (const :tag "C git-link: Links to specific file version" ol-git-link)
  614. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  615. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  616. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  617. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  618. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  619. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  620. (const :tag "C man: Links to man pages in Org mode" ol-man)
  621. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  622. (const :tag "C notify: Notifications for Org mode" org-notify)
  623. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  624. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  625. (const :tag "C registry: A registry for Org links" org-registry)
  626. (const :tag "C screen: Visit screen sessions through links" org-screen)
  627. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  628. (const :tag "C secretary: Team management with Org" org-secretary)
  629. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  630. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  631. (const :tag "C track: Keep up with Org mode development" org-track)
  632. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  633. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  634. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  635. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  636. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  637. (defvar org-export-registered-backends) ; From ox.el.
  638. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  639. (declare-function org-export-backend-name "ox" (backend) t)
  640. (defcustom org-export-backends '(ascii html icalendar latex odt)
  641. "List of export back-ends that should be always available.
  642. If a description starts with <C>, the file is not part of Emacs
  643. and loading it will require that you have downloaded and properly
  644. installed the Org mode distribution.
  645. Unlike to `org-modules', libraries in this list will not be
  646. loaded along with Org, but only once the export framework is
  647. needed.
  648. This variable needs to be set before org.el is loaded. If you
  649. need to make a change while Emacs is running, use the customize
  650. interface or run the following code, where VAL stands for the new
  651. value of the variable, after updating it:
  652. (progn
  653. (setq org-export-registered-backends
  654. (cl-remove-if-not
  655. (lambda (backend)
  656. (let ((name (org-export-backend-name backend)))
  657. (or (memq name val)
  658. (catch \\='parentp
  659. (dolist (b val)
  660. (and (org-export-derived-backend-p b name)
  661. (throw \\='parentp t)))))))
  662. org-export-registered-backends))
  663. (let ((new-list (mapcar #\\='org-export-backend-name
  664. org-export-registered-backends)))
  665. (dolist (backend val)
  666. (cond
  667. ((not (load (format \"ox-%s\" backend) t t))
  668. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  669. backend))
  670. ((not (memq backend new-list)) (push backend new-list))))
  671. (set-default \\='org-export-backends new-list)))
  672. Adding a back-end to this list will also pull the back-end it
  673. depends on, if any."
  674. :group 'org
  675. :group 'org-export
  676. :version "26.1"
  677. :package-version '(Org . "9.0")
  678. :initialize 'custom-initialize-set
  679. :set (lambda (var val)
  680. (if (not (featurep 'ox)) (set-default var val)
  681. ;; Any back-end not required anymore (not present in VAL and not
  682. ;; a parent of any back-end in the new value) is removed from the
  683. ;; list of registered back-ends.
  684. (setq org-export-registered-backends
  685. (cl-remove-if-not
  686. (lambda (backend)
  687. (let ((name (org-export-backend-name backend)))
  688. (or (memq name val)
  689. (catch 'parentp
  690. (dolist (b val)
  691. (and (org-export-derived-backend-p b name)
  692. (throw 'parentp t)))))))
  693. org-export-registered-backends))
  694. ;; Now build NEW-LIST of both new back-ends and required
  695. ;; parents.
  696. (let ((new-list (mapcar #'org-export-backend-name
  697. org-export-registered-backends)))
  698. (dolist (backend val)
  699. (cond
  700. ((not (load (format "ox-%s" backend) t t))
  701. (message "Problems while trying to load export back-end `%s'"
  702. backend))
  703. ((not (memq backend new-list)) (push backend new-list))))
  704. ;; Set VAR to that list with fixed dependencies.
  705. (set-default var new-list))))
  706. :type '(set :greedy t
  707. (const :tag " ascii Export buffer to ASCII format" ascii)
  708. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  709. (const :tag " html Export buffer to HTML format" html)
  710. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  711. (const :tag " latex Export buffer to LaTeX format" latex)
  712. (const :tag " man Export buffer to MAN format" man)
  713. (const :tag " md Export buffer to Markdown format" md)
  714. (const :tag " odt Export buffer to ODT format" odt)
  715. (const :tag " org Export buffer to Org format" org)
  716. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  717. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  718. (const :tag "C deck Export buffer to deck.js presentations" deck)
  719. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  720. (const :tag "C groff Export buffer to Groff format" groff)
  721. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  722. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  723. (const :tag "C s5 Export buffer to s5 presentations" s5)
  724. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  725. (eval-after-load 'ox
  726. '(dolist (backend org-export-backends)
  727. (condition-case nil (require (intern (format "ox-%s" backend)))
  728. (error (message "Problems while trying to load export back-end `%s'"
  729. backend)))))
  730. (defcustom org-support-shift-select nil
  731. "Non-nil means make shift-cursor commands select text when possible.
  732. \\<org-mode-map>
  733. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  734. start selecting a region, or enlarge regions started in this way.
  735. In Org mode, in special contexts, these same keys are used for
  736. other purposes, important enough to compete with shift selection.
  737. Org tries to balance these needs by supporting `shift-select-mode'
  738. outside these special contexts, under control of this variable.
  739. The default of this variable is nil, to avoid confusing behavior. Shifted
  740. cursor keys will then execute Org commands in the following contexts:
  741. - on a headline, changing TODO state (left/right) and priority (up/down)
  742. - on a time stamp, changing the time
  743. - in a plain list item, changing the bullet type
  744. - in a property definition line, switching between allowed values
  745. - in the BEGIN line of a clock table (changing the time block).
  746. Outside these contexts, the commands will throw an error.
  747. When this variable is t and the cursor is not in a special
  748. context, Org mode will support shift-selection for making and
  749. enlarging regions. To make this more effective, the bullet
  750. cycling will no longer happen anywhere in an item line, but only
  751. if the cursor is exactly on the bullet.
  752. If you set this variable to the symbol `always', then the keys
  753. will not be special in headlines, property lines, and item lines,
  754. to make shift selection work there as well. If this is what you
  755. want, you can use the following alternative commands:
  756. `\\[org-todo]' and `\\[org-priority]' \
  757. to change TODO state and priority,
  758. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  759. can be used to switch TODO sets,
  760. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  761. and properties can be edited by hand or in column view.
  762. However, when the cursor is on a timestamp, shift-cursor commands
  763. will still edit the time stamp - this is just too good to give up."
  764. :group 'org
  765. :type '(choice
  766. (const :tag "Never" nil)
  767. (const :tag "When outside special context" t)
  768. (const :tag "Everywhere except timestamps" always)))
  769. (defcustom org-loop-over-headlines-in-active-region nil
  770. "Shall some commands act upon headlines in the active region?
  771. When set to t, some commands will be performed in all headlines
  772. within the active region.
  773. When set to `start-level', some commands will be performed in all
  774. headlines within the active region, provided that these headlines
  775. are of the same level than the first one.
  776. When set to a string, those commands will be performed on the
  777. matching headlines within the active region. Such string must be
  778. a tags/property/todo match as it is used in the agenda tags view.
  779. The list of commands is: `org-schedule', `org-deadline',
  780. `org-todo', `org-set-tags-command', `org-archive-subtree',
  781. `org-archive-set-tag', `org-toggle-archive-tag' and
  782. `org-archive-to-archive-sibling'. The archiving commands skip
  783. already archived entries."
  784. :type '(choice (const :tag "Don't loop" nil)
  785. (const :tag "All headlines in active region" t)
  786. (const :tag "In active region, headlines at the same level than the first one" start-level)
  787. (string :tag "Tags/Property/Todo matcher"))
  788. :version "24.1"
  789. :group 'org-todo
  790. :group 'org-archive)
  791. (defcustom org-startup-folded t
  792. "Non-nil means entering Org mode will switch to OVERVIEW.
  793. This can also be configured on a per-file basis by adding one of
  794. the following lines anywhere in the buffer:
  795. #+STARTUP: fold (or `overview', this is equivalent)
  796. #+STARTUP: nofold (or `showall', this is equivalent)
  797. #+STARTUP: content
  798. #+STARTUP: showeverything
  799. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  800. to ignore this option when Org opens agenda files for the first
  801. time."
  802. :group 'org-startup
  803. :type '(choice
  804. (const :tag "nofold: show all" nil)
  805. (const :tag "fold: overview" t)
  806. (const :tag "content: all headlines" content)
  807. (const :tag "show everything, even drawers" showeverything)))
  808. (defcustom org-startup-truncated t
  809. "Non-nil means entering Org mode will set `truncate-lines'.
  810. This is useful since some lines containing links can be very long and
  811. uninteresting. Also tables look terrible when wrapped.
  812. The variable `org-startup-truncated' allows to configure
  813. truncation for Org mode different to the other modes that use the
  814. variable `truncate-lines' and as a shortcut instead of putting
  815. the variable `truncate-lines' into the `org-mode-hook'. If one
  816. wants to configure truncation for Org mode not statically but
  817. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  818. the variable `truncate-lines' has to be used because in such a
  819. case it is too late to set the variable `org-startup-truncated'."
  820. :group 'org-startup
  821. :type 'boolean)
  822. (defcustom org-startup-indented nil
  823. "Non-nil means turn on `org-indent-mode' on startup.
  824. This can also be configured on a per-file basis by adding one of
  825. the following lines anywhere in the buffer:
  826. #+STARTUP: indent
  827. #+STARTUP: noindent"
  828. :group 'org-structure
  829. :type '(choice
  830. (const :tag "Not" nil)
  831. (const :tag "Globally (slow on startup in large files)" t)))
  832. (defcustom org-use-sub-superscripts t
  833. "Non-nil means interpret \"_\" and \"^\" for display.
  834. If you want to control how Org exports those characters, see
  835. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  836. used to be an alias for `org-export-with-sub-superscripts' in
  837. Org <8.0, it is not anymore.
  838. When this option is turned on, you can use TeX-like syntax for
  839. sub- and superscripts within the buffer. Several characters after
  840. \"_\" or \"^\" will be considered as a single item - so grouping
  841. with {} is normally not needed. For example, the following things
  842. will be parsed as single sub- or superscripts:
  843. 10^24 or 10^tau several digits will be considered 1 item.
  844. 10^-12 or 10^-tau a leading sign with digits or a word
  845. x^2-y^3 will be read as x^2 - y^3, because items are
  846. terminated by almost any nonword/nondigit char.
  847. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  848. Still, ambiguity is possible. So when in doubt, use {} to enclose
  849. the sub/superscript. If you set this variable to the symbol `{}',
  850. the braces are *required* in order to trigger interpretations as
  851. sub/superscript. This can be helpful in documents that need \"_\"
  852. frequently in plain text."
  853. :group 'org-startup
  854. :version "24.4"
  855. :package-version '(Org . "8.0")
  856. :type '(choice
  857. (const :tag "Always interpret" t)
  858. (const :tag "Only with braces" {})
  859. (const :tag "Never interpret" nil)))
  860. (defcustom org-startup-with-beamer-mode nil
  861. "Non-nil means turn on `org-beamer-mode' on startup.
  862. This can also be configured on a per-file basis by adding one of
  863. the following lines anywhere in the buffer:
  864. #+STARTUP: beamer"
  865. :group 'org-startup
  866. :version "24.1"
  867. :type 'boolean)
  868. (defcustom org-startup-align-all-tables nil
  869. "Non-nil means align all tables when visiting a file.
  870. This can also be configured on a per-file basis by adding one of
  871. the following lines anywhere in the buffer:
  872. #+STARTUP: align
  873. #+STARTUP: noalign"
  874. :group 'org-startup
  875. :type 'boolean)
  876. (defcustom org-startup-shrink-all-tables nil
  877. "Non-nil means shrink all table columns with a width cookie.
  878. This can also be configured on a per-file basis by adding one of
  879. the following lines anywhere in the buffer:
  880. #+STARTUP: shrink"
  881. :group 'org-startup
  882. :type 'boolean
  883. :version "27.1"
  884. :package-version '(Org . "9.2")
  885. :safe #'booleanp)
  886. (defcustom org-startup-with-inline-images nil
  887. "Non-nil means show inline images when loading a new Org file.
  888. This can also be configured on a per-file basis by adding one of
  889. the following lines anywhere in the buffer:
  890. #+STARTUP: inlineimages
  891. #+STARTUP: noinlineimages"
  892. :group 'org-startup
  893. :version "24.1"
  894. :type 'boolean)
  895. (defcustom org-startup-with-latex-preview nil
  896. "Non-nil means preview LaTeX fragments when loading a new Org file.
  897. This can also be configured on a per-file basis by adding one of
  898. the following lines anywhere in the buffer:
  899. #+STARTUP: latexpreview
  900. #+STARTUP: nolatexpreview"
  901. :group 'org-startup
  902. :version "24.4"
  903. :package-version '(Org . "8.0")
  904. :type 'boolean)
  905. (defcustom org-insert-mode-line-in-empty-file nil
  906. "Non-nil means insert the first line setting Org mode in empty files.
  907. When the function `org-mode' is called interactively in an empty file, this
  908. normally means that the file name does not automatically trigger Org mode.
  909. To ensure that the file will always be in Org mode in the future, a
  910. line enforcing Org mode will be inserted into the buffer, if this option
  911. has been set."
  912. :group 'org-startup
  913. :type 'boolean)
  914. (defcustom org-ellipsis nil
  915. "The ellipsis to use in the Org mode outline.
  916. When nil, just use the standard three dots. When a non-empty string,
  917. use that string instead.
  918. The change affects only Org mode (which will then use its own display table).
  919. Changing this requires executing `\\[org-mode]' in a buffer to become
  920. effective."
  921. :group 'org-startup
  922. :type '(choice (const :tag "Default" nil)
  923. (string :tag "String" :value "...#"))
  924. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  925. (defvar org-display-table nil
  926. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  927. (defgroup org-keywords nil
  928. "Keywords in Org mode."
  929. :tag "Org Keywords"
  930. :group 'org)
  931. (defcustom org-closed-keep-when-no-todo nil
  932. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  933. :group 'org-todo
  934. :group 'org-keywords
  935. :version "24.4"
  936. :package-version '(Org . "8.0")
  937. :type 'boolean)
  938. (defgroup org-structure nil
  939. "Options concerning the general structure of Org files."
  940. :tag "Org Structure"
  941. :group 'org)
  942. (defgroup org-reveal-location nil
  943. "Options about how to make context of a location visible."
  944. :tag "Org Reveal Location"
  945. :group 'org-structure)
  946. (defcustom org-show-context-detail '((agenda . local)
  947. (bookmark-jump . lineage)
  948. (isearch . lineage)
  949. (default . ancestors))
  950. "Alist between context and visibility span when revealing a location.
  951. \\<org-mode-map>Some actions may move point into invisible
  952. locations. As a consequence, Org always expose a neighborhood
  953. around point. How much is shown depends on the initial action,
  954. or context. Valid contexts are
  955. agenda when exposing an entry from the agenda
  956. org-goto when using the command `org-goto' (`\\[org-goto]')
  957. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  958. tags-tree when constructing a sparse tree based on tags matches
  959. link-search when exposing search matches associated with a link
  960. mark-goto when exposing the jump goal of a mark
  961. bookmark-jump when exposing a bookmark location
  962. isearch when exiting from an incremental search
  963. default default for all contexts not set explicitly
  964. Allowed visibility spans are
  965. minimal show current headline; if point is not on headline,
  966. also show entry
  967. local show current headline, entry and next headline
  968. ancestors show current headline and its direct ancestors; if
  969. point is not on headline, also show entry
  970. lineage show current headline, its direct ancestors and all
  971. their children; if point is not on headline, also show
  972. entry and first child
  973. tree show current headline, its direct ancestors and all
  974. their children; if point is not on headline, also show
  975. entry and all children
  976. canonical show current headline, its direct ancestors along with
  977. their entries and children; if point is not located on
  978. the headline, also show current entry and all children
  979. As special cases, a nil or t value means show all contexts in
  980. `minimal' or `canonical' view, respectively.
  981. Some views can make displayed information very compact, but also
  982. make it harder to edit the location of the match. In such
  983. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  984. more context."
  985. :group 'org-reveal-location
  986. :version "26.1"
  987. :package-version '(Org . "9.0")
  988. :type '(choice
  989. (const :tag "Canonical" t)
  990. (const :tag "Minimal" nil)
  991. (repeat :greedy t :tag "Individual contexts"
  992. (cons
  993. (choice :tag "Context"
  994. (const agenda)
  995. (const org-goto)
  996. (const occur-tree)
  997. (const tags-tree)
  998. (const link-search)
  999. (const mark-goto)
  1000. (const bookmark-jump)
  1001. (const isearch)
  1002. (const default))
  1003. (choice :tag "Detail level"
  1004. (const minimal)
  1005. (const local)
  1006. (const ancestors)
  1007. (const lineage)
  1008. (const tree)
  1009. (const canonical))))))
  1010. (defcustom org-indirect-buffer-display 'other-window
  1011. "How should indirect tree buffers be displayed?
  1012. This applies to indirect buffers created with the commands
  1013. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1014. Valid values are:
  1015. current-window Display in the current window
  1016. other-window Just display in another window.
  1017. dedicated-frame Create one new frame, and re-use it each time.
  1018. new-frame Make a new frame each time. Note that in this case
  1019. previously-made indirect buffers are kept, and you need to
  1020. kill these buffers yourself."
  1021. :group 'org-structure
  1022. :group 'org-agenda-windows
  1023. :type '(choice
  1024. (const :tag "In current window" current-window)
  1025. (const :tag "In current frame, other window" other-window)
  1026. (const :tag "Each time a new frame" new-frame)
  1027. (const :tag "One dedicated frame" dedicated-frame)))
  1028. (defconst org-file-apps-gnu
  1029. '((remote . emacs)
  1030. (system . mailcap)
  1031. (t . mailcap))
  1032. "Default file applications on a UNIX or GNU/Linux system.
  1033. See `org-file-apps'.")
  1034. (defconst org-file-apps-macos
  1035. '((remote . emacs)
  1036. (system . "open %s")
  1037. ("ps.gz" . "gv %s")
  1038. ("eps.gz" . "gv %s")
  1039. ("dvi" . "xdvi %s")
  1040. ("fig" . "xfig %s")
  1041. (t . "open %s"))
  1042. "Default file applications on a macOS system.
  1043. The system \"open\" is known as a default, but we use X11 applications
  1044. for some files for which the OS does not have a good default.
  1045. See `org-file-apps'.")
  1046. (defconst org-file-apps-windowsnt
  1047. (list '(remote . emacs)
  1048. (cons 'system (lambda (file _path)
  1049. (with-no-warnings (w32-shell-execute "open" file))))
  1050. (cons t (lambda (file _path)
  1051. (with-no-warnings (w32-shell-execute "open" file)))))
  1052. "Default file applications on a Windows NT system.
  1053. The system \"open\" is used for most files.
  1054. See `org-file-apps'.")
  1055. (defcustom org-file-apps
  1056. '((auto-mode . emacs)
  1057. ("\\.mm\\'" . default)
  1058. ("\\.x?html?\\'" . default)
  1059. ("\\.pdf\\'" . default))
  1060. "External applications for opening `file:path' items in a document.
  1061. \\<org-mode-map>
  1062. Org mode uses system defaults for different file types, but
  1063. you can use this variable to set the application for a given file
  1064. extension. The entries in this list are cons cells where the car identifies
  1065. files and the cdr the corresponding command.
  1066. Possible values for the file identifier are:
  1067. \"string\" A string as a file identifier can be interpreted in different
  1068. ways, depending on its contents:
  1069. - Alphanumeric characters only:
  1070. Match links with this file extension.
  1071. Example: (\"pdf\" . \"evince %s\")
  1072. to open PDFs with evince.
  1073. - Regular expression: Match links where the
  1074. filename matches the regexp. If you want to
  1075. use groups here, use shy groups.
  1076. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1077. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1078. to open *.html and *.xhtml with firefox.
  1079. - Regular expression which contains (non-shy) groups:
  1080. Match links where the whole link, including \"::\", and
  1081. anything after that, matches the regexp.
  1082. In a custom command string, %1, %2, etc. are replaced with
  1083. the parts of the link that were matched by the groups.
  1084. For backwards compatibility, if a command string is given
  1085. that does not use any of the group matches, this case is
  1086. handled identically to the second one (i.e. match against
  1087. file name only).
  1088. In a custom function, you can access the group matches with
  1089. (match-string n link).
  1090. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1091. \"evince -p %1 %s\")
  1092. to open [[file:document.pdf::5]] with evince at page 5.
  1093. `directory' Matches a directory
  1094. `remote' Matches a remote file, accessible through tramp or efs.
  1095. Remote files most likely should be visited through Emacs
  1096. because external applications cannot handle such paths.
  1097. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1098. so all files Emacs knows how to handle. Using this with
  1099. command `emacs' will open most files in Emacs. Beware that this
  1100. will also open html files inside Emacs, unless you add
  1101. (\"html\" . default) to the list as well.
  1102. `system' The system command to open files, like `open' on Windows
  1103. and macOS, and mailcap under GNU/Linux. This is the command
  1104. that will be selected if you call `org-open-at-point' with a
  1105. double prefix argument (`\\[universal-argument] \
  1106. \\[universal-argument] \\[org-open-at-point]').
  1107. t Default for files not matched by any of the other options.
  1108. Possible values for the command are:
  1109. `emacs' The file will be visited by the current Emacs process.
  1110. `default' Use the default application for this file type, which is the
  1111. association for t in the list, most likely in the system-specific
  1112. part. This can be used to overrule an unwanted setting in the
  1113. system-specific variable.
  1114. `system' Use the system command for opening files, like \"open\".
  1115. This command is specified by the entry whose car is `system'.
  1116. Most likely, the system-specific version of this variable
  1117. does define this command, but you can overrule/replace it
  1118. here.
  1119. `mailcap' Use command specified in the mailcaps.
  1120. string A command to be executed by a shell; %s will be replaced
  1121. by the path to the file.
  1122. function A Lisp function, which will be called with two arguments:
  1123. the file path and the original link string, without the
  1124. \"file:\" prefix.
  1125. For more examples, see the system specific constants
  1126. `org-file-apps-macos'
  1127. `org-file-apps-windowsnt'
  1128. `org-file-apps-gnu'."
  1129. :group 'org
  1130. :type '(repeat
  1131. (cons (choice :value ""
  1132. (string :tag "Extension")
  1133. (const :tag "System command to open files" system)
  1134. (const :tag "Default for unrecognized files" t)
  1135. (const :tag "Remote file" remote)
  1136. (const :tag "Links to a directory" directory)
  1137. (const :tag "Any files that have Emacs modes"
  1138. auto-mode))
  1139. (choice :value ""
  1140. (const :tag "Visit with Emacs" emacs)
  1141. (const :tag "Use default" default)
  1142. (const :tag "Use the system command" system)
  1143. (string :tag "Command")
  1144. (function :tag "Function")))))
  1145. (defcustom org-open-non-existing-files nil
  1146. "Non-nil means `org-open-file' opens non-existing files.
  1147. When nil, an error is thrown.
  1148. This variable applies only to external applications because they
  1149. might choke on non-existing files. If the link is to a file that
  1150. will be opened in Emacs, the variable is ignored."
  1151. :group 'org
  1152. :type 'boolean
  1153. :safe #'booleanp)
  1154. (defcustom org-open-directory-means-index-dot-org nil
  1155. "When non-nil a link to a directory really means to \"index.org\".
  1156. When nil, following a directory link runs Dired or opens
  1157. a finder/explorer window on that directory."
  1158. :group 'org
  1159. :type 'boolean
  1160. :safe #'booleanp)
  1161. (defcustom org-bookmark-names-plist
  1162. '(:last-capture "org-capture-last-stored"
  1163. :last-refile "org-refile-last-stored"
  1164. :last-capture-marker "org-capture-last-stored-marker")
  1165. "Names for bookmarks automatically set by some Org commands.
  1166. This can provide strings as names for a number of bookmarks Org sets
  1167. automatically. The following keys are currently implemented:
  1168. :last-capture
  1169. :last-capture-marker
  1170. :last-refile
  1171. When a key does not show up in the property list, the corresponding bookmark
  1172. is not set."
  1173. :group 'org-structure
  1174. :type 'plist)
  1175. (defgroup org-cycle nil
  1176. "Options concerning visibility cycling in Org mode."
  1177. :tag "Org Cycle"
  1178. :group 'org-structure)
  1179. (defcustom org-cycle-skip-children-state-if-no-children t
  1180. "Non-nil means skip CHILDREN state in entries that don't have any."
  1181. :group 'org-cycle
  1182. :type 'boolean)
  1183. (defcustom org-cycle-max-level nil
  1184. "Maximum level which should still be subject to visibility cycling.
  1185. Levels higher than this will, for cycling, be treated as text, not a headline.
  1186. When `org-odd-levels-only' is set, a value of N in this variable actually
  1187. means 2N-1 stars as the limiting headline.
  1188. When nil, cycle all levels.
  1189. Note that the limiting level of cycling is also influenced by
  1190. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1191. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1192. than its value."
  1193. :group 'org-cycle
  1194. :type '(choice
  1195. (const :tag "No limit" nil)
  1196. (integer :tag "Maximum level")))
  1197. (defcustom org-hide-block-startup nil
  1198. "Non-nil means entering Org mode will fold all blocks.
  1199. This can also be set in on a per-file basis with
  1200. #+STARTUP: hideblocks
  1201. #+STARTUP: showblocks"
  1202. :group 'org-startup
  1203. :group 'org-cycle
  1204. :type 'boolean)
  1205. (defcustom org-cycle-global-at-bob nil
  1206. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1207. This makes it possible to do global cycling without having to use `S-TAB'
  1208. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1209. line of the buffer
  1210. must not be a headline -- it may be empty or some other text.
  1211. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1212. sure the cursor stays at the beginning of the buffer.
  1213. When this option is nil, don't do anything special at the beginning of
  1214. the buffer."
  1215. :group 'org-cycle
  1216. :type 'boolean)
  1217. (defcustom org-cycle-level-after-item/entry-creation t
  1218. "Non-nil means cycle entry level or item indentation in new empty entries.
  1219. When the cursor is at the end of an empty headline, i.e., with only stars
  1220. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1221. and then all possible ancestor states, before returning to the original state.
  1222. This makes data entry extremely fast: M-RET to create a new headline,
  1223. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1224. When the cursor is at the end of an empty plain list item, one TAB will
  1225. make it a subitem, two or more tabs will back up to make this an item
  1226. higher up in the item hierarchy."
  1227. :group 'org-cycle
  1228. :type 'boolean)
  1229. (defcustom org-cycle-emulate-tab t
  1230. "Where should `org-cycle' emulate TAB.
  1231. nil Never
  1232. white Only in completely white lines
  1233. whitestart Only at the beginning of lines, before the first non-white char
  1234. t Everywhere except in headlines
  1235. exc-hl-bol Everywhere except at the start of a headline
  1236. If TAB is used in a place where it does not emulate TAB, the current subtree
  1237. visibility is cycled."
  1238. :group 'org-cycle
  1239. :type '(choice (const :tag "Never" nil)
  1240. (const :tag "Only in completely white lines" white)
  1241. (const :tag "Before first char in a line" whitestart)
  1242. (const :tag "Everywhere except in headlines" t)
  1243. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1244. (defcustom org-cycle-separator-lines 2
  1245. "Number of empty lines needed to keep an empty line between collapsed trees.
  1246. If you leave an empty line between the end of a subtree and the following
  1247. headline, this empty line is hidden when the subtree is folded.
  1248. Org mode will leave (exactly) one empty line visible if the number of
  1249. empty lines is equal or larger to the number given in this variable.
  1250. So the default 2 means at least 2 empty lines after the end of a subtree
  1251. are needed to produce free space between a collapsed subtree and the
  1252. following headline.
  1253. If the number is negative, and the number of empty lines is at least -N,
  1254. all empty lines are shown.
  1255. Special case: when 0, never leave empty lines in collapsed view."
  1256. :group 'org-cycle
  1257. :type 'integer)
  1258. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1259. (defcustom org-pre-cycle-hook nil
  1260. "Hook that is run before visibility cycling is happening.
  1261. The function(s) in this hook must accept a single argument which indicates
  1262. the new state that will be set right after running this hook. The
  1263. argument is a symbol. Before a global state change, it can have the values
  1264. `overview', `content', or `all'. Before a local state change, it can have
  1265. the values `folded', `children', or `subtree'."
  1266. :group 'org-cycle
  1267. :type 'hook)
  1268. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1269. org-cycle-show-empty-lines
  1270. org-optimize-window-after-visibility-change)
  1271. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1272. The function(s) in this hook must accept a single argument which indicates
  1273. the new state that was set by the most recent `org-cycle' command. The
  1274. argument is a symbol. After a global state change, it can have the values
  1275. `overview', `contents', or `all'. After a local state change, it can have
  1276. the values `folded', `children', or `subtree'."
  1277. :group 'org-cycle
  1278. :type 'hook
  1279. :version "26.1"
  1280. :package-version '(Org . "8.3"))
  1281. (defgroup org-edit-structure nil
  1282. "Options concerning structure editing in Org mode."
  1283. :tag "Org Edit Structure"
  1284. :group 'org-structure)
  1285. (defcustom org-odd-levels-only nil
  1286. "Non-nil means skip even levels and only use odd levels for the outline.
  1287. This has the effect that two stars are being added/taken away in
  1288. promotion/demotion commands. It also influences how levels are
  1289. handled by the exporters.
  1290. Changing it requires restart of `font-lock-mode' to become effective
  1291. for fontification also in regions already fontified.
  1292. You may also set this on a per-file basis by adding one of the following
  1293. lines to the buffer:
  1294. #+STARTUP: odd
  1295. #+STARTUP: oddeven"
  1296. :group 'org-edit-structure
  1297. :group 'org-appearance
  1298. :type 'boolean)
  1299. (defcustom org-adapt-indentation t
  1300. "Non-nil means adapt indentation to outline node level.
  1301. When this variable is set, Org assumes that you write outlines by
  1302. indenting text in each node to align with the headline (after the
  1303. stars). The following issues are influenced by this variable:
  1304. - The indentation is increased by one space in a demotion
  1305. command, and decreased by one in a promotion command. However,
  1306. in the latter case, if shifting some line in the entry body
  1307. would alter document structure (e.g., insert a new headline),
  1308. indentation is not changed at all.
  1309. - Property drawers and planning information is inserted indented
  1310. when this variable is set. When nil, they will not be indented.
  1311. - TAB indents a line relative to current level. The lines below
  1312. a headline will be indented when this variable is set.
  1313. Note that this is all about true indentation, by adding and
  1314. removing space characters. See also \"org-indent.el\" which does
  1315. level-dependent indentation in a virtual way, i.e. at display
  1316. time in Emacs."
  1317. :group 'org-edit-structure
  1318. :type 'boolean
  1319. :safe #'booleanp)
  1320. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1321. (defcustom org-special-ctrl-a/e nil
  1322. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1323. When t, `C-a' will bring back the cursor to the beginning of the
  1324. headline text, i.e. after the stars and after a possible TODO
  1325. keyword. In an item, this will be the position after bullet and
  1326. check-box, if any. When the cursor is already at that position,
  1327. another `C-a' will bring it to the beginning of the line.
  1328. `C-e' will jump to the end of the headline, ignoring the presence
  1329. of tags in the headline. A second `C-e' will then jump to the
  1330. true end of the line, after any tags. This also means that, when
  1331. this variable is non-nil, `C-e' also will never jump beyond the
  1332. end of the heading of a folded section, i.e. not after the
  1333. ellipses.
  1334. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1335. normally, going to the true line boundary first. Only a directly
  1336. following, identical keypress will bring the cursor to the
  1337. special positions.
  1338. This may also be a cons cell where the behavior for `C-a' and
  1339. `C-e' is set separately."
  1340. :group 'org-edit-structure
  1341. :type '(choice
  1342. (const :tag "off" nil)
  1343. (const :tag "on: after stars/bullet and before tags first" t)
  1344. (const :tag "reversed: true line boundary first" reversed)
  1345. (cons :tag "Set C-a and C-e separately"
  1346. (choice :tag "Special C-a"
  1347. (const :tag "off" nil)
  1348. (const :tag "on: after stars/bullet first" t)
  1349. (const :tag "reversed: before stars/bullet first" reversed))
  1350. (choice :tag "Special C-e"
  1351. (const :tag "off" nil)
  1352. (const :tag "on: before tags first" t)
  1353. (const :tag "reversed: after tags first" reversed)))))
  1354. (defcustom org-special-ctrl-k nil
  1355. "Non-nil means `C-k' will behave specially in headlines.
  1356. When nil, `C-k' will call the default `kill-line' command.
  1357. When t, the following will happen while the cursor is in the headline:
  1358. - When the cursor is at the beginning of a headline, kill the entire
  1359. line and possible the folded subtree below the line.
  1360. - When in the middle of the headline text, kill the headline up to the tags.
  1361. - When after the headline text, kill the tags."
  1362. :group 'org-edit-structure
  1363. :type 'boolean)
  1364. (defcustom org-ctrl-k-protect-subtree nil
  1365. "Non-nil means, do not delete a hidden subtree with C-k.
  1366. When set to the symbol `error', simply throw an error when C-k is
  1367. used to kill (part-of) a headline that has hidden text behind it.
  1368. Any other non-nil value will result in a query to the user, if it is
  1369. OK to kill that hidden subtree. When nil, kill without remorse."
  1370. :group 'org-edit-structure
  1371. :version "24.1"
  1372. :type '(choice
  1373. (const :tag "Do not protect hidden subtrees" nil)
  1374. (const :tag "Protect hidden subtrees with a security query" t)
  1375. (const :tag "Never kill a hidden subtree with C-k" error)))
  1376. (defcustom org-special-ctrl-o t
  1377. "Non-nil means, make `C-o' insert a row in tables."
  1378. :group 'org-edit-structure
  1379. :type 'boolean)
  1380. (defcustom org-catch-invisible-edits nil
  1381. "Check if in invisible region before inserting or deleting a character.
  1382. Valid values are:
  1383. nil Do not check, so just do invisible edits.
  1384. error Throw an error and do nothing.
  1385. show Make point visible, and do the requested edit.
  1386. show-and-error Make point visible, then throw an error and abort the edit.
  1387. smart Make point visible, and do insertion/deletion if it is
  1388. adjacent to visible text and the change feels predictable.
  1389. Never delete a previously invisible character or add in the
  1390. middle or right after an invisible region. Basically, this
  1391. allows insertion and backward-delete right before ellipses.
  1392. FIXME: maybe in this case we should not even show?"
  1393. :group 'org-edit-structure
  1394. :version "24.1"
  1395. :type '(choice
  1396. (const :tag "Do not check" nil)
  1397. (const :tag "Throw error when trying to edit" error)
  1398. (const :tag "Unhide, but do not do the edit" show-and-error)
  1399. (const :tag "Show invisible part and do the edit" show)
  1400. (const :tag "Be smart and do the right thing" smart)))
  1401. (defcustom org-yank-folded-subtrees t
  1402. "Non-nil means when yanking subtrees, fold them.
  1403. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1404. it starts with a heading and all other headings in it are either children
  1405. or siblings, then fold all the subtrees. However, do this only if no
  1406. text after the yank would be swallowed into a folded tree by this action."
  1407. :group 'org-edit-structure
  1408. :type 'boolean)
  1409. (defcustom org-yank-adjusted-subtrees nil
  1410. "Non-nil means when yanking subtrees, adjust the level.
  1411. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1412. this function for details."
  1413. :group 'org-edit-structure
  1414. :type 'boolean)
  1415. (defcustom org-M-RET-may-split-line '((default . t))
  1416. "Non-nil means M-RET will split the line at the cursor position.
  1417. When nil, it will go to the end of the line before making a
  1418. new line.
  1419. You may also set this option in a different way for different
  1420. contexts. Valid contexts are:
  1421. headline when creating a new headline
  1422. item when creating a new item
  1423. table in a table field
  1424. default the value to be used for all contexts not explicitly
  1425. customized"
  1426. :group 'org-structure
  1427. :group 'org-table
  1428. :type '(choice
  1429. (const :tag "Always" t)
  1430. (const :tag "Never" nil)
  1431. (repeat :greedy t :tag "Individual contexts"
  1432. (cons
  1433. (choice :tag "Context"
  1434. (const headline)
  1435. (const item)
  1436. (const table)
  1437. (const default))
  1438. (boolean)))))
  1439. (defcustom org-insert-heading-respect-content nil
  1440. "Non-nil means insert new headings after the current subtree.
  1441. \\<org-mode-map>
  1442. When nil, the new heading is created directly after the current line.
  1443. The commands `\\[org-insert-heading-respect-content]' and \
  1444. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1445. for the duration of the command."
  1446. :group 'org-structure
  1447. :type 'boolean)
  1448. (defcustom org-blank-before-new-entry '((heading . auto)
  1449. (plain-list-item . auto))
  1450. "Should `org-insert-heading' leave a blank line before new heading/item?
  1451. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1452. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1453. which case Org will look at the surrounding headings/items and try to
  1454. make an intelligent decision whether to insert a blank line or not."
  1455. :group 'org-edit-structure
  1456. :type '(list
  1457. (cons (const heading)
  1458. (choice (const :tag "Never" nil)
  1459. (const :tag "Always" t)
  1460. (const :tag "Auto" auto)))
  1461. (cons (const plain-list-item)
  1462. (choice (const :tag "Never" nil)
  1463. (const :tag "Always" t)
  1464. (const :tag "Auto" auto)))))
  1465. (defcustom org-insert-heading-hook nil
  1466. "Hook being run after inserting a new heading."
  1467. :group 'org-edit-structure
  1468. :type 'hook)
  1469. (defcustom org-enable-fixed-width-editor t
  1470. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1471. This currently only means they are never auto-wrapped.
  1472. When nil, such lines will be treated like ordinary lines."
  1473. :group 'org-edit-structure
  1474. :type 'boolean)
  1475. (defgroup org-sparse-trees nil
  1476. "Options concerning sparse trees in Org mode."
  1477. :tag "Org Sparse Trees"
  1478. :group 'org-structure)
  1479. (defcustom org-highlight-sparse-tree-matches t
  1480. "Non-nil means highlight all matches that define a sparse tree.
  1481. The highlights will automatically disappear the next time the buffer is
  1482. changed by an edit command."
  1483. :group 'org-sparse-trees
  1484. :type 'boolean)
  1485. (defcustom org-remove-highlights-with-change t
  1486. "Non-nil means any change to the buffer will remove temporary highlights.
  1487. \\<org-mode-map>\
  1488. Such highlights are created by `org-occur' and `org-clock-display'.
  1489. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1490. to get rid of the highlights.
  1491. The highlights created by `org-latex-preview' always need
  1492. `\\[org-latex-preview]' to be removed."
  1493. :group 'org-sparse-trees
  1494. :group 'org-time
  1495. :type 'boolean)
  1496. (defcustom org-occur-case-fold-search t
  1497. "Non-nil means `org-occur' should be case-insensitive.
  1498. If set to `smart' the search will be case-insensitive only if it
  1499. doesn't specify any upper case character."
  1500. :group 'org-sparse-trees
  1501. :version "26.1"
  1502. :type '(choice
  1503. (const :tag "Case-sensitive" nil)
  1504. (const :tag "Case-insensitive" t)
  1505. (const :tag "Case-insensitive for lower case searches only" smart)))
  1506. (defcustom org-occur-hook '(org-first-headline-recenter)
  1507. "Hook that is run after `org-occur' has constructed a sparse tree.
  1508. This can be used to recenter the window to show as much of the structure
  1509. as possible."
  1510. :group 'org-sparse-trees
  1511. :type 'hook)
  1512. (defcustom org-self-insert-cluster-for-undo nil
  1513. "Non-nil means cluster self-insert commands for undo when possible.
  1514. If this is set, then, like in the Emacs command loop, 20 consecutive
  1515. characters will be undone together.
  1516. This is configurable, because there is some impact on typing performance."
  1517. :group 'org-table
  1518. :type 'boolean)
  1519. (defvaralias 'org-activate-links 'org-highlight-links)
  1520. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1521. "Types of links that should be highlighted in Org files.
  1522. This is a list of symbols, each one of them leading to the
  1523. highlighting of a certain link type.
  1524. You can still open links that are not highlighted.
  1525. In principle, it does not hurt to turn on highlighting for all
  1526. link types. There may be a small gain when turning off unused
  1527. link types. The types are:
  1528. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1529. angle Links in angular brackets that may contain whitespace like
  1530. <bbdb:Carsten Dominik>.
  1531. plain Plain links in normal text, no whitespace, like http://google.com.
  1532. radio Text that is matched by a radio target, see manual for details.
  1533. tag Tag settings in a headline (link to tag search).
  1534. date Time stamps (link to calendar).
  1535. footnote Footnote labels.
  1536. If you set this variable during an Emacs session, use `org-mode-restart'
  1537. in the Org buffer so that the change takes effect."
  1538. :group 'org-appearance
  1539. :type '(set :greedy t
  1540. (const :tag "Double bracket links" bracket)
  1541. (const :tag "Angular bracket links" angle)
  1542. (const :tag "Plain text links" plain)
  1543. (const :tag "Radio target matches" radio)
  1544. (const :tag "Tags" tag)
  1545. (const :tag "Timestamps" date)
  1546. (const :tag "Footnotes" footnote)))
  1547. (defcustom org-mark-ring-length 4
  1548. "Number of different positions to be recorded in the ring.
  1549. Changing this requires a restart of Emacs to work correctly."
  1550. :group 'org-link-follow
  1551. :type 'integer)
  1552. (defgroup org-refile nil
  1553. "Options concerning refiling entries in Org mode."
  1554. :tag "Org Refile"
  1555. :group 'org)
  1556. (defcustom org-directory "~/org"
  1557. "Directory with Org files.
  1558. This is just a default location to look for Org files. There is no need
  1559. at all to put your files into this directory. It is used in the
  1560. following situations:
  1561. 1. When a capture template specifies a target file that is not an
  1562. absolute path. The path will then be interpreted relative to
  1563. `org-directory'
  1564. 2. When the value of variable `org-agenda-files' is a single file, any
  1565. relative paths in this file will be taken as relative to
  1566. `org-directory'."
  1567. :group 'org-refile
  1568. :group 'org-capture
  1569. :type 'directory)
  1570. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1571. "Default target for storing notes.
  1572. Used as a fall back file for org-capture.el, for templates that
  1573. do not specify a target file."
  1574. :group 'org-refile
  1575. :group 'org-capture
  1576. :type 'file)
  1577. (defcustom org-reverse-note-order nil
  1578. "Non-nil means store new notes at the beginning of a file or entry.
  1579. When nil, new notes will be filed to the end of a file or entry.
  1580. This can also be a list with cons cells of regular expressions that
  1581. are matched against file names, and values."
  1582. :group 'org-capture
  1583. :group 'org-refile
  1584. :type '(choice
  1585. (const :tag "Reverse always" t)
  1586. (const :tag "Reverse never" nil)
  1587. (repeat :tag "By file name regexp"
  1588. (cons regexp boolean))))
  1589. (defcustom org-log-refile nil
  1590. "Information to record when a task is refiled.
  1591. Possible values are:
  1592. nil Don't add anything
  1593. time Add a time stamp to the task
  1594. note Prompt for a note and add it with template `org-log-note-headings'
  1595. This option can also be set with on a per-file-basis with
  1596. #+STARTUP: nologrefile
  1597. #+STARTUP: logrefile
  1598. #+STARTUP: lognoterefile
  1599. You can have local logging settings for a subtree by setting the LOGGING
  1600. property to one or more of these keywords.
  1601. When bulk-refiling, e.g., from the agenda, the value `note' is
  1602. forbidden and will temporarily be changed to `time'."
  1603. :group 'org-refile
  1604. :group 'org-progress
  1605. :version "24.1"
  1606. :type '(choice
  1607. (const :tag "No logging" nil)
  1608. (const :tag "Record timestamp" time)
  1609. (const :tag "Record timestamp with note." note)))
  1610. (defcustom org-refile-targets nil
  1611. "Targets for refiling entries with `\\[org-refile]'.
  1612. This is a list of cons cells. Each cell contains:
  1613. - a specification of the files to be considered, either a list of files,
  1614. or a symbol whose function or variable value will be used to retrieve
  1615. a file name or a list of file names. If you use `org-agenda-files' for
  1616. that, all agenda files will be scanned for targets. Nil means consider
  1617. headings in the current buffer.
  1618. - A specification of how to find candidate refile targets. This may be
  1619. any of:
  1620. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1621. This tag has to be present in all target headlines, inheritance will
  1622. not be considered.
  1623. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1624. todo keyword.
  1625. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1626. headlines that are refiling targets.
  1627. - a cons cell (:level . N). Any headline of level N is considered a target.
  1628. Note that, when `org-odd-levels-only' is set, level corresponds to
  1629. order in hierarchy, not to the number of stars.
  1630. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1631. Note that, when `org-odd-levels-only' is set, level corresponds to
  1632. order in hierarchy, not to the number of stars.
  1633. Each element of this list generates a set of possible targets.
  1634. The union of these sets is presented (with completion) to
  1635. the user by `org-refile'.
  1636. You can set the variable `org-refile-target-verify-function' to a function
  1637. to verify each headline found by the simple criteria above.
  1638. When this variable is nil, all top-level headlines in the current buffer
  1639. are used, equivalent to the value `((nil . (:level . 1))'."
  1640. :group 'org-refile
  1641. :type '(repeat
  1642. (cons
  1643. (choice :value org-agenda-files
  1644. (const :tag "All agenda files" org-agenda-files)
  1645. (const :tag "Current buffer" nil)
  1646. (function) (variable) (file))
  1647. (choice :tag "Identify target headline by"
  1648. (cons :tag "Specific tag" (const :value :tag) (string))
  1649. (cons :tag "TODO keyword" (const :value :todo) (string))
  1650. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1651. (cons :tag "Level number" (const :value :level) (integer))
  1652. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1653. (defcustom org-refile-target-verify-function nil
  1654. "Function to verify if the headline at point should be a refile target.
  1655. The function will be called without arguments, with point at the
  1656. beginning of the headline. It should return t and leave point
  1657. where it is if the headline is a valid target for refiling.
  1658. If the target should not be selected, the function must return nil.
  1659. In addition to this, it may move point to a place from where the search
  1660. should be continued. For example, the function may decide that the entire
  1661. subtree of the current entry should be excluded and move point to the end
  1662. of the subtree."
  1663. :group 'org-refile
  1664. :type '(choice
  1665. (const nil)
  1666. (function)))
  1667. (defcustom org-refile-use-cache nil
  1668. "Non-nil means cache refile targets to speed up the process.
  1669. \\<org-mode-map>\
  1670. The cache for a particular file will be updated automatically when
  1671. the buffer has been killed, or when any of the marker used for flagging
  1672. refile targets no longer points at a live buffer.
  1673. If you have added new entries to a buffer that might themselves be targets,
  1674. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1675. if you find that easier, \
  1676. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1677. \\[org-refile]'."
  1678. :group 'org-refile
  1679. :version "24.1"
  1680. :type 'boolean)
  1681. (defcustom org-refile-use-outline-path nil
  1682. "Non-nil means provide refile targets as paths.
  1683. So a level 3 headline will be available as level1/level2/level3.
  1684. When the value is `file', also include the file name (without directory)
  1685. into the path. In this case, you can also stop the completion after
  1686. the file name, to get entries inserted as top level in the file.
  1687. When `full-file-path', include the full file path.
  1688. When `buffer-name', use the buffer name."
  1689. :group 'org-refile
  1690. :type '(choice
  1691. (const :tag "Not" nil)
  1692. (const :tag "Yes" t)
  1693. (const :tag "Start with file name" file)
  1694. (const :tag "Start with full file path" full-file-path)
  1695. (const :tag "Start with buffer name" buffer-name)))
  1696. (defcustom org-outline-path-complete-in-steps t
  1697. "Non-nil means complete the outline path in hierarchical steps.
  1698. When Org uses the refile interface to select an outline path (see
  1699. `org-refile-use-outline-path'), the completion of the path can be
  1700. done in a single go, or it can be done in steps down the headline
  1701. hierarchy. Going in steps is probably the best if you do not use
  1702. a special completion package like `ido' or `icicles'. However,
  1703. when using these packages, going in one step can be very fast,
  1704. while still showing the whole path to the entry."
  1705. :group 'org-refile
  1706. :type 'boolean)
  1707. (defcustom org-refile-allow-creating-parent-nodes nil
  1708. "Non-nil means allow the creation of new nodes as refile targets.
  1709. New nodes are then created by adding \"/new node name\" to the completion
  1710. of an existing node. When the value of this variable is `confirm',
  1711. new node creation must be confirmed by the user (recommended).
  1712. When nil, the completion must match an existing entry.
  1713. Note that, if the new heading is not seen by the criteria
  1714. listed in `org-refile-targets', multiple instances of the same
  1715. heading would be created by trying again to file under the new
  1716. heading."
  1717. :group 'org-refile
  1718. :type '(choice
  1719. (const :tag "Never" nil)
  1720. (const :tag "Always" t)
  1721. (const :tag "Prompt for confirmation" confirm)))
  1722. (defcustom org-refile-active-region-within-subtree nil
  1723. "Non-nil means also refile active region within a subtree.
  1724. By default `org-refile' doesn't allow refiling regions if they
  1725. don't contain a set of subtrees, but it might be convenient to
  1726. do so sometimes: in that case, the first line of the region is
  1727. converted to a headline before refiling."
  1728. :group 'org-refile
  1729. :version "24.1"
  1730. :type 'boolean)
  1731. (defgroup org-todo nil
  1732. "Options concerning TODO items in Org mode."
  1733. :tag "Org TODO"
  1734. :group 'org)
  1735. (defgroup org-progress nil
  1736. "Options concerning Progress logging in Org mode."
  1737. :tag "Org Progress"
  1738. :group 'org-time)
  1739. (defvar org-todo-interpretation-widgets
  1740. '((:tag "Sequence (cycling hits every state)" sequence)
  1741. (:tag "Type (cycling directly to DONE)" type))
  1742. "The available interpretation symbols for customizing `org-todo-keywords'.
  1743. Interested libraries should add to this list.")
  1744. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1745. "List of TODO entry keyword sequences and their interpretation.
  1746. \\<org-mode-map>This is a list of sequences.
  1747. Each sequence starts with a symbol, either `sequence' or `type',
  1748. indicating if the keywords should be interpreted as a sequence of
  1749. action steps, or as different types of TODO items. The first
  1750. keywords are states requiring action - these states will select a headline
  1751. for inclusion into the global TODO list Org produces. If one of the
  1752. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1753. signify that no further action is necessary. If \"|\" is not found,
  1754. the last keyword is treated as the only DONE state of the sequence.
  1755. The command `\\[org-todo]' cycles an entry through these states, and one
  1756. additional state where no keyword is present. For details about this
  1757. cycling, see the manual.
  1758. TODO keywords and interpretation can also be set on a per-file basis with
  1759. the special #+SEQ_TODO and #+TYP_TODO lines.
  1760. Each keyword can optionally specify a character for fast state selection
  1761. \(in combination with the variable `org-use-fast-todo-selection')
  1762. and specifiers for state change logging, using the same syntax that
  1763. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1764. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1765. indicates to record a time stamp each time this state is selected.
  1766. Each keyword may also specify if a timestamp or a note should be
  1767. recorded when entering or leaving the state, by adding additional
  1768. characters in the parenthesis after the keyword. This looks like this:
  1769. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1770. record only the time of the state change. With X and Y being either
  1771. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1772. Y when leaving the state if and only if the *target* state does not
  1773. define X. You may omit any of the fast-selection key or X or /Y,
  1774. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1775. For backward compatibility, this variable may also be just a list
  1776. of keywords. In this case the interpretation (sequence or type) will be
  1777. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1778. :group 'org-todo
  1779. :group 'org-keywords
  1780. :type '(choice
  1781. (repeat :tag "Old syntax, just keywords"
  1782. (string :tag "Keyword"))
  1783. (repeat :tag "New syntax"
  1784. (cons
  1785. (choice
  1786. :tag "Interpretation"
  1787. ;;Quick and dirty way to see
  1788. ;;`org-todo-interpretations'. This takes the
  1789. ;;place of item arguments
  1790. :convert-widget
  1791. (lambda (widget)
  1792. (widget-put widget
  1793. :args (mapcar
  1794. (lambda (x)
  1795. (widget-convert
  1796. (cons 'const x)))
  1797. org-todo-interpretation-widgets))
  1798. widget))
  1799. (repeat
  1800. (string :tag "Keyword"))))))
  1801. (defvar-local org-todo-keywords-1 nil
  1802. "All TODO and DONE keywords active in a buffer.")
  1803. (defvar org-todo-keywords-for-agenda nil)
  1804. (defvar org-done-keywords-for-agenda nil)
  1805. (defvar org-todo-keyword-alist-for-agenda nil)
  1806. (defvar org-tag-alist-for-agenda nil
  1807. "Alist of all tags from all agenda files.")
  1808. (defvar org-tag-groups-alist-for-agenda nil
  1809. "Alist of all groups tags from all current agenda files.")
  1810. (defvar-local org-tag-groups-alist nil)
  1811. (defvar org-agenda-contributing-files nil)
  1812. (defvar-local org-current-tag-alist nil
  1813. "Alist of all tag groups in current buffer.
  1814. This variable takes into consideration `org-tag-alist',
  1815. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1816. (defvar-local org-not-done-keywords nil)
  1817. (defvar-local org-done-keywords nil)
  1818. (defvar-local org-todo-heads nil)
  1819. (defvar-local org-todo-sets nil)
  1820. (defvar-local org-todo-log-states nil)
  1821. (defvar-local org-todo-kwd-alist nil)
  1822. (defvar-local org-todo-key-alist nil)
  1823. (defvar-local org-todo-key-trigger nil)
  1824. (defcustom org-todo-interpretation 'sequence
  1825. "Controls how TODO keywords are interpreted.
  1826. This variable is in principle obsolete and is only used for
  1827. backward compatibility, if the interpretation of todo keywords is
  1828. not given already in `org-todo-keywords'. See that variable for
  1829. more information."
  1830. :group 'org-todo
  1831. :group 'org-keywords
  1832. :type '(choice (const sequence)
  1833. (const type)))
  1834. (defcustom org-use-fast-todo-selection 'auto
  1835. "\\<org-mode-map>\
  1836. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1837. This variable describes if and under what circumstances the cycling
  1838. mechanism for TODO keywords will be replaced by a single-key, direct
  1839. selection scheme, where the choices are displayed in a little window.
  1840. When nil, fast selection is never used. This means that the command
  1841. will always switch to the next state.
  1842. When it is the symbol `auto', fast selection is whenever selection
  1843. keys have been defined.
  1844. `expert' is like `auto', but no special window with the keyword
  1845. will be shown, choices will only be listed in the prompt.
  1846. In all cases, the special interface is only used if access keys have
  1847. actually been assigned by the user, i.e. if keywords in the configuration
  1848. are followed by a letter in parenthesis, like TODO(t)."
  1849. :group 'org-todo
  1850. :set (lambda (var val)
  1851. (cond
  1852. ((eq var t) (set var 'auto))
  1853. ((eq var 'prefix) (set var nil))
  1854. (t (set var val))))
  1855. :type '(choice
  1856. (const :tag "Never" nil)
  1857. (const :tag "Automatically, when key letter have been defined" auto)
  1858. (const :tag "Automatically, but don't show the selection window" expert)))
  1859. (defcustom org-provide-todo-statistics t
  1860. "Non-nil means update todo statistics after insert and toggle.
  1861. ALL-HEADLINES means update todo statistics by including headlines
  1862. with no TODO keyword as well, counting them as not done.
  1863. A list of TODO keywords means the same, but skip keywords that are
  1864. not in this list.
  1865. When set to a list of two lists, the first list contains keywords
  1866. to consider as TODO keywords, the second list contains keywords
  1867. to consider as DONE keywords.
  1868. When this is set, todo statistics is updated in the parent of the
  1869. current entry each time a todo state is changed."
  1870. :group 'org-todo
  1871. :type '(choice
  1872. (const :tag "Yes, only for TODO entries" t)
  1873. (const :tag "Yes, including all entries" all-headlines)
  1874. (repeat :tag "Yes, for TODOs in this list"
  1875. (string :tag "TODO keyword"))
  1876. (list :tag "Yes, for TODOs and DONEs in these lists"
  1877. (repeat (string :tag "TODO keyword"))
  1878. (repeat (string :tag "DONE keyword")))
  1879. (other :tag "No TODO statistics" nil)))
  1880. (defcustom org-hierarchical-todo-statistics t
  1881. "Non-nil means TODO statistics covers just direct children.
  1882. When nil, all entries in the subtree are considered.
  1883. This has only an effect if `org-provide-todo-statistics' is set.
  1884. To set this to nil for only a single subtree, use a COOKIE_DATA
  1885. property and include the word \"recursive\" into the value."
  1886. :group 'org-todo
  1887. :type 'boolean)
  1888. (defcustom org-after-todo-state-change-hook nil
  1889. "Hook which is run after the state of a TODO item was changed.
  1890. The new state (a string with a TODO keyword, or nil) is available in the
  1891. Lisp variable `org-state'."
  1892. :group 'org-todo
  1893. :type 'hook)
  1894. (defvar org-blocker-hook nil
  1895. "Hook for functions that are allowed to block a state change.
  1896. Functions in this hook should not modify the buffer.
  1897. Each function gets as its single argument a property list,
  1898. see `org-trigger-hook' for more information about this list.
  1899. If any of the functions in this hook returns nil, the state change
  1900. is blocked.")
  1901. (defvar org-trigger-hook nil
  1902. "Hook for functions that are triggered by a state change.
  1903. Each function gets as its single argument a property list with at
  1904. least the following elements:
  1905. (:type type-of-change :position pos-at-entry-start
  1906. :from old-state :to new-state)
  1907. Depending on the type, more properties may be present.
  1908. This mechanism is currently implemented for:
  1909. TODO state changes
  1910. ------------------
  1911. :type todo-state-change
  1912. :from previous state (keyword as a string), or nil, or a symbol
  1913. `todo' or `done', to indicate the general type of state.
  1914. :to new state, like in :from")
  1915. (defcustom org-enforce-todo-dependencies nil
  1916. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1917. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1918. be blocked if any prior sibling is not yet done.
  1919. Finally, if the parent is blocked because of ordered siblings of its own,
  1920. the child will also be blocked."
  1921. :set (lambda (var val)
  1922. (set var val)
  1923. (if val
  1924. (add-hook 'org-blocker-hook
  1925. 'org-block-todo-from-children-or-siblings-or-parent)
  1926. (remove-hook 'org-blocker-hook
  1927. 'org-block-todo-from-children-or-siblings-or-parent)))
  1928. :group 'org-todo
  1929. :type 'boolean)
  1930. (defcustom org-enforce-todo-checkbox-dependencies nil
  1931. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1932. When this is nil, checkboxes have no influence on switching TODO states.
  1933. When non-nil, you first need to check off all check boxes before the TODO
  1934. entry can be switched to DONE.
  1935. This variable needs to be set before org.el is loaded, and you need to
  1936. restart Emacs after a change to make the change effective. The only way
  1937. to change it while Emacs is running is through the customize interface."
  1938. :set (lambda (var val)
  1939. (set var val)
  1940. (if val
  1941. (add-hook 'org-blocker-hook
  1942. 'org-block-todo-from-checkboxes)
  1943. (remove-hook 'org-blocker-hook
  1944. 'org-block-todo-from-checkboxes)))
  1945. :group 'org-todo
  1946. :type 'boolean)
  1947. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1948. "Non-nil means inserting a TODO heading is treated as state change.
  1949. So when the command `\\[org-insert-todo-heading]' is used, state change
  1950. logging will apply if appropriate. When nil, the new TODO item will
  1951. be inserted directly, and no logging will take place."
  1952. :group 'org-todo
  1953. :type 'boolean)
  1954. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1955. "Non-nil means switching TODO states with S-cursor counts as state change.
  1956. This is the default behavior. However, setting this to nil allows a
  1957. convenient way to select a TODO state and bypass any logging associated
  1958. with that."
  1959. :group 'org-todo
  1960. :type 'boolean)
  1961. (defcustom org-todo-state-tags-triggers nil
  1962. "Tag changes that should be triggered by TODO state changes.
  1963. This is a list. Each entry is
  1964. (state-change (tag . flag) .......)
  1965. State-change can be a string with a state, and empty string to indicate the
  1966. state that has no TODO keyword, or it can be one of the symbols `todo'
  1967. or `done', meaning any not-done or done state, respectively."
  1968. :group 'org-todo
  1969. :group 'org-tags
  1970. :type '(repeat
  1971. (cons (choice :tag "When changing to"
  1972. (const :tag "Not-done state" todo)
  1973. (const :tag "Done state" done)
  1974. (string :tag "State"))
  1975. (repeat
  1976. (cons :tag "Tag action"
  1977. (string :tag "Tag")
  1978. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1979. (defcustom org-log-done nil
  1980. "Information to record when a task moves to the DONE state.
  1981. Possible values are:
  1982. nil Don't add anything, just change the keyword
  1983. time Add a time stamp to the task
  1984. note Prompt for a note and add it with template `org-log-note-headings'
  1985. This option can also be set with on a per-file-basis with
  1986. #+STARTUP: nologdone
  1987. #+STARTUP: logdone
  1988. #+STARTUP: lognotedone
  1989. You can have local logging settings for a subtree by setting the LOGGING
  1990. property to one or more of these keywords."
  1991. :group 'org-todo
  1992. :group 'org-progress
  1993. :type '(choice
  1994. (const :tag "No logging" nil)
  1995. (const :tag "Record CLOSED timestamp" time)
  1996. (const :tag "Record CLOSED timestamp with note." note)))
  1997. ;; Normalize old uses of org-log-done.
  1998. (cond
  1999. ((eq org-log-done t) (setq org-log-done 'time))
  2000. ((and (listp org-log-done) (memq 'done org-log-done))
  2001. (setq org-log-done 'note)))
  2002. (defcustom org-log-reschedule nil
  2003. "Information to record when the scheduling date of a task is modified.
  2004. Possible values are:
  2005. nil Don't add anything, just change the date
  2006. time Add a time stamp to the task
  2007. note Prompt for a note and add it with template `org-log-note-headings'
  2008. This option can also be set with on a per-file-basis with
  2009. #+STARTUP: nologreschedule
  2010. #+STARTUP: logreschedule
  2011. #+STARTUP: lognotereschedule
  2012. You can have local logging settings for a subtree by setting the LOGGING
  2013. property to one or more of these keywords.
  2014. This variable has an effect when calling `org-schedule' or
  2015. `org-agenda-schedule' only."
  2016. :group 'org-todo
  2017. :group 'org-progress
  2018. :type '(choice
  2019. (const :tag "No logging" nil)
  2020. (const :tag "Record timestamp" time)
  2021. (const :tag "Record timestamp with note" note)))
  2022. (defcustom org-log-redeadline nil
  2023. "Information to record when the deadline date of a task is modified.
  2024. Possible values are:
  2025. nil Don't add anything, just change the date
  2026. time Add a time stamp to the task
  2027. note Prompt for a note and add it with template `org-log-note-headings'
  2028. This option can also be set with on a per-file-basis with
  2029. #+STARTUP: nologredeadline
  2030. #+STARTUP: logredeadline
  2031. #+STARTUP: lognoteredeadline
  2032. You can have local logging settings for a subtree by setting the LOGGING
  2033. property to one or more of these keywords.
  2034. This variable has an effect when calling `org-deadline' or
  2035. `org-agenda-deadline' only."
  2036. :group 'org-todo
  2037. :group 'org-progress
  2038. :type '(choice
  2039. (const :tag "No logging" nil)
  2040. (const :tag "Record timestamp" time)
  2041. (const :tag "Record timestamp with note." note)))
  2042. (defcustom org-log-note-clock-out nil
  2043. "Non-nil means record a note when clocking out of an item.
  2044. This can also be configured on a per-file basis by adding one of
  2045. the following lines anywhere in the buffer:
  2046. #+STARTUP: lognoteclock-out
  2047. #+STARTUP: nolognoteclock-out"
  2048. :group 'org-todo
  2049. :group 'org-progress
  2050. :type 'boolean)
  2051. (defcustom org-log-done-with-time t
  2052. "Non-nil means the CLOSED time stamp will contain date and time.
  2053. When nil, only the date will be recorded."
  2054. :group 'org-progress
  2055. :type 'boolean)
  2056. (defcustom org-log-note-headings
  2057. '((done . "CLOSING NOTE %t")
  2058. (state . "State %-12s from %-12S %t")
  2059. (note . "Note taken on %t")
  2060. (reschedule . "Rescheduled from %S on %t")
  2061. (delschedule . "Not scheduled, was %S on %t")
  2062. (redeadline . "New deadline from %S on %t")
  2063. (deldeadline . "Removed deadline, was %S on %t")
  2064. (refile . "Refiled on %t")
  2065. (clock-out . ""))
  2066. "Headings for notes added to entries.
  2067. The value is an alist, with the car being a symbol indicating the
  2068. note context, and the cdr is the heading to be used. The heading
  2069. may also be the empty string. The following placeholders can be
  2070. used:
  2071. %t a time stamp.
  2072. %T an active time stamp instead the default inactive one
  2073. %d a short-format time stamp.
  2074. %D an active short-format time stamp.
  2075. %s the new TODO state or time stamp (inactive), in double quotes.
  2076. %S the old TODO state or time stamp (inactive), in double quotes.
  2077. %u the user name.
  2078. %U full user name.
  2079. In fact, it is not a good idea to change the `state' entry,
  2080. because Agenda Log mode depends on the format of these entries."
  2081. :group 'org-todo
  2082. :group 'org-progress
  2083. :type '(list :greedy t
  2084. (cons (const :tag "Heading when closing an item" done) string)
  2085. (cons (const :tag
  2086. "Heading when changing todo state (todo sequence only)"
  2087. state) string)
  2088. (cons (const :tag "Heading when just taking a note" note) string)
  2089. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2090. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2091. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2092. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2093. (cons (const :tag "Heading when refiling" refile) string)
  2094. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2095. (unless (assq 'note org-log-note-headings)
  2096. (push '(note . "%t") org-log-note-headings))
  2097. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2098. (defcustom org-log-into-drawer nil
  2099. "Non-nil means insert state change notes and time stamps into a drawer.
  2100. When nil, state changes notes will be inserted after the headline and
  2101. any scheduling and clock lines, but not inside a drawer.
  2102. The value of this variable should be the name of the drawer to use.
  2103. LOGBOOK is proposed as the default drawer for this purpose, you can
  2104. also set this to a string to define the drawer of your choice.
  2105. A value of t is also allowed, representing \"LOGBOOK\".
  2106. A value of t or nil can also be set with on a per-file-basis with
  2107. #+STARTUP: logdrawer
  2108. #+STARTUP: nologdrawer
  2109. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2110. will be ignored.
  2111. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2112. a subtree.
  2113. Do not check directly this variable in a Lisp program. Call
  2114. function `org-log-into-drawer' instead."
  2115. :group 'org-todo
  2116. :group 'org-progress
  2117. :type '(choice
  2118. (const :tag "Not into a drawer" nil)
  2119. (const :tag "LOGBOOK" t)
  2120. (string :tag "Other")))
  2121. (defun org-log-into-drawer ()
  2122. "Name of the log drawer, as a string, or nil.
  2123. This is the value of `org-log-into-drawer'. However, if the
  2124. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2125. be used instead of the default value."
  2126. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2127. (cond ((equal p "nil") nil)
  2128. ((equal p "t") "LOGBOOK")
  2129. ((stringp p) p)
  2130. (p "LOGBOOK")
  2131. ((stringp org-log-into-drawer) org-log-into-drawer)
  2132. (org-log-into-drawer "LOGBOOK"))))
  2133. (defcustom org-log-state-notes-insert-after-drawers nil
  2134. "Non-nil means insert state change notes after any drawers in entry.
  2135. Only the drawers that *immediately* follow the headline and the
  2136. deadline/scheduled line are skipped.
  2137. When nil, insert notes right after the heading and perhaps the line
  2138. with deadline/scheduling if present.
  2139. This variable will have no effect if `org-log-into-drawer' is
  2140. set."
  2141. :group 'org-todo
  2142. :group 'org-progress
  2143. :type 'boolean)
  2144. (defcustom org-log-states-order-reversed t
  2145. "Non-nil means the latest state note will be directly after heading.
  2146. When nil, the state change notes will be ordered according to time.
  2147. This option can also be set with on a per-file-basis with
  2148. #+STARTUP: logstatesreversed
  2149. #+STARTUP: nologstatesreversed"
  2150. :group 'org-todo
  2151. :group 'org-progress
  2152. :type 'boolean)
  2153. (defcustom org-todo-repeat-to-state nil
  2154. "The TODO state to which a repeater should return the repeating task.
  2155. By default this is the first task of a TODO sequence or the
  2156. previous state of a TYPE_TODO set. But you can specify to use
  2157. the previous state in a TODO sequence or a string.
  2158. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2159. entry, which has precedence over this option."
  2160. :group 'org-todo
  2161. :version "24.1"
  2162. :type '(choice (const :tag "Use the previous TODO state" t)
  2163. (const :tag "Use the head of the TODO sequence" nil)
  2164. (string :tag "Use a specific TODO state")))
  2165. (defcustom org-log-repeat 'time
  2166. "Non-nil means record moving through the DONE state when triggering repeat.
  2167. An auto-repeating task is immediately switched back to TODO when
  2168. marked DONE. If you are not logging state changes (by adding \"@\"
  2169. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2170. record a closing note, there will be no record of the task moving
  2171. through DONE. This variable forces taking a note anyway.
  2172. nil Don't force a record
  2173. time Record a time stamp
  2174. note Prompt for a note and add it with template `org-log-note-headings'
  2175. This option can also be set with on a per-file-basis with
  2176. #+STARTUP: nologrepeat
  2177. #+STARTUP: logrepeat
  2178. #+STARTUP: lognoterepeat
  2179. You can have local logging settings for a subtree by setting the LOGGING
  2180. property to one or more of these keywords."
  2181. :group 'org-todo
  2182. :group 'org-progress
  2183. :type '(choice
  2184. (const :tag "Don't force a record" nil)
  2185. (const :tag "Force recording the DONE state" time)
  2186. (const :tag "Force recording a note with the DONE state" note)))
  2187. (defcustom org-todo-repeat-hook nil
  2188. "Hook that is run after a task has been repeated."
  2189. :package-version '(Org . "9.2")
  2190. :group 'org-todo
  2191. :type 'hook)
  2192. (defgroup org-priorities nil
  2193. "Priorities in Org mode."
  2194. :tag "Org Priorities"
  2195. :group 'org-todo)
  2196. (defcustom org-enable-priority-commands t
  2197. "Non-nil means priority commands are active.
  2198. When nil, these commands will be disabled, so that you never accidentally
  2199. set a priority."
  2200. :group 'org-priorities
  2201. :type 'boolean)
  2202. (defcustom org-highest-priority ?A
  2203. "The highest priority of TODO items. A character like ?A, ?B etc.
  2204. Must have a smaller ASCII number than `org-lowest-priority'."
  2205. :group 'org-priorities
  2206. :type 'character)
  2207. (defcustom org-lowest-priority ?C
  2208. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2209. Must have a larger ASCII number than `org-highest-priority'."
  2210. :group 'org-priorities
  2211. :type 'character)
  2212. (defcustom org-default-priority ?B
  2213. "The default priority of TODO items.
  2214. This is the priority an item gets if no explicit priority is given.
  2215. When starting to cycle on an empty priority the first step in the cycle
  2216. depends on `org-priority-start-cycle-with-default'. The resulting first
  2217. step priority must not exceed the range from `org-highest-priority' to
  2218. `org-lowest-priority' which means that `org-default-priority' has to be
  2219. in this range exclusive or inclusive the range boundaries. Else the
  2220. first step refuses to set the default and the second will fall back
  2221. to (depending on the command used) the highest or lowest priority."
  2222. :group 'org-priorities
  2223. :type 'character)
  2224. (defcustom org-priority-start-cycle-with-default t
  2225. "Non-nil means start with default priority when starting to cycle.
  2226. When this is nil, the first step in the cycle will be (depending on the
  2227. command used) one higher or lower than the default priority.
  2228. See also `org-default-priority'."
  2229. :group 'org-priorities
  2230. :type 'boolean)
  2231. (defcustom org-get-priority-function nil
  2232. "Function to extract the priority from a string.
  2233. The string is normally the headline. If this is nil Org computes the
  2234. priority from the priority cookie like [#A] in the headline. It returns
  2235. an integer, increasing by 1000 for each priority level.
  2236. The user can set a different function here, which should take a string
  2237. as an argument and return the numeric priority."
  2238. :group 'org-priorities
  2239. :version "24.1"
  2240. :type '(choice
  2241. (const nil)
  2242. (function)))
  2243. (defgroup org-time nil
  2244. "Options concerning time stamps and deadlines in Org mode."
  2245. :tag "Org Time"
  2246. :group 'org)
  2247. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2248. "Number of minutes to round time stamps to.
  2249. \\<org-mode-map>\
  2250. These are two values, the first applies when first creating a time stamp.
  2251. The second applies when changing it with the commands `S-up' and `S-down'.
  2252. When changing the time stamp, this means that it will change in steps
  2253. of N minutes, as given by the second value.
  2254. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2255. numbers should be factors of 60, so for example 5, 10, 15.
  2256. When this is larger than 1, you can still force an exact time stamp by using
  2257. a double prefix argument to a time stamp command like \
  2258. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2259. and by using a prefix arg to `S-up/down' to specify the exact number
  2260. of minutes to shift."
  2261. :group 'org-time
  2262. :get (lambda (var) ; Make sure both elements are there
  2263. (if (integerp (default-value var))
  2264. (list (default-value var) 5)
  2265. (default-value var)))
  2266. :type '(list
  2267. (integer :tag "when inserting times")
  2268. (integer :tag "when modifying times")))
  2269. ;; Normalize old customizations of this variable.
  2270. (when (integerp org-time-stamp-rounding-minutes)
  2271. (setq org-time-stamp-rounding-minutes
  2272. (list org-time-stamp-rounding-minutes
  2273. org-time-stamp-rounding-minutes)))
  2274. (defcustom org-display-custom-times nil
  2275. "Non-nil means overlay custom formats over all time stamps.
  2276. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2277. To turn this on on a per-file basis, insert anywhere in the file:
  2278. #+STARTUP: customtime"
  2279. :group 'org-time
  2280. :set 'set-default
  2281. :type 'sexp)
  2282. (make-variable-buffer-local 'org-display-custom-times)
  2283. (defcustom org-time-stamp-custom-formats
  2284. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2285. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2286. These are overlaid over the default ISO format if the variable
  2287. `org-display-custom-times' is set. Time like %H:%M should be at the
  2288. end of the second format. The custom formats are also honored by export
  2289. commands, if custom time display is turned on at the time of export."
  2290. :group 'org-time
  2291. :type 'sexp)
  2292. (defun org-time-stamp-format (&optional long inactive)
  2293. "Get the right format for a time string."
  2294. (let ((f (if long (cdr org-time-stamp-formats)
  2295. (car org-time-stamp-formats))))
  2296. (if inactive
  2297. (concat "[" (substring f 1 -1) "]")
  2298. f)))
  2299. (defcustom org-deadline-warning-days 14
  2300. "Number of days before expiration during which a deadline becomes active.
  2301. This variable governs the display in sparse trees and in the agenda.
  2302. When 0 or negative, it means use this number (the absolute value of it)
  2303. even if a deadline has a different individual lead time specified.
  2304. Custom commands can set this variable in the options section."
  2305. :group 'org-time
  2306. :group 'org-agenda-daily/weekly
  2307. :type 'integer)
  2308. (defcustom org-scheduled-delay-days 0
  2309. "Number of days before a scheduled item becomes active.
  2310. This variable governs the display in sparse trees and in the agenda.
  2311. The default value (i.e. 0) means: don't delay scheduled item.
  2312. When negative, it means use this number (the absolute value of it)
  2313. even if a scheduled item has a different individual delay time
  2314. specified.
  2315. Custom commands can set this variable in the options section."
  2316. :group 'org-time
  2317. :group 'org-agenda-daily/weekly
  2318. :version "24.4"
  2319. :package-version '(Org . "8.0")
  2320. :type 'integer)
  2321. (defcustom org-read-date-prefer-future t
  2322. "Non-nil means assume future for incomplete date input from user.
  2323. This affects the following situations:
  2324. 1. The user gives a month but not a year.
  2325. For example, if it is April and you enter \"feb 2\", this will be read
  2326. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2327. 2. The user gives a day, but no month.
  2328. For example, if today is the 15th, and you enter \"3\", Org will read
  2329. this as the third of *next* month. However, if you enter \"17\",
  2330. it will be considered as *this* month.
  2331. If you set this variable to the symbol `time', then also the following
  2332. will work:
  2333. 3. If the user gives a time.
  2334. If the time is before now, it will be interpreted as tomorrow.
  2335. Currently none of this works for ISO week specifications.
  2336. When this option is nil, the current day, month and year will always be
  2337. used as defaults.
  2338. See also `org-agenda-jump-prefer-future'."
  2339. :group 'org-time
  2340. :type '(choice
  2341. (const :tag "Never" nil)
  2342. (const :tag "Check month and day" t)
  2343. (const :tag "Check month, day, and time" time)))
  2344. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2345. "Should the agenda jump command prefer the future for incomplete dates?
  2346. The default is to do the same as configured in `org-read-date-prefer-future'.
  2347. But you can also set a deviating value here.
  2348. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2349. :group 'org-agenda
  2350. :group 'org-time
  2351. :version "24.1"
  2352. :type '(choice
  2353. (const :tag "Use org-read-date-prefer-future"
  2354. org-read-date-prefer-future)
  2355. (const :tag "Never" nil)
  2356. (const :tag "Always" t)))
  2357. (defcustom org-read-date-force-compatible-dates t
  2358. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2359. Depending on the system Emacs is running on, certain dates cannot
  2360. be represented with the type used internally to represent time.
  2361. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2362. correctly. Some systems allow for earlier dates, some for later,
  2363. some for both. One way to find out is to insert any date into an
  2364. Org buffer, putting the cursor on the year and hitting S-up and
  2365. S-down to test the range.
  2366. When this variable is set to t, the date/time prompt will not let
  2367. you specify dates outside the 1970-2037 range, so it is certain that
  2368. these dates will work in whatever version of Emacs you are
  2369. running, and also that you can move a file from one Emacs implementation
  2370. to another. Whenever Org is forcing the year for you, it will display
  2371. a message and beep.
  2372. When this variable is nil, Org will check if the date is
  2373. representable in the specific Emacs implementation you are using.
  2374. If not, it will force a year, usually the current year, and beep
  2375. to remind you. Currently this setting is not recommended because
  2376. the likelihood that you will open your Org files in an Emacs that
  2377. has limited date range is not negligible.
  2378. A workaround for this problem is to use diary sexp dates for time
  2379. stamps outside of this range."
  2380. :group 'org-time
  2381. :version "24.1"
  2382. :type 'boolean)
  2383. (defcustom org-read-date-display-live t
  2384. "Non-nil means display current interpretation of date prompt live.
  2385. This display will be in an overlay, in the minibuffer."
  2386. :group 'org-time
  2387. :type 'boolean)
  2388. (defvaralias 'org-popup-calendar-for-date-prompt
  2389. 'org-read-date-popup-calendar)
  2390. (defcustom org-read-date-popup-calendar t
  2391. "Non-nil means pop up a calendar when prompting for a date.
  2392. In the calendar, the date can be selected with mouse-1. However, the
  2393. minibuffer will also be active, and you can simply enter the date as well.
  2394. When nil, only the minibuffer will be available."
  2395. :group 'org-time
  2396. :type 'boolean)
  2397. (defcustom org-extend-today-until 0
  2398. "The hour when your day really ends. Must be an integer.
  2399. This has influence for the following applications:
  2400. - When switching the agenda to \"today\". It it is still earlier than
  2401. the time given here, the day recognized as TODAY is actually yesterday.
  2402. - When a date is read from the user and it is still before the time given
  2403. here, the current date and time will be assumed to be yesterday, 23:59.
  2404. Also, timestamps inserted in capture templates follow this rule.
  2405. IMPORTANT: This is a feature whose implementation is and likely will
  2406. remain incomplete. Really, it is only here because past midnight seems to
  2407. be the favorite working time of John Wiegley :-)"
  2408. :group 'org-time
  2409. :type 'integer)
  2410. (defcustom org-use-effective-time nil
  2411. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2412. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2413. \"effective time\" of any timestamps between midnight and 8am will be
  2414. 23:59 of the previous day."
  2415. :group 'org-time
  2416. :version "24.1"
  2417. :type 'boolean)
  2418. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2419. "When non-nil, use the last clock out time for `org-todo'.
  2420. Note that this option has precedence over the combined use of
  2421. `org-use-effective-time' and `org-extend-today-until'."
  2422. :group 'org-time
  2423. :version "24.4"
  2424. :package-version '(Org . "8.0")
  2425. :type 'boolean)
  2426. (defcustom org-edit-timestamp-down-means-later nil
  2427. "Non-nil means S-down will increase the time in a time stamp.
  2428. When nil, S-up will increase."
  2429. :group 'org-time
  2430. :type 'boolean)
  2431. (defcustom org-calendar-follow-timestamp-change t
  2432. "Non-nil means make the calendar window follow timestamp changes.
  2433. When a timestamp is modified and the calendar window is visible, it will be
  2434. moved to the new date."
  2435. :group 'org-time
  2436. :type 'boolean)
  2437. (defgroup org-tags nil
  2438. "Options concerning tags in Org mode."
  2439. :tag "Org Tags"
  2440. :group 'org)
  2441. (defcustom org-tag-alist nil
  2442. "Default tags available in Org files.
  2443. The value of this variable is an alist. Associations either:
  2444. (TAG)
  2445. (TAG . SELECT)
  2446. (SPECIAL)
  2447. where TAG is a tag as a string, SELECT is character, used to
  2448. select that tag through the fast tag selection interface, and
  2449. SPECIAL is one of the following keywords: `:startgroup',
  2450. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2451. `:newline'. These keywords are used to define a hierarchy of
  2452. tags. See manual for details.
  2453. When this variable is nil, Org mode bases tag input on what is
  2454. already in the buffer. The value can be overridden locally by
  2455. using a TAGS keyword, e.g.,
  2456. #+TAGS: tag1 tag2
  2457. See also `org-tag-persistent-alist' to sidestep this behavior."
  2458. :group 'org-tags
  2459. :type '(repeat
  2460. (choice
  2461. (cons :tag "Tag with key"
  2462. (string :tag "Tag name")
  2463. (character :tag "Access char"))
  2464. (list :tag "Tag" (string :tag "Tag name"))
  2465. (const :tag "Start radio group" (:startgroup))
  2466. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2467. (const :tag "Group tags delimiter" (:grouptags))
  2468. (const :tag "End radio group" (:endgroup))
  2469. (const :tag "End tag group, non distinct" (:endgrouptag))
  2470. (const :tag "New line" (:newline)))))
  2471. (defcustom org-tag-persistent-alist nil
  2472. "Tags always available in Org files.
  2473. The value of this variable is an alist. Associations either:
  2474. (TAG)
  2475. (TAG . SELECT)
  2476. (SPECIAL)
  2477. where TAG is a tag as a string, SELECT is a character, used to
  2478. select that tag through the fast tag selection interface, and
  2479. SPECIAL is one of the following keywords: `:startgroup',
  2480. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2481. `:newline'. These keywords are used to define a hierarchy of
  2482. tags. See manual for details.
  2483. Unlike to `org-tag-alist', tags defined in this variable do not
  2484. depend on a local TAGS keyword. Instead, to disable these tags
  2485. on a per-file basis, insert anywhere in the file:
  2486. #+STARTUP: noptag"
  2487. :group 'org-tags
  2488. :type '(repeat
  2489. (choice
  2490. (cons :tag "Tag with key"
  2491. (string :tag "Tag name")
  2492. (character :tag "Access char"))
  2493. (list :tag "Tag" (string :tag "Tag name"))
  2494. (const :tag "Start radio group" (:startgroup))
  2495. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2496. (const :tag "Group tags delimiter" (:grouptags))
  2497. (const :tag "End radio group" (:endgroup))
  2498. (const :tag "End tag group, non distinct" (:endgrouptag))
  2499. (const :tag "New line" (:newline)))))
  2500. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2501. "If non-nil, always offer completion for all tags of all agenda files.
  2502. Setting this variable locally allows for dynamic generation of tag
  2503. completions in capture buffers.
  2504. (add-hook \\='org-capture-mode-hook
  2505. (lambda ()
  2506. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2507. :group 'org-tags
  2508. :version "24.1"
  2509. :type 'boolean)
  2510. (defvar org-file-tags nil
  2511. "List of tags that can be inherited by all entries in the file.
  2512. The tags will be inherited if the variable `org-use-tag-inheritance'
  2513. says they should be.
  2514. This variable is populated from #+FILETAGS lines.")
  2515. (defcustom org-use-fast-tag-selection 'auto
  2516. "Non-nil means use fast tag selection scheme.
  2517. This is a special interface to select and deselect tags with single keys.
  2518. When nil, fast selection is never used.
  2519. When the symbol `auto', fast selection is used if and only if selection
  2520. characters for tags have been configured, either through the variable
  2521. `org-tag-alist' or through a #+TAGS line in the buffer.
  2522. When t, fast selection is always used and selection keys are assigned
  2523. automatically if necessary."
  2524. :group 'org-tags
  2525. :type '(choice
  2526. (const :tag "Always" t)
  2527. (const :tag "Never" nil)
  2528. (const :tag "When selection characters are configured" auto)))
  2529. (defcustom org-fast-tag-selection-single-key nil
  2530. "Non-nil means fast tag selection exits after first change.
  2531. When nil, you have to press RET to exit it.
  2532. During fast tag selection, you can toggle this flag with `C-c'.
  2533. This variable can also have the value `expert'. In this case, the window
  2534. displaying the tags menu is not even shown, until you press C-c again."
  2535. :group 'org-tags
  2536. :type '(choice
  2537. (const :tag "No" nil)
  2538. (const :tag "Yes" t)
  2539. (const :tag "Expert" expert)))
  2540. (defvar org-fast-tag-selection-include-todo nil
  2541. "Non-nil means fast tags selection interface will also offer TODO states.
  2542. This is an undocumented feature, you should not rely on it.")
  2543. (defcustom org-tags-column -77
  2544. "The column to which tags should be indented in a headline.
  2545. If this number is positive, it specifies the column. If it is negative,
  2546. it means that the tags should be flushright to that column. For example,
  2547. -80 works well for a normal 80 character screen.
  2548. When 0, place tags directly after headline text, with only one space in
  2549. between."
  2550. :group 'org-tags
  2551. :type 'integer)
  2552. (defcustom org-auto-align-tags t
  2553. "Non-nil keeps tags aligned when modifying headlines.
  2554. Some operations (i.e. demoting) change the length of a headline and
  2555. therefore shift the tags around. With this option turned on, after
  2556. each such operation the tags are again aligned to `org-tags-column'."
  2557. :group 'org-tags
  2558. :type 'boolean)
  2559. (defcustom org-use-tag-inheritance t
  2560. "Non-nil means tags in levels apply also for sublevels.
  2561. When nil, only the tags directly given in a specific line apply there.
  2562. This may also be a list of tags that should be inherited, or a regexp that
  2563. matches tags that should be inherited. Additional control is possible
  2564. with the variable `org-tags-exclude-from-inheritance' which gives an
  2565. explicit list of tags to be excluded from inheritance, even if the value of
  2566. `org-use-tag-inheritance' would select it for inheritance.
  2567. If this option is t, a match early-on in a tree can lead to a large
  2568. number of matches in the subtree when constructing the agenda or creating
  2569. a sparse tree. If you only want to see the first match in a tree during
  2570. a search, check out the variable `org-tags-match-list-sublevels'."
  2571. :group 'org-tags
  2572. :type '(choice
  2573. (const :tag "Not" nil)
  2574. (const :tag "Always" t)
  2575. (repeat :tag "Specific tags" (string :tag "Tag"))
  2576. (regexp :tag "Tags matched by regexp")))
  2577. (defcustom org-tags-exclude-from-inheritance nil
  2578. "List of tags that should never be inherited.
  2579. This is a way to exclude a few tags from inheritance. For way to do
  2580. the opposite, to actively allow inheritance for selected tags,
  2581. see the variable `org-use-tag-inheritance'."
  2582. :group 'org-tags
  2583. :type '(repeat (string :tag "Tag")))
  2584. (defun org-tag-inherit-p (tag)
  2585. "Check if TAG is one that should be inherited."
  2586. (cond
  2587. ((member tag org-tags-exclude-from-inheritance) nil)
  2588. ((eq org-use-tag-inheritance t) t)
  2589. ((not org-use-tag-inheritance) nil)
  2590. ((stringp org-use-tag-inheritance)
  2591. (string-match org-use-tag-inheritance tag))
  2592. ((listp org-use-tag-inheritance)
  2593. (member tag org-use-tag-inheritance))
  2594. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2595. (defcustom org-tags-match-list-sublevels t
  2596. "Non-nil means list also sublevels of headlines matching a search.
  2597. This variable applies to tags/property searches, and also to stuck
  2598. projects because this search is based on a tags match as well.
  2599. When set to the symbol `indented', sublevels are indented with
  2600. leading dots.
  2601. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2602. the sublevels of a headline matching a tag search often also match
  2603. the same search. Listing all of them can create very long lists.
  2604. Setting this variable to nil causes subtrees of a match to be skipped.
  2605. This variable is semi-obsolete and probably should always be true. It
  2606. is better to limit inheritance to certain tags using the variables
  2607. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2608. :group 'org-tags
  2609. :type '(choice
  2610. (const :tag "No, don't list them" nil)
  2611. (const :tag "Yes, do list them" t)
  2612. (const :tag "List them, indented with leading dots" indented)))
  2613. (defcustom org-tags-sort-function nil
  2614. "When set, tags are sorted using this function as a comparator."
  2615. :group 'org-tags
  2616. :type '(choice
  2617. (const :tag "No sorting" nil)
  2618. (const :tag "Alphabetical" org-string-collate-lessp)
  2619. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2620. (function :tag "Custom function" nil)))
  2621. (defvar org-tags-history nil
  2622. "History of minibuffer reads for tags.")
  2623. (defvar org-last-tags-completion-table nil
  2624. "The last used completion table for tags.")
  2625. (defvar org-after-tags-change-hook nil
  2626. "Hook that is run after the tags in a line have changed.")
  2627. (defgroup org-properties nil
  2628. "Options concerning properties in Org mode."
  2629. :tag "Org Properties"
  2630. :group 'org)
  2631. (defcustom org-property-format "%-10s %s"
  2632. "How property key/value pairs should be formatted by `indent-line'.
  2633. When `indent-line' hits a property definition, it will format the line
  2634. according to this format, mainly to make sure that the values are
  2635. lined-up with respect to each other."
  2636. :group 'org-properties
  2637. :type 'string)
  2638. (defcustom org-properties-postprocess-alist nil
  2639. "Alist of properties and functions to adjust inserted values.
  2640. Elements of this alist must be of the form
  2641. ([string] [function])
  2642. where [string] must be a property name and [function] must be a
  2643. lambda expression: this lambda expression must take one argument,
  2644. the value to adjust, and return the new value as a string.
  2645. For example, this element will allow the property \"Remaining\"
  2646. to be updated wrt the relation between the \"Effort\" property
  2647. and the clock summary:
  2648. ((\"Remaining\" (lambda(value)
  2649. (let ((clocksum (org-clock-sum-current-item))
  2650. (effort (org-duration-to-minutes
  2651. (org-entry-get (point) \"Effort\"))))
  2652. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2653. :group 'org-properties
  2654. :version "24.1"
  2655. :type '(alist :key-type (string :tag "Property")
  2656. :value-type (function :tag "Function")))
  2657. (defcustom org-use-property-inheritance nil
  2658. "Non-nil means properties apply also for sublevels.
  2659. This setting is chiefly used during property searches. Turning it on can
  2660. cause significant overhead when doing a search, which is why it is not
  2661. on by default.
  2662. When nil, only the properties directly given in the current entry count.
  2663. When t, every property is inherited. The value may also be a list of
  2664. properties that should have inheritance, or a regular expression matching
  2665. properties that should be inherited.
  2666. However, note that some special properties use inheritance under special
  2667. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2668. and the properties ending in \"_ALL\" when they are used as descriptor
  2669. for valid values of a property.
  2670. Note for programmers:
  2671. When querying an entry with `org-entry-get', you can control if inheritance
  2672. should be used. By default, `org-entry-get' looks only at the local
  2673. properties. You can request inheritance by setting the inherit argument
  2674. to t (to force inheritance) or to `selective' (to respect the setting
  2675. in this variable)."
  2676. :group 'org-properties
  2677. :type '(choice
  2678. (const :tag "Not" nil)
  2679. (const :tag "Always" t)
  2680. (repeat :tag "Specific properties" (string :tag "Property"))
  2681. (regexp :tag "Properties matched by regexp")))
  2682. (defun org-property-inherit-p (property)
  2683. "Return a non-nil value if PROPERTY should be inherited."
  2684. (cond
  2685. ((eq org-use-property-inheritance t) t)
  2686. ((not org-use-property-inheritance) nil)
  2687. ((stringp org-use-property-inheritance)
  2688. (string-match org-use-property-inheritance property))
  2689. ((listp org-use-property-inheritance)
  2690. (member-ignore-case property org-use-property-inheritance))
  2691. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2692. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2693. "The default column format, if no other format has been defined.
  2694. This variable can be set on the per-file basis by inserting a line
  2695. #+COLUMNS: %25ITEM ....."
  2696. :group 'org-properties
  2697. :type 'string)
  2698. (defcustom org-columns-ellipses ".."
  2699. "The ellipses to be used when a field in column view is truncated.
  2700. When this is the empty string, as many characters as possible are shown,
  2701. but then there will be no visual indication that the field has been truncated.
  2702. When this is a string of length N, the last N characters of a truncated
  2703. field are replaced by this string. If the column is narrower than the
  2704. ellipses string, only part of the ellipses string will be shown."
  2705. :group 'org-properties
  2706. :type 'string)
  2707. (defconst org-global-properties-fixed
  2708. '(("VISIBILITY_ALL" . "folded children content all")
  2709. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2710. "List of property/value pairs that can be inherited by any entry.
  2711. These are fixed values, for the preset properties. The user variable
  2712. that can be used to add to this list is `org-global-properties'.
  2713. The entries in this list are cons cells where the car is a property
  2714. name and cdr is a string with the value. If the value represents
  2715. multiple items like an \"_ALL\" property, separate the items by
  2716. spaces.")
  2717. (defcustom org-global-properties nil
  2718. "List of property/value pairs that can be inherited by any entry.
  2719. This list will be combined with the constant `org-global-properties-fixed'.
  2720. The entries in this list are cons cells where the car is a property
  2721. name and cdr is a string with the value.
  2722. You can set buffer-local values for the same purpose in the variable
  2723. `org-file-properties' this by adding lines like
  2724. #+PROPERTY: NAME VALUE"
  2725. :group 'org-properties
  2726. :type '(repeat
  2727. (cons (string :tag "Property")
  2728. (string :tag "Value"))))
  2729. (defvar-local org-file-properties nil
  2730. "List of property/value pairs that can be inherited by any entry.
  2731. Valid for the current buffer.
  2732. This variable is populated from #+PROPERTY lines.")
  2733. (defgroup org-agenda nil
  2734. "Options concerning agenda views in Org mode."
  2735. :tag "Org Agenda"
  2736. :group 'org)
  2737. (defvar-local org-category nil
  2738. "Variable used by Org files to set a category for agenda display.
  2739. Such files should use a file variable to set it, for example
  2740. # -*- mode: org; org-category: \"ELisp\"
  2741. or contain a special line
  2742. #+CATEGORY: ELisp
  2743. If the file does not specify a category, then file's base name
  2744. is used instead.")
  2745. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2746. (defcustom org-agenda-files nil
  2747. "The files to be used for agenda display.
  2748. If an entry is a directory, all files in that directory that are matched
  2749. by `org-agenda-file-regexp' will be part of the file list.
  2750. If the value of the variable is not a list but a single file name, then
  2751. the list of agenda files is actually stored and maintained in that file,
  2752. one agenda file per line. In this file paths can be given relative to
  2753. `org-directory'. Tilde expansion and environment variable substitution
  2754. are also made.
  2755. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2756. and removed with `\\[org-remove-file]'."
  2757. :group 'org-agenda
  2758. :type '(choice
  2759. (repeat :tag "List of files and directories" file)
  2760. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2761. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2762. "Regular expression to match files for `org-agenda-files'.
  2763. If any element in the list in that variable contains a directory instead
  2764. of a normal file, all files in that directory that are matched by this
  2765. regular expression will be included."
  2766. :group 'org-agenda
  2767. :type 'regexp)
  2768. (defvaralias 'org-agenda-multi-occur-extra-files
  2769. 'org-agenda-text-search-extra-files)
  2770. (defcustom org-agenda-text-search-extra-files nil
  2771. "List of extra files to be searched by text search commands.
  2772. These files will be searched in addition to the agenda files by the
  2773. commands `org-search-view' (`\\[org-agenda] s') \
  2774. and `org-occur-in-agenda-files'.
  2775. Note that these files will only be searched for text search commands,
  2776. not for the other agenda views like todo lists, tag searches or the weekly
  2777. agenda. This variable is intended to list notes and possibly archive files
  2778. that should also be searched by these two commands.
  2779. In fact, if the first element in the list is the symbol `agenda-archives',
  2780. then all archive files of all agenda files will be added to the search
  2781. scope."
  2782. :group 'org-agenda
  2783. :type '(set :greedy t
  2784. (const :tag "Agenda Archives" agenda-archives)
  2785. (repeat :inline t (file))))
  2786. (defcustom org-agenda-skip-unavailable-files nil
  2787. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2788. A nil value means to remove them, after a query, from the list."
  2789. :group 'org-agenda
  2790. :type 'boolean)
  2791. (defcustom org-agenda-diary-file 'diary-file
  2792. "File to which to add new entries with the `i' key in agenda and calendar.
  2793. When this is the symbol `diary-file', the functionality in the Emacs
  2794. calendar will be used to add entries to the `diary-file'. But when this
  2795. points to a file, `org-agenda-diary-entry' will be used instead."
  2796. :group 'org-agenda
  2797. :type '(choice
  2798. (const :tag "The standard Emacs diary file" diary-file)
  2799. (file :tag "Special Org file diary entries")))
  2800. (defgroup org-latex nil
  2801. "Options for embedding LaTeX code into Org mode."
  2802. :tag "Org LaTeX"
  2803. :group 'org)
  2804. (defcustom org-format-latex-options
  2805. '(:foreground default :background default :scale 1.0
  2806. :html-foreground "Black" :html-background "Transparent"
  2807. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2808. "Options for creating images from LaTeX fragments.
  2809. This is a property list with the following properties:
  2810. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2811. `default' means use the foreground of the default face.
  2812. `auto' means use the foreground from the text face.
  2813. :background the background color, or \"Transparent\".
  2814. `default' means use the background of the default face.
  2815. `auto' means use the background from the text face.
  2816. :scale a scaling factor for the size of the images, to get more pixels
  2817. :html-foreground, :html-background, :html-scale
  2818. the same numbers for HTML export.
  2819. :matchers a list indicating which matchers should be used to
  2820. find LaTeX fragments. Valid members of this list are:
  2821. \"begin\" find environments
  2822. \"$1\" find single characters surrounded by $.$
  2823. \"$\" find math expressions surrounded by $...$
  2824. \"$$\" find math expressions surrounded by $$....$$
  2825. \"\\(\" find math expressions surrounded by \\(...\\)
  2826. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2827. :group 'org-latex
  2828. :type 'plist)
  2829. (defcustom org-format-latex-signal-error t
  2830. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2831. When nil, just push out a message."
  2832. :group 'org-latex
  2833. :version "24.1"
  2834. :type 'boolean)
  2835. (defcustom org-latex-to-mathml-jar-file nil
  2836. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2837. Use this to specify additional executable file say a jar file.
  2838. When using MathToWeb as the converter, specify the full-path to
  2839. your mathtoweb.jar file."
  2840. :group 'org-latex
  2841. :version "24.1"
  2842. :type '(choice
  2843. (const :tag "None" nil)
  2844. (file :tag "JAR file" :must-match t)))
  2845. (defcustom org-latex-to-mathml-convert-command nil
  2846. "Command to convert LaTeX fragments to MathML.
  2847. Replace format-specifiers in the command as noted below and use
  2848. `shell-command' to convert LaTeX to MathML.
  2849. %j: Executable file in fully expanded form as specified by
  2850. `org-latex-to-mathml-jar-file'.
  2851. %I: Input LaTeX file in fully expanded form.
  2852. %i: The latex fragment to be converted.
  2853. %o: Output MathML file.
  2854. This command is used by `org-create-math-formula'.
  2855. When using MathToWeb as the converter, set this option to
  2856. \"java -jar %j -unicode -force -df %o %I\".
  2857. When using LaTeXML set this option to
  2858. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2859. :group 'org-latex
  2860. :version "24.1"
  2861. :type '(choice
  2862. (const :tag "None" nil)
  2863. (string :tag "\nShell command")))
  2864. (defcustom org-preview-latex-default-process 'dvipng
  2865. "The default process to convert LaTeX fragments to image files.
  2866. All available processes and theirs documents can be found in
  2867. `org-preview-latex-process-alist', which see."
  2868. :group 'org-latex
  2869. :version "26.1"
  2870. :package-version '(Org . "9.0")
  2871. :type 'symbol)
  2872. (defcustom org-preview-latex-process-alist
  2873. '((dvipng
  2874. :programs ("latex" "dvipng")
  2875. :description "dvi > png"
  2876. :message "you need to install the programs: latex and dvipng."
  2877. :image-input-type "dvi"
  2878. :image-output-type "png"
  2879. :image-size-adjust (1.0 . 1.0)
  2880. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2881. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2882. (dvisvgm
  2883. :programs ("latex" "dvisvgm")
  2884. :description "dvi > svg"
  2885. :message "you need to install the programs: latex and dvisvgm."
  2886. :image-input-type "dvi"
  2887. :image-output-type "svg"
  2888. :image-size-adjust (1.7 . 1.5)
  2889. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2890. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2891. (imagemagick
  2892. :programs ("latex" "convert")
  2893. :description "pdf > png"
  2894. :message "you need to install the programs: latex and imagemagick."
  2895. :image-input-type "pdf"
  2896. :image-output-type "png"
  2897. :image-size-adjust (1.0 . 1.0)
  2898. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2899. :image-converter
  2900. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2901. "Definitions of external processes for LaTeX previewing.
  2902. Org mode can use some external commands to generate TeX snippet's images for
  2903. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2904. `org-create-formula-image' how to call them.
  2905. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2906. PROPERTIES accepts the following attributes:
  2907. :programs list of strings, required programs.
  2908. :description string, describe the process.
  2909. :message string, message it when required programs cannot be found.
  2910. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2911. :image-output-type string, output file type of image converter (e.g., \"png\").
  2912. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2913. image size showed in buffer and the cdr element is for
  2914. HTML file. This option is only useful for process
  2915. developers, users should use variable
  2916. `org-format-latex-options' instead.
  2917. :post-clean list of strings, files matched are to be cleaned up once
  2918. the image is generated. When nil, the files with \".dvi\",
  2919. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2920. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2921. be cleaned up.
  2922. :latex-header list of strings, the LaTeX header of the snippet file.
  2923. When nil, the fallback value is used instead, which is
  2924. controlled by `org-format-latex-header',
  2925. `org-latex-default-packages-alist' and
  2926. `org-latex-packages-alist', which see.
  2927. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2928. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2929. replaced with values defined below.
  2930. :image-converter list of image converter commands strings. Each of them is
  2931. given to the shell and supports any of the following
  2932. place-holders defined below.
  2933. Place-holders used by `:image-converter' and `:latex-compiler':
  2934. %f input file name
  2935. %b base name of input file
  2936. %o base directory of input file
  2937. %O absolute output file name
  2938. Place-holders only used by `:image-converter':
  2939. %D dpi, which is used to adjust image size by some processing commands.
  2940. %S the image size scale ratio, which is used to adjust image size by some
  2941. processing commands."
  2942. :group 'org-latex
  2943. :version "26.1"
  2944. :package-version '(Org . "9.0")
  2945. :type '(alist :tag "LaTeX to image backends"
  2946. :value-type (plist)))
  2947. (defcustom org-preview-latex-image-directory "ltximg/"
  2948. "Path to store latex preview images.
  2949. A relative path here creates many directories relative to the
  2950. processed Org files paths. An absolute path puts all preview
  2951. images at the same place."
  2952. :group 'org-latex
  2953. :version "26.1"
  2954. :package-version '(Org . "9.0")
  2955. :type 'string)
  2956. (defun org-format-latex-mathml-available-p ()
  2957. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2958. (save-match-data
  2959. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2960. org-latex-to-mathml-convert-command)
  2961. (let ((executable (car (split-string
  2962. org-latex-to-mathml-convert-command))))
  2963. (when (executable-find executable)
  2964. (if (string-match
  2965. "%j" org-latex-to-mathml-convert-command)
  2966. (file-readable-p org-latex-to-mathml-jar-file)
  2967. t))))))
  2968. (defcustom org-format-latex-header "\\documentclass{article}
  2969. \\usepackage[usenames]{color}
  2970. \[PACKAGES]
  2971. \[DEFAULT-PACKAGES]
  2972. \\pagestyle{empty} % do not remove
  2973. % The settings below are copied from fullpage.sty
  2974. \\setlength{\\textwidth}{\\paperwidth}
  2975. \\addtolength{\\textwidth}{-3cm}
  2976. \\setlength{\\oddsidemargin}{1.5cm}
  2977. \\addtolength{\\oddsidemargin}{-2.54cm}
  2978. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2979. \\setlength{\\textheight}{\\paperheight}
  2980. \\addtolength{\\textheight}{-\\headheight}
  2981. \\addtolength{\\textheight}{-\\headsep}
  2982. \\addtolength{\\textheight}{-\\footskip}
  2983. \\addtolength{\\textheight}{-3cm}
  2984. \\setlength{\\topmargin}{1.5cm}
  2985. \\addtolength{\\topmargin}{-2.54cm}"
  2986. "The document header used for processing LaTeX fragments.
  2987. It is imperative that this header make sure that no page number
  2988. appears on the page. The package defined in the variables
  2989. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2990. will either replace the placeholder \"[PACKAGES]\" in this
  2991. header, or they will be appended."
  2992. :group 'org-latex
  2993. :type 'string)
  2994. (defun org-set-packages-alist (var val)
  2995. "Set the packages alist and make sure it has 3 elements per entry."
  2996. (set var (mapcar (lambda (x)
  2997. (if (and (consp x) (= (length x) 2))
  2998. (list (car x) (nth 1 x) t)
  2999. x))
  3000. val)))
  3001. (defun org-get-packages-alist (var)
  3002. "Get the packages alist and make sure it has 3 elements per entry."
  3003. (mapcar (lambda (x)
  3004. (if (and (consp x) (= (length x) 2))
  3005. (list (car x) (nth 1 x) t)
  3006. x))
  3007. (default-value var)))
  3008. (defcustom org-latex-default-packages-alist
  3009. '(("AUTO" "inputenc" t ("pdflatex"))
  3010. ("T1" "fontenc" t ("pdflatex"))
  3011. ("" "graphicx" t)
  3012. ("" "grffile" t)
  3013. ("" "longtable" nil)
  3014. ("" "wrapfig" nil)
  3015. ("" "rotating" nil)
  3016. ("normalem" "ulem" t)
  3017. ("" "amsmath" t)
  3018. ("" "textcomp" t)
  3019. ("" "amssymb" t)
  3020. ("" "capt-of" nil)
  3021. ("" "hyperref" nil))
  3022. "Alist of default packages to be inserted in the header.
  3023. Change this only if one of the packages here causes an
  3024. incompatibility with another package you are using.
  3025. The packages in this list are needed by one part or another of
  3026. Org mode to function properly:
  3027. - inputenc, fontenc: for basic font and character selection
  3028. - graphicx: for including images
  3029. - grffile: allow periods and spaces in graphics file names
  3030. - longtable: For multipage tables
  3031. - wrapfig: for figure placement
  3032. - rotating: for sideways figures and tables
  3033. - ulem: for underline and strike-through
  3034. - amsmath: for subscript and superscript and math environments
  3035. - textcomp, amssymb: for various symbols used
  3036. for interpreting the entities in `org-entities'. You can skip
  3037. some of these packages if you don't use any of their symbols.
  3038. - capt-of: for captions outside of floats
  3039. - hyperref: for cross references
  3040. Therefore you should not modify this variable unless you know
  3041. what you are doing. The one reason to change it anyway is that
  3042. you might be loading some other package that conflicts with one
  3043. of the default packages. Each element is either a cell or
  3044. a string.
  3045. A cell is of the format
  3046. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3047. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3048. when compiling LaTeX snippets into images for inclusion into
  3049. non-LaTeX output.
  3050. COMPILERS is a list of compilers that should include the package,
  3051. see `org-latex-compiler'. If the document compiler is not in the
  3052. list, and the list is non-nil, the package will not be inserted
  3053. in the final document.
  3054. A string will be inserted as-is in the header of the document."
  3055. :group 'org-latex
  3056. :group 'org-export-latex
  3057. :set 'org-set-packages-alist
  3058. :get 'org-get-packages-alist
  3059. :version "26.1"
  3060. :package-version '(Org . "8.3")
  3061. :type '(repeat
  3062. (choice
  3063. (list :tag "options/package pair"
  3064. (string :tag "options")
  3065. (string :tag "package")
  3066. (boolean :tag "Snippet")
  3067. (choice
  3068. (const :tag "For all compilers" nil)
  3069. (repeat :tag "Allowed compiler" string)))
  3070. (string :tag "A line of LaTeX"))))
  3071. (defcustom org-latex-packages-alist nil
  3072. "Alist of packages to be inserted in every LaTeX header.
  3073. These will be inserted after `org-latex-default-packages-alist'.
  3074. Each element is either a cell or a string.
  3075. A cell is of the format:
  3076. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3077. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3078. needed when turning LaTeX snippets into images for inclusion into
  3079. non-LaTeX output.
  3080. COMPILERS is a list of compilers that should include the package,
  3081. see `org-latex-compiler'. If the document compiler is not in the
  3082. list, and the list is non-nil, the package will not be inserted
  3083. in the final document.
  3084. A string will be inserted as-is in the header of the document.
  3085. Make sure that you only list packages here which:
  3086. - you want in every file;
  3087. - do not conflict with the setup in `org-format-latex-header';
  3088. - do not conflict with the default packages in
  3089. `org-latex-default-packages-alist'."
  3090. :group 'org-latex
  3091. :group 'org-export-latex
  3092. :set 'org-set-packages-alist
  3093. :get 'org-get-packages-alist
  3094. :type '(repeat
  3095. (choice
  3096. (list :tag "options/package pair"
  3097. (string :tag "options")
  3098. (string :tag "package")
  3099. (boolean :tag "Snippet"))
  3100. (string :tag "A line of LaTeX"))))
  3101. (defgroup org-appearance nil
  3102. "Settings for Org mode appearance."
  3103. :tag "Org Appearance"
  3104. :group 'org)
  3105. (defcustom org-level-color-stars-only nil
  3106. "Non-nil means fontify only the stars in each headline.
  3107. When nil, the entire headline is fontified.
  3108. Changing it requires restart of `font-lock-mode' to become effective
  3109. also in regions already fontified."
  3110. :group 'org-appearance
  3111. :type 'boolean)
  3112. (defcustom org-hide-leading-stars nil
  3113. "Non-nil means hide the first N-1 stars in a headline.
  3114. This works by using the face `org-hide' for these stars. This
  3115. face is white for a light background, and black for a dark
  3116. background. You may have to customize the face `org-hide' to
  3117. make this work.
  3118. Changing it requires restart of `font-lock-mode' to become effective
  3119. also in regions already fontified.
  3120. You may also set this on a per-file basis by adding one of the following
  3121. lines to the buffer:
  3122. #+STARTUP: hidestars
  3123. #+STARTUP: showstars"
  3124. :group 'org-appearance
  3125. :type 'boolean)
  3126. (defcustom org-hidden-keywords nil
  3127. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3128. For example, a value \\='(title) for this list makes the document's title
  3129. appear in the buffer without the initial \"#+TITLE:\" part."
  3130. :group 'org-appearance
  3131. :version "24.1"
  3132. :type '(set (const :tag "#+AUTHOR" author)
  3133. (const :tag "#+DATE" date)
  3134. (const :tag "#+EMAIL" email)
  3135. (const :tag "#+TITLE" title)))
  3136. (defcustom org-custom-properties nil
  3137. "List of properties (as strings) with a special meaning.
  3138. The default use of these custom properties is to let the user
  3139. hide them with `org-toggle-custom-properties-visibility'."
  3140. :group 'org-properties
  3141. :group 'org-appearance
  3142. :version "24.3"
  3143. :type '(repeat (string :tag "Property Name")))
  3144. (defcustom org-fontify-done-headline nil
  3145. "Non-nil means change the face of a headline if it is marked DONE.
  3146. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3147. When this is non-nil, the headline after the keyword is set to the
  3148. `org-headline-done' as an additional indication."
  3149. :group 'org-appearance
  3150. :type 'boolean)
  3151. (defcustom org-fontify-emphasized-text t
  3152. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3153. Changing this variable requires a restart of Emacs to take effect."
  3154. :group 'org-appearance
  3155. :type 'boolean)
  3156. (defcustom org-fontify-whole-heading-line nil
  3157. "Non-nil means fontify the whole line for headings.
  3158. This is useful when setting a background color for the
  3159. org-level-* faces."
  3160. :group 'org-appearance
  3161. :type 'boolean)
  3162. (defcustom org-fontify-whole-block-delimiter-line t
  3163. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3164. This is useful when setting a background color for the
  3165. org-block-begin-line and org-block-end-line faces."
  3166. :group 'org-appearance
  3167. :type 'boolean)
  3168. (defcustom org-highlight-latex-and-related nil
  3169. "Non-nil means highlight LaTeX related syntax in the buffer.
  3170. When non nil, the value should be a list containing any of the
  3171. following symbols:
  3172. `native' Highlight LaTeX snippets and environments natively.
  3173. `latex' Highlight LaTeX snippets and environments.
  3174. `script' Highlight subscript and superscript.
  3175. `entities' Highlight entities."
  3176. :group 'org-appearance
  3177. :version "24.4"
  3178. :package-version '(Org . "8.0")
  3179. :type '(choice
  3180. (const :tag "No highlighting" nil)
  3181. (set :greedy t :tag "Highlight"
  3182. (const :tag "LaTeX snippets and environments (native)" native)
  3183. (const :tag "LaTeX snippets and environments" latex)
  3184. (const :tag "Subscript and superscript" script)
  3185. (const :tag "Entities" entities))))
  3186. (defcustom org-hide-emphasis-markers nil
  3187. "Non-nil mean font-lock should hide the emphasis marker characters."
  3188. :group 'org-appearance
  3189. :type 'boolean
  3190. :safe #'booleanp)
  3191. (defcustom org-hide-macro-markers nil
  3192. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3193. :group 'org-appearance
  3194. :type 'boolean)
  3195. (defcustom org-pretty-entities nil
  3196. "Non-nil means show entities as UTF8 characters.
  3197. When nil, the \\name form remains in the buffer."
  3198. :group 'org-appearance
  3199. :version "24.1"
  3200. :type 'boolean)
  3201. (defcustom org-pretty-entities-include-sub-superscripts t
  3202. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3203. :group 'org-appearance
  3204. :version "24.1"
  3205. :type 'boolean)
  3206. (defvar org-emph-re nil
  3207. "Regular expression for matching emphasis.
  3208. After a match, the match groups contain these elements:
  3209. 0 The match of the full regular expression, including the characters
  3210. before and after the proper match
  3211. 1 The character before the proper match, or empty at beginning of line
  3212. 2 The proper match, including the leading and trailing markers
  3213. 3 The leading marker like * or /, indicating the type of highlighting
  3214. 4 The text between the emphasis markers, not including the markers
  3215. 5 The character after the match, empty at the end of a line")
  3216. (defvar org-verbatim-re nil
  3217. "Regular expression for matching verbatim text.")
  3218. (defvar org-emphasis-regexp-components) ; defined just below
  3219. (defvar org-emphasis-alist) ; defined just below
  3220. (defun org-set-emph-re (var val)
  3221. "Set variable and compute the emphasis regular expression."
  3222. (set var val)
  3223. (when (and (boundp 'org-emphasis-alist)
  3224. (boundp 'org-emphasis-regexp-components)
  3225. org-emphasis-alist org-emphasis-regexp-components)
  3226. (pcase-let*
  3227. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3228. (body (if (<= nl 0) body
  3229. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3230. (template
  3231. (format (concat "\\([%s]\\|^\\)" ;before markers
  3232. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3233. "\\([%s]\\|$\\)") ;after markers
  3234. pre border border body border post)))
  3235. (setq org-emph-re (format template "*/_+"))
  3236. (setq org-verbatim-re (format template "=~")))))
  3237. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3238. ;; set this option proved cumbersome. See this message/thread:
  3239. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3240. (defvar org-emphasis-regexp-components
  3241. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3242. "Components used to build the regular expression for emphasis.
  3243. This is a list with five entries. Terminology: In an emphasis string
  3244. like \" *strong word* \", we call the initial space PREMATCH, the final
  3245. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3246. and \"trong wor\" is the body. The different components in this variable
  3247. specify what is allowed/forbidden in each part:
  3248. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3249. post Chars allowed as postmatch. End of line will be allowed too.
  3250. border The chars *forbidden* as border characters.
  3251. body-regexp A regexp like \".\" to match a body character. Don't use
  3252. non-shy groups here, and don't allow newline here.
  3253. newline The maximum number of newlines allowed in an emphasis exp.
  3254. You need to reload Org or to restart Emacs after setting this.")
  3255. (defcustom org-emphasis-alist
  3256. '(("*" bold)
  3257. ("/" italic)
  3258. ("_" underline)
  3259. ("=" org-verbatim verbatim)
  3260. ("~" org-code verbatim)
  3261. ("+" (:strike-through t)))
  3262. "Alist of characters and faces to emphasize text.
  3263. Text starting and ending with a special character will be emphasized,
  3264. for example *bold*, _underlined_ and /italic/. This variable sets the
  3265. marker characters and the face to be used by font-lock for highlighting
  3266. in Org buffers.
  3267. You need to reload Org or to restart Emacs after customizing this."
  3268. :group 'org-appearance
  3269. :set 'org-set-emph-re
  3270. :version "24.4"
  3271. :package-version '(Org . "8.0")
  3272. :type '(repeat
  3273. (list
  3274. (string :tag "Marker character")
  3275. (choice
  3276. (face :tag "Font-lock-face")
  3277. (plist :tag "Face property list"))
  3278. (option (const verbatim)))))
  3279. (defvar org-protecting-blocks '("src" "example" "export")
  3280. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3281. This is needed for font-lock setup.")
  3282. ;;; Functions and variables from their packages
  3283. ;; Declared here to avoid compiler warnings
  3284. (defvar mark-active)
  3285. ;; Various packages
  3286. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3287. (declare-function calendar-forward-day "cal-move" (arg))
  3288. (declare-function calendar-goto-date "cal-move" (date))
  3289. (declare-function calendar-goto-today "cal-move" ())
  3290. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3291. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3292. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3293. (declare-function cdlatex-tab "ext:cdlatex" ())
  3294. (declare-function dired-get-filename
  3295. "dired"
  3296. (&optional localp no-error-if-not-filep))
  3297. (declare-function iswitchb-read-buffer
  3298. "iswitchb"
  3299. (prompt &optional
  3300. default require-match _predicate start matches-set))
  3301. (declare-function org-agenda-change-all-lines
  3302. "org-agenda"
  3303. (newhead hdmarker &optional fixface just-this))
  3304. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3305. "org-agenda"
  3306. (&optional end))
  3307. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3308. (declare-function org-agenda-format-item
  3309. "org-agenda"
  3310. (extra txt &optional level category tags dotime
  3311. remove-re habitp))
  3312. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3313. (declare-function org-agenda-save-markers-for-cut-and-paste
  3314. "org-agenda"
  3315. (beg end))
  3316. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3317. (declare-function org-agenda-skip "org-agenda" ())
  3318. (declare-function org-attach-expand "org-attach" (file))
  3319. (declare-function org-attach-reveal "org-attach" ())
  3320. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3321. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3322. (declare-function org-indent-mode "org-indent" (&optional arg))
  3323. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3324. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3325. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3326. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3327. (declare-function parse-time-string "parse-time" (string))
  3328. (defvar align-mode-rules-list)
  3329. (defvar calc-embedded-close-formula)
  3330. (defvar calc-embedded-open-formula)
  3331. (defvar calc-embedded-open-mode)
  3332. (defvar font-lock-unfontify-region-function)
  3333. (defvar iswitchb-temp-buflist)
  3334. (defvar org-agenda-tags-todo-honor-ignore-options)
  3335. (defvar remember-data-file)
  3336. (defvar texmathp-why)
  3337. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3338. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3339. (declare-function org-resolve-clocks "org-clock"
  3340. (&optional also-non-dangling-p prompt last-valid))
  3341. (defvar org-clock-start-time)
  3342. (defvar org-clock-marker (make-marker)
  3343. "Marker recording the last clock-in.")
  3344. (defvar org-clock-hd-marker (make-marker)
  3345. "Marker recording the last clock-in, but the headline position.")
  3346. (defvar org-clock-heading ""
  3347. "The heading of the current clock entry.")
  3348. (defun org-clock-is-active ()
  3349. "Return the buffer where the clock is currently running.
  3350. Return nil if no clock is running."
  3351. (marker-buffer org-clock-marker))
  3352. (defun org-check-running-clock ()
  3353. "Check if the current buffer contains the running clock.
  3354. If yes, offer to stop it and to save the buffer with the changes."
  3355. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3356. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3357. (buffer-name))))
  3358. (org-clock-out)
  3359. (when (y-or-n-p "Save changed buffer?")
  3360. (save-buffer))))
  3361. (defun org-clocktable-try-shift (dir n)
  3362. "Check if this line starts a clock table, if yes, shift the time block."
  3363. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3364. (org-clocktable-shift dir n)))
  3365. ;;;###autoload
  3366. (defun org-clock-persistence-insinuate ()
  3367. "Set up hooks for clock persistence."
  3368. (require 'org-clock)
  3369. (add-hook 'org-mode-hook 'org-clock-load)
  3370. (add-hook 'kill-emacs-hook 'org-clock-save))
  3371. (defgroup org-archive nil
  3372. "Options concerning archiving in Org mode."
  3373. :tag "Org Archive"
  3374. :group 'org-structure)
  3375. (defcustom org-archive-location "%s_archive::"
  3376. "The location where subtrees should be archived.
  3377. The value of this variable is a string, consisting of two parts,
  3378. separated by a double-colon. The first part is a filename and
  3379. the second part is a headline.
  3380. When the filename is omitted, archiving happens in the same file.
  3381. %s in the filename will be replaced by the current file
  3382. name (without the directory part). Archiving to a different file
  3383. is useful to keep archived entries from contributing to the
  3384. Org Agenda.
  3385. The archived entries will be filed as subtrees of the specified
  3386. headline. When the headline is omitted, the subtrees are simply
  3387. filed away at the end of the file, as top-level entries. Also in
  3388. the heading you can use %s to represent the file name, this can be
  3389. useful when using the same archive for a number of different files.
  3390. Here are a few examples:
  3391. \"%s_archive::\"
  3392. If the current file is Projects.org, archive in file
  3393. Projects.org_archive, as top-level trees. This is the default.
  3394. \"::* Archived Tasks\"
  3395. Archive in the current file, under the top-level headline
  3396. \"* Archived Tasks\".
  3397. \"~/org/archive.org::\"
  3398. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3399. \"~/org/archive.org::* From %s\"
  3400. Archive in file ~/org/archive.org (absolute path), under headlines
  3401. \"From FILENAME\" where file name is the current file name.
  3402. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3403. The \"datetree/\" string is special, signifying to archive
  3404. items to the datetree. Items are placed in either the CLOSED
  3405. date of the item, or the current date if there is no CLOSED date.
  3406. The heading will be a subentry to the current date. There doesn't
  3407. need to be a heading, but there always needs to be a slash after
  3408. datetree. For example, to store archived items directly in the
  3409. datetree, use \"~/org/datetree.org::datetree/\".
  3410. \"basement::** Finished Tasks\"
  3411. Archive in file ./basement (relative path), as level 3 trees
  3412. below the level 2 heading \"** Finished Tasks\".
  3413. You may set this option on a per-file basis by adding to the buffer a
  3414. line like
  3415. #+ARCHIVE: basement::** Finished Tasks
  3416. You may also define it locally for a subtree by setting an ARCHIVE property
  3417. in the entry. If such a property is found in an entry, or anywhere up
  3418. the hierarchy, it will be used."
  3419. :group 'org-archive
  3420. :type 'string)
  3421. (defcustom org-agenda-skip-archived-trees t
  3422. "Non-nil means the agenda will skip any items located in archived trees.
  3423. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3424. variable is no longer recommended, you should leave it at the value t.
  3425. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3426. :group 'org-archive
  3427. :group 'org-agenda-skip
  3428. :type 'boolean)
  3429. (defcustom org-columns-skip-archived-trees t
  3430. "Non-nil means ignore archived trees when creating column view."
  3431. :group 'org-archive
  3432. :group 'org-properties
  3433. :type 'boolean)
  3434. (defcustom org-cycle-open-archived-trees nil
  3435. "Non-nil means `org-cycle' will open archived trees.
  3436. An archived tree is a tree marked with the tag ARCHIVE.
  3437. When nil, archived trees will stay folded. You can still open them with
  3438. normal outline commands like `show-all', but not with the cycling commands."
  3439. :group 'org-archive
  3440. :group 'org-cycle
  3441. :type 'boolean)
  3442. (defcustom org-sparse-tree-open-archived-trees nil
  3443. "Non-nil means sparse tree construction shows matches in archived trees.
  3444. When nil, matches in these trees are highlighted, but the trees are kept in
  3445. collapsed state."
  3446. :group 'org-archive
  3447. :group 'org-sparse-trees
  3448. :type 'boolean)
  3449. (defcustom org-sparse-tree-default-date-type nil
  3450. "The default date type when building a sparse tree.
  3451. When this is nil, a date is a scheduled or a deadline timestamp.
  3452. Otherwise, these types are allowed:
  3453. all: all timestamps
  3454. active: only active timestamps (<...>)
  3455. inactive: only inactive timestamps ([...])
  3456. scheduled: only scheduled timestamps
  3457. deadline: only deadline timestamps"
  3458. :type '(choice (const :tag "Scheduled or deadline" nil)
  3459. (const :tag "All timestamps" all)
  3460. (const :tag "Only active timestamps" active)
  3461. (const :tag "Only inactive timestamps" inactive)
  3462. (const :tag "Only scheduled timestamps" scheduled)
  3463. (const :tag "Only deadline timestamps" deadline)
  3464. (const :tag "Only closed timestamps" closed))
  3465. :version "26.1"
  3466. :package-version '(Org . "8.3")
  3467. :group 'org-sparse-trees)
  3468. (defun org-cycle-hide-archived-subtrees (state)
  3469. "Re-hide all archived subtrees after a visibility state change.
  3470. STATE should be one of the symbols listed in the docstring of
  3471. `org-cycle-hook'."
  3472. (when (and (not org-cycle-open-archived-trees)
  3473. (not (memq state '(overview folded))))
  3474. (save-excursion
  3475. (let* ((globalp (memq state '(contents all)))
  3476. (beg (if globalp (point-min) (point)))
  3477. (end (if globalp (point-max) (org-end-of-subtree t))))
  3478. (org-hide-archived-subtrees beg end)
  3479. (goto-char beg)
  3480. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3481. (message "%s" (substitute-command-keys
  3482. "Subtree is archived and stays closed. Use \
  3483. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3484. (defun org-force-cycle-archived ()
  3485. "Cycle subtree even if it is archived."
  3486. (interactive)
  3487. (setq this-command 'org-cycle)
  3488. (let ((org-cycle-open-archived-trees t))
  3489. (call-interactively 'org-cycle)))
  3490. (defun org-hide-archived-subtrees (beg end)
  3491. "Re-hide all archived subtrees after a visibility state change."
  3492. (org-with-wide-buffer
  3493. (let ((case-fold-search nil)
  3494. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3495. (goto-char beg)
  3496. ;; Include headline point is currently on.
  3497. (beginning-of-line)
  3498. (while (and (< (point) end) (re-search-forward re end t))
  3499. (when (member org-archive-tag (org-get-tags nil t))
  3500. (org-flag-subtree t)
  3501. (org-end-of-subtree t))))))
  3502. (defun org-flag-subtree (flag)
  3503. (save-excursion
  3504. (org-back-to-heading t)
  3505. (org-flag-region (line-end-position)
  3506. (progn (org-end-of-subtree t) (point))
  3507. flag
  3508. 'outline)))
  3509. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3510. ;; Declare Column View Code
  3511. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3512. (declare-function org-columns-compute "org-colview" (property))
  3513. ;; Declare ID code
  3514. (declare-function org-id-store-link "org-id")
  3515. (declare-function org-id-locations-load "org-id")
  3516. (declare-function org-id-locations-save "org-id")
  3517. (defvar org-id-track-globally)
  3518. ;;; Variables for pre-computed regular expressions, all buffer local
  3519. (defvar-local org-todo-regexp nil
  3520. "Matches any of the TODO state keywords.
  3521. Since TODO keywords are case-sensitive, `case-fold-search' is
  3522. expected to be bound to nil when matching against this regexp.")
  3523. (defvar-local org-not-done-regexp nil
  3524. "Matches any of the TODO state keywords except the last one.
  3525. Since TODO keywords are case-sensitive, `case-fold-search' is
  3526. expected to be bound to nil when matching against this regexp.")
  3527. (defvar-local org-not-done-heading-regexp nil
  3528. "Matches a TODO headline that is not done.
  3529. Since TODO keywords are case-sensitive, `case-fold-search' is
  3530. expected to be bound to nil when matching against this regexp.")
  3531. (defvar-local org-todo-line-regexp nil
  3532. "Matches a headline and puts TODO state into group 2 if present.
  3533. Since TODO keywords are case-sensitive, `case-fold-search' is
  3534. expected to be bound to nil when matching against this regexp.")
  3535. (defvar-local org-complex-heading-regexp nil
  3536. "Matches a headline and puts everything into groups:
  3537. group 1: Stars
  3538. group 2: The TODO keyword, maybe
  3539. group 3: Priority cookie
  3540. group 4: True headline
  3541. group 5: Tags
  3542. Since TODO keywords are case-sensitive, `case-fold-search' is
  3543. expected to be bound to nil when matching against this regexp.")
  3544. (defvar-local org-complex-heading-regexp-format nil
  3545. "Printf format to make regexp to match an exact headline.
  3546. This regexp will match the headline of any node which has the
  3547. exact headline text that is put into the format, but may have any
  3548. TODO state, priority and tags.")
  3549. (defvar-local org-todo-line-tags-regexp nil
  3550. "Matches a headline and puts TODO state into group 2 if present.
  3551. Also put tags into group 4 if tags are present.")
  3552. (defconst org-plain-time-of-day-regexp
  3553. (concat
  3554. "\\(\\<[012]?[0-9]"
  3555. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3556. "\\(--?"
  3557. "\\(\\<[012]?[0-9]"
  3558. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3559. "\\)?")
  3560. "Regular expression to match a plain time or time range.
  3561. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3562. groups carry important information:
  3563. 0 the full match
  3564. 1 the first time, range or not
  3565. 8 the second time, if it is a range.")
  3566. (defconst org-plain-time-extension-regexp
  3567. (concat
  3568. "\\(\\<[012]?[0-9]"
  3569. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3570. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3571. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3572. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3573. groups carry important information:
  3574. 0 the full match
  3575. 7 hours of duration
  3576. 9 minutes of duration")
  3577. (defconst org-stamp-time-of-day-regexp
  3578. (concat
  3579. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3580. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3581. "\\(--?"
  3582. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3583. "Regular expression to match a timestamp time or time range.
  3584. After a match, the following groups carry important information:
  3585. 0 the full match
  3586. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3587. 2 the first time, range or not
  3588. 4 the second time, if it is a range.")
  3589. (defconst org-startup-options
  3590. '(("fold" org-startup-folded t)
  3591. ("overview" org-startup-folded t)
  3592. ("nofold" org-startup-folded nil)
  3593. ("showall" org-startup-folded nil)
  3594. ("showeverything" org-startup-folded showeverything)
  3595. ("content" org-startup-folded content)
  3596. ("indent" org-startup-indented t)
  3597. ("noindent" org-startup-indented nil)
  3598. ("hidestars" org-hide-leading-stars t)
  3599. ("showstars" org-hide-leading-stars nil)
  3600. ("odd" org-odd-levels-only t)
  3601. ("oddeven" org-odd-levels-only nil)
  3602. ("align" org-startup-align-all-tables t)
  3603. ("noalign" org-startup-align-all-tables nil)
  3604. ("shrink" org-startup-shrink-all-tables t)
  3605. ("inlineimages" org-startup-with-inline-images t)
  3606. ("noinlineimages" org-startup-with-inline-images nil)
  3607. ("latexpreview" org-startup-with-latex-preview t)
  3608. ("nolatexpreview" org-startup-with-latex-preview nil)
  3609. ("customtime" org-display-custom-times t)
  3610. ("logdone" org-log-done time)
  3611. ("lognotedone" org-log-done note)
  3612. ("nologdone" org-log-done nil)
  3613. ("lognoteclock-out" org-log-note-clock-out t)
  3614. ("nolognoteclock-out" org-log-note-clock-out nil)
  3615. ("logrepeat" org-log-repeat state)
  3616. ("lognoterepeat" org-log-repeat note)
  3617. ("logdrawer" org-log-into-drawer t)
  3618. ("nologdrawer" org-log-into-drawer nil)
  3619. ("logstatesreversed" org-log-states-order-reversed t)
  3620. ("nologstatesreversed" org-log-states-order-reversed nil)
  3621. ("nologrepeat" org-log-repeat nil)
  3622. ("logreschedule" org-log-reschedule time)
  3623. ("lognotereschedule" org-log-reschedule note)
  3624. ("nologreschedule" org-log-reschedule nil)
  3625. ("logredeadline" org-log-redeadline time)
  3626. ("lognoteredeadline" org-log-redeadline note)
  3627. ("nologredeadline" org-log-redeadline nil)
  3628. ("logrefile" org-log-refile time)
  3629. ("lognoterefile" org-log-refile note)
  3630. ("nologrefile" org-log-refile nil)
  3631. ("fninline" org-footnote-define-inline t)
  3632. ("nofninline" org-footnote-define-inline nil)
  3633. ("fnlocal" org-footnote-section nil)
  3634. ("fnauto" org-footnote-auto-label t)
  3635. ("fnprompt" org-footnote-auto-label nil)
  3636. ("fnconfirm" org-footnote-auto-label confirm)
  3637. ("fnplain" org-footnote-auto-label plain)
  3638. ("fnadjust" org-footnote-auto-adjust t)
  3639. ("nofnadjust" org-footnote-auto-adjust nil)
  3640. ("constcgs" constants-unit-system cgs)
  3641. ("constSI" constants-unit-system SI)
  3642. ("noptag" org-tag-persistent-alist nil)
  3643. ("hideblocks" org-hide-block-startup t)
  3644. ("nohideblocks" org-hide-block-startup nil)
  3645. ("beamer" org-startup-with-beamer-mode t)
  3646. ("entitiespretty" org-pretty-entities t)
  3647. ("entitiesplain" org-pretty-entities nil))
  3648. "Variable associated with STARTUP options for Org.
  3649. Each element is a list of three items: the startup options (as written
  3650. in the #+STARTUP line), the corresponding variable, and the value to set
  3651. this variable to if the option is found. An optional forth element PUSH
  3652. means to push this value onto the list in the variable.")
  3653. (defcustom org-group-tags t
  3654. "When non-nil (the default), use group tags.
  3655. This can be turned on/off through `org-toggle-tags-groups'."
  3656. :group 'org-tags
  3657. :group 'org-startup
  3658. :type 'boolean)
  3659. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3660. (defun org-toggle-tags-groups ()
  3661. "Toggle support for group tags.
  3662. Support for group tags is controlled by the option
  3663. `org-group-tags', which is non-nil by default."
  3664. (interactive)
  3665. (setq org-group-tags (not org-group-tags))
  3666. (cond ((and (derived-mode-p 'org-agenda-mode)
  3667. org-group-tags)
  3668. (org-agenda-redo))
  3669. ((derived-mode-p 'org-mode)
  3670. (let ((org-inhibit-startup t)) (org-mode))))
  3671. (message "Groups tags support has been turned %s"
  3672. (if org-group-tags "on" "off")))
  3673. (defun org--tag-add-to-alist (alist1 alist2)
  3674. "Merge tags from ALIST1 into ALIST2.
  3675. Duplicates tags outside a group are removed. Keywords and order
  3676. are preserved.
  3677. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3678. See `org-tag-alist' for their structure."
  3679. (cond
  3680. ((null alist2) alist1)
  3681. ((null alist1) alist2)
  3682. (t
  3683. (let ((to-add nil)
  3684. (group-flag nil))
  3685. (dolist (tag-pair alist1)
  3686. (pcase tag-pair
  3687. (`(,(or :startgrouptag :startgroup))
  3688. (setq group-flag t)
  3689. (push tag-pair to-add))
  3690. (`(,(or :endgrouptag :endgroup))
  3691. (setq group-flag nil)
  3692. (push tag-pair to-add))
  3693. (`(,(or :grouptags :newline))
  3694. (push tag-pair to-add))
  3695. (`(,tag . ,_)
  3696. ;; Remove duplicates from ALIST1, unless they are in
  3697. ;; a group. Indeed, it makes sense to have a tag appear in
  3698. ;; multiple groups.
  3699. (when (or group-flag (not (assoc tag alist2)))
  3700. (push tag-pair to-add)))
  3701. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3702. ;; Preserve order of ALIST1.
  3703. (append (nreverse to-add) alist2)))))
  3704. (defun org-set-regexps-and-options (&optional tags-only)
  3705. "Precompute regular expressions used in the current buffer.
  3706. When optional argument TAGS-ONLY is non-nil, only compute tags
  3707. related expressions."
  3708. (when (derived-mode-p 'org-mode)
  3709. (let ((alist (org--setup-collect-keywords
  3710. (org-make-options-regexp
  3711. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3712. (and (not tags-only)
  3713. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3714. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3715. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3716. ;; Startup options. Get this early since it does change
  3717. ;; behavior for other options (e.g., tags).
  3718. (let ((startup (cdr (assq 'startup alist))))
  3719. (dolist (option startup)
  3720. (let ((entry (assoc-string option org-startup-options t)))
  3721. (when entry
  3722. (let ((var (nth 1 entry))
  3723. (val (nth 2 entry)))
  3724. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3725. (unless (listp (symbol-value var))
  3726. (set (make-local-variable var) nil))
  3727. (add-to-list var val)))))))
  3728. (setq-local org-file-tags
  3729. (mapcar #'org-add-prop-inherited
  3730. (cdr (assq 'filetags alist))))
  3731. (setq org-current-tag-alist
  3732. (org--tag-add-to-alist
  3733. org-tag-persistent-alist
  3734. (let ((tags (cdr (assq 'tags alist))))
  3735. (if tags (org-tag-string-to-alist tags)
  3736. org-tag-alist))))
  3737. (setq org-tag-groups-alist
  3738. (org-tag-alist-to-groups org-current-tag-alist))
  3739. (unless tags-only
  3740. ;; File properties.
  3741. (setq-local org-file-properties (cdr (assq 'property alist)))
  3742. ;; Archive location.
  3743. (let ((archive (cdr (assq 'archive alist))))
  3744. (when archive (setq-local org-archive-location archive)))
  3745. ;; Category.
  3746. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3747. (when cat
  3748. (setq-local org-category (intern cat))
  3749. (setq-local org-file-properties
  3750. (org--update-property-plist
  3751. "CATEGORY" cat org-file-properties))))
  3752. ;; Columns.
  3753. (let ((column (cdr (assq 'columns alist))))
  3754. (when column (setq-local org-columns-default-format column)))
  3755. ;; Constants.
  3756. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3757. ;; Link abbreviations.
  3758. (let ((links (cdr (assq 'link alist))))
  3759. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3760. ;; Priorities.
  3761. (let ((priorities (cdr (assq 'priorities alist))))
  3762. (when priorities
  3763. (setq-local org-highest-priority (nth 0 priorities))
  3764. (setq-local org-lowest-priority (nth 1 priorities))
  3765. (setq-local org-default-priority (nth 2 priorities))))
  3766. ;; Scripts.
  3767. (let ((scripts (assq 'scripts alist)))
  3768. (when scripts
  3769. (setq-local org-use-sub-superscripts (cdr scripts))))
  3770. ;; TODO keywords.
  3771. (setq-local org-todo-kwd-alist nil)
  3772. (setq-local org-todo-key-alist nil)
  3773. (setq-local org-todo-key-trigger nil)
  3774. (setq-local org-todo-keywords-1 nil)
  3775. (setq-local org-done-keywords nil)
  3776. (setq-local org-todo-heads nil)
  3777. (setq-local org-todo-sets nil)
  3778. (setq-local org-todo-log-states nil)
  3779. (let ((todo-sequences
  3780. (or (nreverse (cdr (assq 'todo alist)))
  3781. (let ((d (default-value 'org-todo-keywords)))
  3782. (if (not (stringp (car d))) d
  3783. ;; XXX: Backward compatibility code.
  3784. (list (cons org-todo-interpretation d)))))))
  3785. (dolist (sequence todo-sequences)
  3786. (let* ((sequence (or (run-hook-with-args-until-success
  3787. 'org-todo-setup-filter-hook sequence)
  3788. sequence))
  3789. (sequence-type (car sequence))
  3790. (keywords (cdr sequence))
  3791. (sep (member "|" keywords))
  3792. names alist)
  3793. (dolist (k (remove "|" keywords))
  3794. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3795. k)
  3796. (error "Invalid TODO keyword %s" k))
  3797. (let ((name (match-string 1 k))
  3798. (key (match-string 2 k))
  3799. (log (org-extract-log-state-settings k)))
  3800. (push name names)
  3801. (push (cons name (and key (string-to-char key))) alist)
  3802. (when log (push log org-todo-log-states))))
  3803. (let* ((names (nreverse names))
  3804. (done (if sep (org-remove-keyword-keys (cdr sep))
  3805. (last names)))
  3806. (head (car names))
  3807. (tail (list sequence-type head (car done) (org-last done))))
  3808. (add-to-list 'org-todo-heads head 'append)
  3809. (push names org-todo-sets)
  3810. (setq org-done-keywords (append org-done-keywords done nil))
  3811. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3812. (setq org-todo-key-alist
  3813. (append org-todo-key-alist
  3814. (and alist
  3815. (append '((:startgroup))
  3816. (nreverse alist)
  3817. '((:endgroup))))))
  3818. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3819. (setq org-todo-sets (nreverse org-todo-sets)
  3820. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3821. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3822. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3823. ;; Compute the regular expressions and other local variables.
  3824. ;; Using `org-outline-regexp-bol' would complicate them much,
  3825. ;; because of the fixed white space at the end of that string.
  3826. (unless org-done-keywords
  3827. (setq org-done-keywords
  3828. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3829. (setq org-not-done-keywords
  3830. (org-delete-all org-done-keywords
  3831. (copy-sequence org-todo-keywords-1))
  3832. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3833. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3834. org-not-done-heading-regexp
  3835. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3836. org-todo-line-regexp
  3837. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3838. org-complex-heading-regexp
  3839. (concat "^\\(\\*+\\)"
  3840. "\\(?: +" org-todo-regexp "\\)?"
  3841. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3842. "\\(?: +\\(.*?\\)\\)??"
  3843. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3844. "[ \t]*$")
  3845. org-complex-heading-regexp-format
  3846. (concat "^\\(\\*+\\)"
  3847. "\\(?: +" org-todo-regexp "\\)?"
  3848. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3849. "\\(?: +"
  3850. ;; Stats cookies can be stuck to body.
  3851. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3852. "\\(%s\\)"
  3853. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3854. "\\)"
  3855. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3856. "[ \t]*$")
  3857. org-todo-line-tags-regexp
  3858. (concat "^\\(\\*+\\)"
  3859. "\\(?: +" org-todo-regexp "\\)?"
  3860. "\\(?: +\\(.*?\\)\\)??"
  3861. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3862. "[ \t]*$"))
  3863. (org-compute-latex-and-related-regexp)))))
  3864. (defun org--setup-collect-keywords (regexp &optional files alist)
  3865. "Return setup keywords values as an alist.
  3866. REGEXP matches a subset of setup keywords. FILES is a list of
  3867. file names already visited. It is used to avoid circular setup
  3868. files. ALIST, when non-nil, is the alist computed so far.
  3869. Return value contains the following keys: `archive', `category',
  3870. `columns', `constants', `filetags', `link', `priorities',
  3871. `property', `scripts', `startup', `tags' and `todo'."
  3872. (org-with-wide-buffer
  3873. (goto-char (point-min))
  3874. (let ((case-fold-search t))
  3875. (while (re-search-forward regexp nil t)
  3876. (let ((element (org-element-at-point)))
  3877. (when (eq (org-element-type element) 'keyword)
  3878. (let ((key (org-element-property :key element))
  3879. (value (org-element-property :value element)))
  3880. (cond
  3881. ((equal key "ARCHIVE")
  3882. (when (org-string-nw-p value)
  3883. (push (cons 'archive value) alist)))
  3884. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3885. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3886. ((equal key "CONSTANTS")
  3887. (let* ((constants (assq 'constants alist))
  3888. (store (cdr constants)))
  3889. (dolist (pair (split-string value))
  3890. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3891. pair)
  3892. (let* ((name (match-string 1 pair))
  3893. (value (match-string 2 pair))
  3894. (old (assoc name store)))
  3895. (if old (setcdr old value)
  3896. (push (cons name value) store)))))
  3897. (if constants (setcdr constants store)
  3898. (push (cons 'constants store) alist))))
  3899. ((equal key "FILETAGS")
  3900. (when (org-string-nw-p value)
  3901. (let ((old (assq 'filetags alist))
  3902. (new (apply #'nconc
  3903. (mapcar (lambda (x) (org-split-string x ":"))
  3904. (split-string value)))))
  3905. (if old (setcdr old (append new (cdr old)))
  3906. (push (cons 'filetags new) alist)))))
  3907. ((equal key "LINK")
  3908. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3909. (let ((links (assq 'link alist))
  3910. (pair (cons (match-string-no-properties 1 value)
  3911. (match-string-no-properties 2 value))))
  3912. (if links (push pair (cdr links))
  3913. (push (list 'link pair) alist)))))
  3914. ((equal key "OPTIONS")
  3915. (when (and (org-string-nw-p value)
  3916. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3917. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3918. ((equal key "PRIORITIES")
  3919. (push (cons 'priorities
  3920. (let ((prio (split-string value)))
  3921. (if (< (length prio) 3) '(?A ?C ?B)
  3922. (mapcar #'string-to-char prio))))
  3923. alist))
  3924. ((equal key "PROPERTY")
  3925. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3926. (let* ((property (assq 'property alist))
  3927. (value (org--update-property-plist
  3928. (match-string-no-properties 1 value)
  3929. (match-string-no-properties 2 value)
  3930. (cdr property))))
  3931. (if property (setcdr property value)
  3932. (push (cons 'property value) alist)))))
  3933. ((equal key "STARTUP")
  3934. (let ((startup (assq 'startup alist)))
  3935. (if startup
  3936. (setcdr startup
  3937. (append (cdr startup) (split-string value)))
  3938. (push (cons 'startup (split-string value)) alist))))
  3939. ((equal key "TAGS")
  3940. (let ((tag-cell (assq 'tags alist)))
  3941. (if tag-cell
  3942. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3943. (push (cons 'tags value) alist))))
  3944. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3945. (let ((todo (assq 'todo alist))
  3946. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3947. (split-string value))))
  3948. (if todo (push value (cdr todo))
  3949. (push (list 'todo value) alist))))
  3950. ((equal key "SETUPFILE")
  3951. (unless buffer-read-only ; Do not check in Gnus messages.
  3952. (let ((f (and (org-string-nw-p value)
  3953. (expand-file-name (org-strip-quotes value)))))
  3954. (when (and f (file-readable-p f) (not (member f files)))
  3955. (with-temp-buffer
  3956. (setq default-directory (file-name-directory f))
  3957. (insert-file-contents f)
  3958. (setq alist
  3959. ;; Fake Org mode to benefit from cache
  3960. ;; without recurring needlessly.
  3961. (let ((major-mode 'org-mode))
  3962. (org--setup-collect-keywords
  3963. regexp (cons f files) alist)))))))))))))))
  3964. alist)
  3965. (defun org-tag-string-to-alist (s)
  3966. "Return tag alist associated to string S.
  3967. S is a value for TAGS keyword or produced with
  3968. `org-tag-alist-to-string'. Return value is an alist suitable for
  3969. `org-tag-alist' or `org-tag-persistent-alist'."
  3970. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3971. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3972. "\\(?:(\\(.\\))\\)?\\'"))
  3973. alist group-flag)
  3974. (dolist (tokens lines (cdr (nreverse alist)))
  3975. (push '(:newline) alist)
  3976. (while tokens
  3977. (let ((token (pop tokens)))
  3978. (pcase token
  3979. ("{"
  3980. (push '(:startgroup) alist)
  3981. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3982. ("}"
  3983. (push '(:endgroup) alist)
  3984. (setq group-flag nil))
  3985. ("["
  3986. (push '(:startgrouptag) alist)
  3987. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3988. ("]"
  3989. (push '(:endgrouptag) alist)
  3990. (setq group-flag nil))
  3991. (":"
  3992. (push '(:grouptags) alist))
  3993. ((guard (string-match tag-re token))
  3994. (let ((tag (match-string 1 token))
  3995. (key (and (match-beginning 2)
  3996. (string-to-char (match-string 2 token)))))
  3997. ;; Push all tags in groups, no matter if they already
  3998. ;; appear somewhere else in the list.
  3999. (when (or group-flag (not (assoc tag alist)))
  4000. (push (cons tag key) alist))))))))))
  4001. (defun org-tag-alist-to-string (alist &optional skip-key)
  4002. "Return tag string associated to ALIST.
  4003. ALIST is an alist, as defined in `org-tag-alist' or
  4004. `org-tag-persistent-alist', or produced with
  4005. `org-tag-string-to-alist'.
  4006. Return value is a string suitable as a value for \"TAGS\"
  4007. keyword.
  4008. When optional argument SKIP-KEY is non-nil, skip selection keys
  4009. next to tags."
  4010. (mapconcat (lambda (token)
  4011. (pcase token
  4012. (`(:startgroup) "{")
  4013. (`(:endgroup) "}")
  4014. (`(:startgrouptag) "[")
  4015. (`(:endgrouptag) "]")
  4016. (`(:grouptags) ":")
  4017. (`(:newline) "\\n")
  4018. ((and
  4019. (guard (not skip-key))
  4020. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4021. (format "%s(%c)" tag key))
  4022. (`(,(and tag (pred stringp)) . ,_) tag)
  4023. (_ (user-error "Invalid tag token: %S" token))))
  4024. alist
  4025. " "))
  4026. (defun org-tag-alist-to-groups (alist)
  4027. "Return group alist from tag ALIST.
  4028. ALIST is an alist, as defined in `org-tag-alist' or
  4029. `org-tag-persistent-alist', or produced with
  4030. `org-tag-string-to-alist'. Return value is an alist following
  4031. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4032. a string, summarizing TAGS, as a list of strings."
  4033. (let (groups group-status current-group)
  4034. (dolist (token alist (nreverse groups))
  4035. (pcase token
  4036. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4037. (`(,(or :endgroup :endgrouptag))
  4038. (when (eq group-status 'append)
  4039. (push (nreverse current-group) groups))
  4040. (setq group-status nil current-group nil))
  4041. (`(:grouptags) (setq group-status 'append))
  4042. ((and `(,tag . ,_) (guard group-status))
  4043. (if (eq group-status 'append) (push tag current-group)
  4044. (setq current-group (list tag))))
  4045. (_ nil)))))
  4046. (defvar org--file-cache (make-hash-table :test #'equal)
  4047. "Hash table to store contents of files referenced via a URL.
  4048. This is the cache of file URLs read using `org-file-contents'.")
  4049. (defun org-reset-file-cache ()
  4050. "Reset the cache of files downloaded by `org-file-contents'."
  4051. (clrhash org--file-cache))
  4052. (defun org-file-url-p (file)
  4053. "Non-nil if FILE is a URL."
  4054. (require 'ffap)
  4055. (string-match-p ffap-url-regexp file))
  4056. (defun org-file-contents (file &optional noerror nocache)
  4057. "Return the contents of FILE, as a string.
  4058. FILE can be a file name or URL.
  4059. If FILE is a URL, download the contents. If the URL contents are
  4060. already cached in the `org--file-cache' hash table, the download step
  4061. is skipped.
  4062. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4063. from file or URL.
  4064. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4065. is available. This option applies only if FILE is a URL."
  4066. (let* ((is-url (org-file-url-p file))
  4067. (cache (and is-url
  4068. (not nocache)
  4069. (gethash file org--file-cache))))
  4070. (cond
  4071. (cache)
  4072. (is-url
  4073. (with-current-buffer (url-retrieve-synchronously file)
  4074. (goto-char (point-min))
  4075. ;; Move point to after the url-retrieve header.
  4076. (search-forward "\n\n" nil :move)
  4077. ;; Search for the success code only in the url-retrieve header.
  4078. (if (save-excursion
  4079. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4080. ;; Update the cache `org--file-cache' and return contents.
  4081. (puthash file
  4082. (buffer-substring-no-properties (point) (point-max))
  4083. org--file-cache)
  4084. (funcall (if noerror #'message #'user-error)
  4085. "Unable to fetch file from %S"
  4086. file))))
  4087. (t
  4088. (with-temp-buffer
  4089. (condition-case nil
  4090. (progn
  4091. (insert-file-contents file)
  4092. (buffer-string))
  4093. (file-error
  4094. (funcall (if noerror #'message #'user-error)
  4095. "Unable to read file %S"
  4096. file))))))))
  4097. (defun org-extract-log-state-settings (x)
  4098. "Extract the log state setting from a TODO keyword string.
  4099. This will extract info from a string like \"WAIT(w@/!)\"."
  4100. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4101. (let ((kw (match-string 1 x))
  4102. (log1 (and (match-end 3) (match-string 3 x)))
  4103. (log2 (and (match-end 4) (match-string 4 x))))
  4104. (and (or log1 log2)
  4105. (list kw
  4106. (and log1 (if (equal log1 "!") 'time 'note))
  4107. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4108. (defun org-remove-keyword-keys (list)
  4109. "Remove a pair of parenthesis at the end of each string in LIST."
  4110. (mapcar (lambda (x)
  4111. (if (string-match "(.*)$" x)
  4112. (substring x 0 (match-beginning 0))
  4113. x))
  4114. list))
  4115. (defun org-assign-fast-keys (alist)
  4116. "Assign fast keys to a keyword-key alist.
  4117. Respect keys that are already there."
  4118. (let (new e (alt ?0))
  4119. (while (setq e (pop alist))
  4120. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4121. (cdr e)) ;; Key already assigned.
  4122. (push e new)
  4123. (let ((clist (string-to-list (downcase (car e))))
  4124. (used (append new alist)))
  4125. (when (= (car clist) ?@)
  4126. (pop clist))
  4127. (while (and clist (rassoc (car clist) used))
  4128. (pop clist))
  4129. (unless clist
  4130. (while (rassoc alt used)
  4131. (cl-incf alt)))
  4132. (push (cons (car e) (or (car clist) alt)) new))))
  4133. (nreverse new)))
  4134. ;;; Some variables used in various places
  4135. (defvar org-window-configuration nil
  4136. "Used in various places to store a window configuration.")
  4137. (defvar org-selected-window nil
  4138. "Used in various places to store a window configuration.")
  4139. (defvar org-finish-function nil
  4140. "Function to be called when `C-c C-c' is used.
  4141. This is for getting out of special buffers like capture.")
  4142. (defvar org-last-state)
  4143. ;; Defined somewhere in this file, but used before definition.
  4144. (defvar org-entities) ;; defined in org-entities.el
  4145. (defvar org-struct-menu)
  4146. (defvar org-org-menu)
  4147. (defvar org-tbl-menu)
  4148. ;;;; Define the Org mode
  4149. (defun org-before-change-function (_beg _end)
  4150. "Every change indicates that a table might need an update."
  4151. (setq org-table-may-need-update t))
  4152. (defvar org-mode-map)
  4153. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4154. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4155. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4156. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4157. (defvar bidi-paragraph-direction)
  4158. (defvar buffer-face-mode-face)
  4159. (require 'outline)
  4160. ;; Other stuff we need.
  4161. (require 'time-date)
  4162. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4163. (require 'easymenu)
  4164. (autoload 'easy-menu-add "easymenu")
  4165. (require 'overlay)
  4166. ;; (require 'org-macs) moved higher up in the file before it is first used
  4167. (require 'org-entities)
  4168. ;; (require 'org-compat) moved higher up in the file before it is first used
  4169. (require 'org-faces)
  4170. (require 'org-list)
  4171. (require 'org-pcomplete)
  4172. (require 'org-src)
  4173. (require 'org-footnote)
  4174. (require 'org-macro)
  4175. ;; babel
  4176. (require 'ob)
  4177. ;;;###autoload
  4178. (define-derived-mode org-mode outline-mode "Org"
  4179. "Outline-based notes management and organizer, alias
  4180. \"Carsten's outline-mode for keeping track of everything.\"
  4181. Org mode develops organizational tasks around a NOTES file which
  4182. contains information about projects as plain text. Org mode is
  4183. implemented on top of Outline mode, which is ideal to keep the content
  4184. of large files well structured. It supports ToDo items, deadlines and
  4185. time stamps, which magically appear in the diary listing of the Emacs
  4186. calendar. Tables are easily created with a built-in table editor.
  4187. Plain text URL-like links connect to websites, emails (VM), Usenet
  4188. messages (Gnus), BBDB entries, and any files related to the project.
  4189. For printing and sharing of notes, an Org file (or a part of it)
  4190. can be exported as a structured ASCII or HTML file.
  4191. The following commands are available:
  4192. \\{org-mode-map}"
  4193. (org-load-modules-maybe)
  4194. (org-install-agenda-files-menu)
  4195. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4196. (add-to-invisibility-spec '(org-hide-block . t))
  4197. (add-to-invisibility-spec '(org-hide-drawer . t))
  4198. (setq-local outline-regexp org-outline-regexp)
  4199. (setq-local outline-level 'org-outline-level)
  4200. (setq bidi-paragraph-direction 'left-to-right)
  4201. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4202. (unless org-display-table
  4203. (setq org-display-table (make-display-table)))
  4204. (set-display-table-slot
  4205. org-display-table 4
  4206. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4207. org-ellipsis)))
  4208. (setq buffer-display-table org-display-table))
  4209. (org-set-regexps-and-options)
  4210. (org-set-font-lock-defaults)
  4211. (when (and org-tag-faces (not org-tags-special-faces-re))
  4212. ;; tag faces set outside customize.... force initialization.
  4213. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4214. ;; Calc embedded
  4215. (setq-local calc-embedded-open-mode "# ")
  4216. ;; Modify a few syntax entries
  4217. (modify-syntax-entry ?\" "\"")
  4218. (modify-syntax-entry ?\\ "_")
  4219. (modify-syntax-entry ?~ "_")
  4220. (modify-syntax-entry ?< "(>")
  4221. (modify-syntax-entry ?> ")<")
  4222. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4223. ;; Activate before-change-function
  4224. (setq-local org-table-may-need-update t)
  4225. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4226. ;; Check for running clock before killing a buffer
  4227. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4228. ;; Initialize macros templates.
  4229. (org-macro-initialize-templates)
  4230. ;; Initialize radio targets.
  4231. (org-update-radio-target-regexp)
  4232. ;; Indentation.
  4233. (setq-local indent-line-function 'org-indent-line)
  4234. (setq-local indent-region-function 'org-indent-region)
  4235. ;; Filling and auto-filling.
  4236. (org-setup-filling)
  4237. ;; Comments.
  4238. (org-setup-comments-handling)
  4239. ;; Initialize cache.
  4240. (org-element-cache-reset)
  4241. ;; Beginning/end of defun
  4242. (setq-local beginning-of-defun-function 'org-backward-element)
  4243. (setq-local end-of-defun-function
  4244. (lambda ()
  4245. (if (not (org-at-heading-p))
  4246. (org-forward-element)
  4247. (org-forward-element)
  4248. (forward-char -1))))
  4249. ;; Next error for sparse trees
  4250. (setq-local next-error-function 'org-occur-next-match)
  4251. ;; Make commit log messages from Org documents easier.
  4252. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4253. ;; Make sure dependence stuff works reliably, even for users who set it
  4254. ;; too late :-(
  4255. (if org-enforce-todo-dependencies
  4256. (add-hook 'org-blocker-hook
  4257. 'org-block-todo-from-children-or-siblings-or-parent)
  4258. (remove-hook 'org-blocker-hook
  4259. 'org-block-todo-from-children-or-siblings-or-parent))
  4260. (if org-enforce-todo-checkbox-dependencies
  4261. (add-hook 'org-blocker-hook
  4262. 'org-block-todo-from-checkboxes)
  4263. (remove-hook 'org-blocker-hook
  4264. 'org-block-todo-from-checkboxes))
  4265. ;; Align options lines
  4266. (setq-local
  4267. align-mode-rules-list
  4268. '((org-in-buffer-settings
  4269. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4270. (modes . '(org-mode)))))
  4271. ;; Make isearch reveal context
  4272. (setq-local outline-isearch-open-invisible-function
  4273. (lambda (&rest _) (org-show-context 'isearch)))
  4274. ;; Setup the pcomplete hooks
  4275. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4276. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4277. (setq-local pcomplete-default-completion-function 'ignore)
  4278. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4279. (setq-local pcomplete-termination-string "")
  4280. (setq-local buffer-face-mode-face 'org-default)
  4281. ;; If empty file that did not turn on Org mode automatically, make
  4282. ;; it to.
  4283. (when (and org-insert-mode-line-in-empty-file
  4284. (called-interactively-p 'any)
  4285. (= (point-min) (point-max)))
  4286. (insert "# -*- mode: org -*-\n\n"))
  4287. (unless org-inhibit-startup
  4288. (org-unmodified
  4289. (when org-startup-with-beamer-mode (org-beamer-mode))
  4290. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4291. (org-table-map-tables
  4292. (cond ((and org-startup-align-all-tables
  4293. org-startup-shrink-all-tables)
  4294. (lambda () (org-table-align) (org-table-shrink)))
  4295. (org-startup-align-all-tables #'org-table-align)
  4296. (t #'org-table-shrink))
  4297. t))
  4298. (when org-startup-with-inline-images (org-display-inline-images))
  4299. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4300. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4301. (when org-startup-truncated (setq truncate-lines t))
  4302. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4303. ;; Try to set `org-hide' face correctly.
  4304. (let ((foreground (org-find-invisible-foreground)))
  4305. (when foreground
  4306. (set-face-foreground 'org-hide foreground))))
  4307. ;; Update `customize-package-emacs-version-alist'
  4308. (add-to-list 'customize-package-emacs-version-alist
  4309. '(Org ("8.0" . "24.4")
  4310. ("8.1" . "24.4")
  4311. ("8.2" . "24.4")
  4312. ("8.2.7" . "24.4")
  4313. ("8.3" . "26.1")
  4314. ("9.0" . "26.1")
  4315. ("9.1" . "26.1")
  4316. ("9.2" . "27.1")))
  4317. (defvar org-mode-transpose-word-syntax-table
  4318. (let ((st (make-syntax-table text-mode-syntax-table)))
  4319. (dolist (c org-emphasis-alist st)
  4320. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4321. (when (fboundp 'abbrev-table-put)
  4322. (abbrev-table-put org-mode-abbrev-table
  4323. :parents (list text-mode-abbrev-table)))
  4324. (defun org-find-invisible-foreground ()
  4325. (let ((candidates (remove
  4326. "unspecified-bg"
  4327. (nconc
  4328. (list (face-background 'default)
  4329. (face-background 'org-default))
  4330. (mapcar
  4331. (lambda (alist)
  4332. (when (boundp alist)
  4333. (cdr (assq 'background-color (symbol-value alist)))))
  4334. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4335. (list (face-foreground 'org-hide))))))
  4336. (car (remove nil candidates))))
  4337. (defun org-current-time (&optional rounding-minutes past)
  4338. "Current time, possibly rounded to ROUNDING-MINUTES.
  4339. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4340. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4341. the rounding returns a past time."
  4342. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4343. (car org-time-stamp-rounding-minutes)))
  4344. (time (decode-time)) res)
  4345. (if (< r 1)
  4346. (current-time)
  4347. (setq res
  4348. (apply 'encode-time
  4349. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4350. (nthcdr 2 time))))
  4351. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4352. (seconds-to-time (- (float-time res) (* r 60)))
  4353. res))))
  4354. (defun org-today ()
  4355. "Return today date, considering `org-extend-today-until'."
  4356. (time-to-days
  4357. (time-subtract (current-time)
  4358. (list 0 (* 3600 org-extend-today-until) 0))))
  4359. ;;;; Font-Lock stuff, including the activators
  4360. (require 'font-lock)
  4361. (defconst org-match-sexp-depth 3
  4362. "Number of stacked braces for sub/superscript matching.")
  4363. (defun org-create-multibrace-regexp (left right n)
  4364. "Create a regular expression which will match a balanced sexp.
  4365. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4366. as single character strings.
  4367. The regexp returned will match the entire expression including the
  4368. delimiters. It will also define a single group which contains the
  4369. match except for the outermost delimiters. The maximum depth of
  4370. stacked delimiters is N. Escaping delimiters is not possible."
  4371. (let* ((nothing (concat "[^" left right "]*?"))
  4372. (or "\\|")
  4373. (re nothing)
  4374. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4375. (while (> n 1)
  4376. (setq n (1- n)
  4377. re (concat re or next)
  4378. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4379. (concat left "\\(" re "\\)" right)))
  4380. (defconst org-match-substring-regexp
  4381. (concat
  4382. "\\(\\S-\\)\\([_^]\\)\\("
  4383. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4384. "\\|"
  4385. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4386. "\\|"
  4387. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4388. "The regular expression matching a sub- or superscript.")
  4389. (defconst org-match-substring-with-braces-regexp
  4390. (concat
  4391. "\\(\\S-\\)\\([_^]\\)"
  4392. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4393. "The regular expression matching a sub- or superscript, forcing braces.")
  4394. (defvar org-emph-face nil)
  4395. (defun org-do-emphasis-faces (limit)
  4396. "Run through the buffer and emphasize strings."
  4397. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4398. (car org-emphasis-regexp-components))))
  4399. (catch :exit
  4400. (while (re-search-forward quick-re limit t)
  4401. (let* ((marker (match-string 2))
  4402. (verbatim? (member marker '("~" "="))))
  4403. (when (save-excursion
  4404. (goto-char (match-beginning 0))
  4405. (and
  4406. ;; Do not match table hlines.
  4407. (not (and (equal marker "+")
  4408. (org-match-line
  4409. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4410. ;; Do not match headline stars. Do not consider
  4411. ;; stars of a headline as closing marker for bold
  4412. ;; markup either.
  4413. (not (and (equal marker "*")
  4414. (save-excursion
  4415. (forward-char)
  4416. (skip-chars-backward "*")
  4417. (looking-at-p org-outline-regexp-bol))))
  4418. ;; Match full emphasis markup regexp.
  4419. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4420. ;; Do not span over paragraph boundaries.
  4421. (not (string-match-p org-element-paragraph-separate
  4422. (match-string 2)))
  4423. ;; Do not span over cells in table rows.
  4424. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4425. (string-match-p "|" (match-string 4))))))
  4426. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4427. (font-lock-prepend-text-property
  4428. (match-beginning 2) (match-end 2) 'face face)
  4429. (when verbatim?
  4430. (org-remove-flyspell-overlays-in
  4431. (match-beginning 0) (match-end 0))
  4432. (remove-text-properties (match-beginning 2) (match-end 2)
  4433. '(display t invisible t intangible t)))
  4434. (add-text-properties (match-beginning 2) (match-end 2)
  4435. '(font-lock-multiline t org-emphasis t))
  4436. (when org-hide-emphasis-markers
  4437. (add-text-properties (match-end 4) (match-beginning 5)
  4438. '(invisible org-link))
  4439. (add-text-properties (match-beginning 3) (match-end 3)
  4440. '(invisible org-link)))
  4441. (throw :exit t))))))))
  4442. (defun org-emphasize (&optional char)
  4443. "Insert or change an emphasis, i.e. a font like bold or italic.
  4444. If there is an active region, change that region to a new emphasis.
  4445. If there is no region, just insert the marker characters and position
  4446. the cursor between them.
  4447. CHAR should be the marker character. If it is a space, it means to
  4448. remove the emphasis of the selected region.
  4449. If CHAR is not given (for example in an interactive call) it will be
  4450. prompted for."
  4451. (interactive)
  4452. (let ((erc org-emphasis-regexp-components)
  4453. (string "") beg end move s)
  4454. (if (org-region-active-p)
  4455. (setq beg (region-beginning)
  4456. end (region-end)
  4457. string (buffer-substring beg end))
  4458. (setq move t))
  4459. (unless char
  4460. (message "Emphasis marker or tag: [%s]"
  4461. (mapconcat #'car org-emphasis-alist ""))
  4462. (setq char (read-char-exclusive)))
  4463. (if (equal char ?\s)
  4464. (setq s ""
  4465. move nil)
  4466. (unless (assoc (char-to-string char) org-emphasis-alist)
  4467. (user-error "No such emphasis marker: \"%c\"" char))
  4468. (setq s (char-to-string char)))
  4469. (while (and (> (length string) 1)
  4470. (equal (substring string 0 1) (substring string -1))
  4471. (assoc (substring string 0 1) org-emphasis-alist))
  4472. (setq string (substring string 1 -1)))
  4473. (setq string (concat s string s))
  4474. (when beg (delete-region beg end))
  4475. (unless (or (bolp)
  4476. (string-match (concat "[" (nth 0 erc) "\n]")
  4477. (char-to-string (char-before (point)))))
  4478. (insert " "))
  4479. (unless (or (eobp)
  4480. (string-match (concat "[" (nth 1 erc) "\n]")
  4481. (char-to-string (char-after (point)))))
  4482. (insert " ") (backward-char 1))
  4483. (insert string)
  4484. (and move (backward-char 1))))
  4485. (defconst org-nonsticky-props
  4486. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4487. (defsubst org-rear-nonsticky-at (pos)
  4488. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4489. (defun org-activate-links (limit)
  4490. "Add link properties to links.
  4491. This includes angle, plain, and bracket links."
  4492. (catch :exit
  4493. (while (re-search-forward org-link-any-re limit t)
  4494. (let* ((start (match-beginning 0))
  4495. (end (match-end 0))
  4496. (style (cond ((eq ?< (char-after start)) 'angle)
  4497. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4498. (t 'plain))))
  4499. (when (and (memq style org-highlight-links)
  4500. ;; Do not span over paragraph boundaries.
  4501. (not (string-match-p org-element-paragraph-separate
  4502. (match-string 0)))
  4503. ;; Do not confuse plain links with tags.
  4504. (not (and (eq style 'plain)
  4505. (let ((face (get-text-property
  4506. (max (1- start) (point-min)) 'face)))
  4507. (if (consp face) (memq 'org-tag face)
  4508. (eq 'org-tag face))))))
  4509. (let* ((link-object (save-excursion
  4510. (goto-char start)
  4511. (save-match-data (org-element-link-parser))))
  4512. (link (org-element-property :raw-link link-object))
  4513. (type (org-element-property :type link-object))
  4514. (path (org-element-property :path link-object))
  4515. (properties ;for link's visible part
  4516. (list
  4517. 'face (pcase (org-link-get-parameter type :face)
  4518. ((and (pred functionp) face) (funcall face path))
  4519. ((and (pred facep) face) face)
  4520. ((and (pred consp) face) face) ;anonymous
  4521. (_ 'org-link))
  4522. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4523. 'highlight)
  4524. 'keymap (or (org-link-get-parameter type :keymap)
  4525. org-mouse-map)
  4526. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4527. ((and (pred stringp) echo) echo)
  4528. ((and (pred functionp) echo) echo)
  4529. (_ (concat "LINK: " link)))
  4530. 'htmlize-link (pcase (org-link-get-parameter type
  4531. :htmlize-link)
  4532. ((and (pred functionp) f) (funcall f))
  4533. (_ `(:uri ,link)))
  4534. 'font-lock-multiline t)))
  4535. (org-remove-flyspell-overlays-in start end)
  4536. (org-rear-nonsticky-at end)
  4537. (if (not (eq 'bracket style))
  4538. (add-text-properties start end properties)
  4539. ;; Handle invisible parts in bracket links.
  4540. (remove-text-properties start end '(invisible nil))
  4541. (let ((hidden
  4542. (append `(invisible
  4543. ,(or (org-link-get-parameter type :display)
  4544. 'org-link))
  4545. properties))
  4546. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4547. (visible-end (or (match-end 3) (match-end 2))))
  4548. (add-text-properties start visible-start hidden)
  4549. (add-text-properties visible-start visible-end properties)
  4550. (add-text-properties visible-end end hidden)
  4551. (org-rear-nonsticky-at visible-start)
  4552. (org-rear-nonsticky-at visible-end)))
  4553. (let ((f (org-link-get-parameter type :activate-func)))
  4554. (when (functionp f)
  4555. (funcall f start end path (eq style 'bracket))))
  4556. (throw :exit t))))) ;signal success
  4557. nil))
  4558. (defun org-activate-code (limit)
  4559. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4560. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4561. (remove-text-properties (match-beginning 0) (match-end 0)
  4562. '(display t invisible t intangible t))
  4563. t))
  4564. (defcustom org-src-fontify-natively t
  4565. "When non-nil, fontify code in code blocks.
  4566. See also the `org-block' face."
  4567. :type 'boolean
  4568. :version "26.1"
  4569. :package-version '(Org . "8.3")
  4570. :group 'org-appearance
  4571. :group 'org-babel)
  4572. (defcustom org-allow-promoting-top-level-subtree nil
  4573. "When non-nil, allow promoting a top level subtree.
  4574. The leading star of the top level headline will be replaced
  4575. by a #."
  4576. :type 'boolean
  4577. :version "24.1"
  4578. :group 'org-appearance)
  4579. (defun org-fontify-meta-lines-and-blocks (limit)
  4580. (condition-case nil
  4581. (org-fontify-meta-lines-and-blocks-1 limit)
  4582. (error (message "Org mode fontification error in %S at %d"
  4583. (current-buffer)
  4584. (line-number-at-pos)))))
  4585. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4586. "Fontify #+ lines and blocks."
  4587. (let ((case-fold-search t))
  4588. (when (re-search-forward
  4589. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  4590. limit t)
  4591. (let ((beg (match-beginning 0))
  4592. (end-of-beginline (match-end 0))
  4593. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4594. (block-end nil) ; will include \n after end of block content
  4595. (lang (match-string 7)) ; the language, if it is an src block
  4596. (bol-after-beginline (line-beginning-position 2))
  4597. (dc1 (downcase (match-string 2)))
  4598. (dc3 (downcase (match-string 3)))
  4599. (whole-blockline org-fontify-whole-block-delimiter-line)
  4600. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4601. (cond
  4602. ((and (match-end 4) (equal dc3 "+begin"))
  4603. ;; Truly a block
  4604. (setq block-type (downcase (match-string 5))
  4605. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4606. (when (re-search-forward
  4607. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  4608. nil t) ;; on purpose, we look further than LIMIT
  4609. ;; We do have a matching #+end line
  4610. (setq beg-of-endline (match-beginning 0)
  4611. end-of-endline (match-end 0)
  4612. nl-before-endline (1- (match-beginning 0)))
  4613. (setq block-end (match-beginning 0)) ; includes the final newline.
  4614. (when quoting
  4615. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4616. (remove-text-properties beg end-of-endline
  4617. '(display t invisible t intangible t)))
  4618. (add-text-properties
  4619. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4620. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4621. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4622. (cond
  4623. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4624. (org-src-font-lock-fontify-block lang block-start block-end)
  4625. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4626. (quoting
  4627. (add-text-properties
  4628. bol-after-beginline beg-of-endline
  4629. (list 'face
  4630. (list :inherit
  4631. (let ((face-name
  4632. (intern (format "org-block-%s" lang))))
  4633. (append (and (facep face-name) (list face-name))
  4634. '(org-block)))))))
  4635. ((not org-fontify-quote-and-verse-blocks))
  4636. ((string= block-type "quote")
  4637. (add-face-text-property
  4638. bol-after-beginline beg-of-endline 'org-quote t))
  4639. ((string= block-type "verse")
  4640. (add-face-text-property
  4641. bol-after-beginline beg-of-endline 'org-verse t)))
  4642. ;; Fontify the #+begin and #+end lines of the blocks
  4643. (add-text-properties
  4644. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4645. '(face org-block-begin-line))
  4646. (add-text-properties
  4647. beg-of-endline
  4648. (min (point-max) (if whole-blockline (min (point-max) (1+ end-of-endline)) end-of-endline))
  4649. '(face org-block-end-line))
  4650. t))
  4651. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4652. (org-remove-flyspell-overlays-in
  4653. (match-beginning 0)
  4654. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4655. (add-text-properties
  4656. beg (match-end 3)
  4657. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4658. '(font-lock-fontified t invisible t)
  4659. '(font-lock-fontified t face org-document-info-keyword)))
  4660. (add-text-properties
  4661. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4662. (if (string-equal dc1 "+title:")
  4663. '(font-lock-fontified t face org-document-title)
  4664. '(font-lock-fontified t face org-document-info))))
  4665. ((string-prefix-p "+caption" dc1)
  4666. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4667. (remove-text-properties (match-beginning 0) (match-end 0)
  4668. '(display t invisible t intangible t))
  4669. ;; Handle short captions.
  4670. (save-excursion
  4671. (beginning-of-line)
  4672. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  4673. (add-text-properties (line-beginning-position) (match-end 1)
  4674. '(font-lock-fontified t face org-meta-line))
  4675. (add-text-properties (match-end 0) (line-end-position)
  4676. '(font-lock-fontified t face org-block))
  4677. t)
  4678. ((member dc3 '(" " ""))
  4679. ; Just a comment, the plus was not there
  4680. (org-remove-flyspell-overlays-in beg (match-end 0))
  4681. (add-text-properties
  4682. beg (match-end 0)
  4683. '(font-lock-fontified t face font-lock-comment-face)))
  4684. (t ;; just any other in-buffer setting, but not indented
  4685. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4686. (remove-text-properties (match-beginning 0) (match-end 0)
  4687. '(display t invisible t intangible t))
  4688. (add-text-properties beg (match-end 0)
  4689. '(font-lock-fontified t face org-meta-line))
  4690. t))))))
  4691. (defun org-fontify-drawers (limit)
  4692. "Fontify drawers."
  4693. (when (re-search-forward org-drawer-regexp limit t)
  4694. (add-text-properties
  4695. (match-beginning 0) (match-end 0)
  4696. '(font-lock-fontified t face org-special-keyword))
  4697. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4698. t))
  4699. (defun org-fontify-macros (limit)
  4700. "Fontify macros."
  4701. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4702. (let ((begin (match-beginning 0))
  4703. (opening-end (match-beginning 1)))
  4704. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4705. (match-string 1))
  4706. (let ((end (match-end 1))
  4707. (closing-start (match-beginning 1)))
  4708. (add-text-properties
  4709. begin end
  4710. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4711. (org-remove-flyspell-overlays-in begin end)
  4712. (when org-hide-macro-markers
  4713. (add-text-properties begin opening-end '(invisible t))
  4714. (add-text-properties closing-start end '(invisible t)))
  4715. t)))))
  4716. (defun org-fontify-extend-region (beg end _old-len)
  4717. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4718. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4719. (extend (lambda (r1 r2 dir)
  4720. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4721. (replace-regexp-in-string "[][]" r2
  4722. (match-string-no-properties 0)))))
  4723. (re-search-forward (regexp-quote re) nil t dir)))))
  4724. (save-match-data
  4725. (save-excursion
  4726. (goto-char beg)
  4727. (back-to-indentation)
  4728. (cond ((looking-at end-re)
  4729. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4730. ((looking-at begin-re)
  4731. (cons beg (or (funcall extend "end" "]" 1) end)))
  4732. (t (cons beg end)))))))
  4733. (defun org-activate-footnote-links (limit)
  4734. "Add text properties for footnotes."
  4735. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4736. (when fn
  4737. (let* ((beg (nth 1 fn))
  4738. (end (nth 2 fn))
  4739. (label (car fn))
  4740. (referencep (/= (line-beginning-position) beg)))
  4741. (when (and referencep (nth 3 fn))
  4742. (save-excursion
  4743. (goto-char beg)
  4744. (search-forward (or label "fn:"))
  4745. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4746. (add-text-properties beg end
  4747. (list 'mouse-face 'highlight
  4748. 'keymap org-mouse-map
  4749. 'help-echo
  4750. (if referencep "Footnote reference"
  4751. "Footnote definition")
  4752. 'font-lock-fontified t
  4753. 'font-lock-multiline t
  4754. 'face 'org-footnote))))))
  4755. (defun org-activate-dates (limit)
  4756. "Add text properties for dates."
  4757. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4758. (not (equal (char-before (match-beginning 0)) 91)))
  4759. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4760. (add-text-properties (match-beginning 0) (match-end 0)
  4761. (list 'mouse-face 'highlight
  4762. 'keymap org-mouse-map))
  4763. (org-rear-nonsticky-at (match-end 0))
  4764. (when org-display-custom-times
  4765. ;; If it's a date range, activate custom time for second date.
  4766. (when (match-end 3)
  4767. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4768. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4769. t))
  4770. (defun org-activate-target-links (limit)
  4771. "Add text properties for target matches."
  4772. (when org-target-link-regexp
  4773. (let ((case-fold-search t))
  4774. ;; `org-target-link-regexp' matches one character before the
  4775. ;; actual target.
  4776. (unless (bolp) (forward-char -1))
  4777. (when (re-search-forward org-target-link-regexp limit t)
  4778. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4779. (add-text-properties (match-beginning 1) (match-end 1)
  4780. (list 'mouse-face 'highlight
  4781. 'keymap org-mouse-map
  4782. 'help-echo "Radio target link"
  4783. 'org-linked-text t))
  4784. (org-rear-nonsticky-at (match-end 1))
  4785. t))))
  4786. (defvar org-latex-and-related-regexp nil
  4787. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4788. (defun org-compute-latex-and-related-regexp ()
  4789. "Compute regular expression for LaTeX, entities and sub/superscript.
  4790. Result depends on variable `org-highlight-latex-and-related'."
  4791. (let ((re-sub
  4792. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4793. ((eq org-use-sub-superscripts '{})
  4794. (list org-match-substring-with-braces-regexp))
  4795. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4796. (re-latex
  4797. (when (or (memq 'latex org-highlight-latex-and-related)
  4798. (memq 'native org-highlight-latex-and-related))
  4799. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4800. (delq nil
  4801. (mapcar (lambda (x)
  4802. (and (member (car x) matchers) (nth 1 x)))
  4803. org-latex-regexps)))))
  4804. (re-entities
  4805. (when (memq 'entities org-highlight-latex-and-related)
  4806. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4807. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4808. (setq-local org-latex-and-related-regexp
  4809. (mapconcat #'identity
  4810. (append re-latex re-entities re-sub)
  4811. "\\|"))))
  4812. (defun org-do-latex-and-related (_limit)
  4813. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4814. Stop at first highlighted object, if any. Return t if some
  4815. highlighting was done, nil otherwise."
  4816. (when (org-string-nw-p org-latex-and-related-regexp)
  4817. (catch 'found
  4818. (while (re-search-forward org-latex-and-related-regexp
  4819. nil t) ;; on purpose, we ignore LIMIT
  4820. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4821. org-special-keyword)))
  4822. (save-excursion
  4823. (goto-char (1+ (match-beginning 0)))
  4824. (face-at-point nil t)))
  4825. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4826. '(?_ ?^))
  4827. 1
  4828. 0))
  4829. (start (+ offset (match-beginning 0)))
  4830. (end (match-end 0)))
  4831. (if (memq 'native org-highlight-latex-and-related)
  4832. (org-src-font-lock-fontify-block "latex" start end)
  4833. (font-lock-prepend-text-property start end
  4834. 'face 'org-latex-and-related))
  4835. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4836. '(font-lock-multiline t)))
  4837. (throw 'found t)))
  4838. nil)))
  4839. (defun org-restart-font-lock ()
  4840. "Restart `font-lock-mode', to force refontification."
  4841. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4842. (font-lock-mode -1)
  4843. (font-lock-mode 1)))
  4844. (defun org-activate-tags (limit)
  4845. (when (re-search-forward org-tag-line-re limit t)
  4846. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4847. (add-text-properties (match-beginning 1) (match-end 1)
  4848. (list 'mouse-face 'highlight
  4849. 'keymap org-mouse-map))
  4850. (org-rear-nonsticky-at (match-end 1))
  4851. t))
  4852. (defun org-outline-level ()
  4853. "Compute the outline level of the heading at point.
  4854. If this is called at a normal headline, the level is the number
  4855. of stars. Use `org-reduced-level' to remove the effect of
  4856. `org-odd-levels'. Unlike to `org-current-level', this function
  4857. takes into consideration inlinetasks."
  4858. (org-with-wide-buffer
  4859. (end-of-line)
  4860. (if (re-search-backward org-outline-regexp-bol nil t)
  4861. (1- (- (match-end 0) (match-beginning 0)))
  4862. 0)))
  4863. (defvar org-font-lock-keywords nil)
  4864. (defsubst org-re-property (property &optional literal allow-null value)
  4865. "Return a regexp matching a PROPERTY line.
  4866. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4867. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4868. non-nil, match properties even without a value.
  4869. Match group 3 is set to the value when it exists. If there is no
  4870. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4871. With optional argument VALUE, match only property lines with
  4872. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4873. unless LITERAL is non-nil."
  4874. (concat
  4875. "^\\(?4:[ \t]*\\)"
  4876. (format "\\(?1::\\(?2:%s\\):\\)"
  4877. (if literal property (regexp-quote property)))
  4878. (cond (value
  4879. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4880. (if literal value (regexp-quote value))))
  4881. (allow-null
  4882. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4883. (t
  4884. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4885. (defconst org-property-re
  4886. (org-re-property "\\S-+" 'literal t)
  4887. "Regular expression matching a property line.
  4888. There are four matching groups:
  4889. 1: :PROPKEY: including the leading and trailing colon,
  4890. 2: PROPKEY without the leading and trailing colon,
  4891. 3: PROPVAL without leading or trailing spaces,
  4892. 4: the indentation of the current line,
  4893. 5: trailing whitespace.")
  4894. (defvar org-font-lock-hook nil
  4895. "Functions to be called for special font lock stuff.")
  4896. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4897. (defvar org-font-lock-set-keywords-hook nil
  4898. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4899. This is called after `org-font-lock-extra-keywords' is defined, but before
  4900. it is installed to be used by font lock. This can be useful if something
  4901. needs to be inserted at a specific position in the font-lock sequence.")
  4902. (defun org-font-lock-hook (limit)
  4903. "Run `org-font-lock-hook' within LIMIT."
  4904. (run-hook-with-args 'org-font-lock-hook limit))
  4905. (defun org-set-font-lock-defaults ()
  4906. "Set font lock defaults for the current buffer."
  4907. (let* ((em org-fontify-emphasized-text)
  4908. (lk org-highlight-links)
  4909. (org-font-lock-extra-keywords
  4910. (list
  4911. ;; Call the hook
  4912. '(org-font-lock-hook)
  4913. ;; Headlines
  4914. `(,(if org-fontify-whole-heading-line
  4915. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4916. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4917. (1 (org-get-level-face 1))
  4918. (2 (org-get-level-face 2))
  4919. (3 (org-get-level-face 3)))
  4920. ;; Table lines
  4921. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4922. (1 'org-table t))
  4923. ;; Table internals
  4924. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4925. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4926. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4927. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4928. ;; Drawers
  4929. '(org-fontify-drawers)
  4930. ;; Properties
  4931. (list org-property-re
  4932. '(1 'org-special-keyword t)
  4933. '(3 'org-property-value t))
  4934. ;; Link related fontification.
  4935. '(org-activate-links)
  4936. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4937. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4938. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4939. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4940. ;; Targets.
  4941. (list org-radio-target-regexp '(0 'org-target t))
  4942. (list org-target-regexp '(0 'org-target t))
  4943. ;; Diary sexps.
  4944. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4945. ;; Macro
  4946. '(org-fontify-macros)
  4947. ;; TODO keyword
  4948. (list (format org-heading-keyword-regexp-format
  4949. org-todo-regexp)
  4950. '(2 (org-get-todo-face 2) t))
  4951. ;; DONE
  4952. (if org-fontify-done-headline
  4953. (list (format org-heading-keyword-regexp-format
  4954. (concat
  4955. "\\(?:"
  4956. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4957. "\\)"))
  4958. '(2 'org-headline-done t))
  4959. nil)
  4960. ;; Priorities
  4961. '(org-font-lock-add-priority-faces)
  4962. ;; Tags
  4963. '(org-font-lock-add-tag-faces)
  4964. ;; Tags groups
  4965. (when (and org-group-tags org-tag-groups-alist)
  4966. (list (concat org-outline-regexp-bol ".+\\(:"
  4967. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4968. ":\\).*$")
  4969. '(1 'org-tag-group prepend)))
  4970. ;; Special keywords
  4971. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4972. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4973. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4974. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4975. ;; Emphasis
  4976. (when em '(org-do-emphasis-faces))
  4977. ;; Checkboxes
  4978. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4979. 1 'org-checkbox prepend)
  4980. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4981. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4982. (0 (org-get-checkbox-statistics-face) t)))
  4983. ;; Description list items
  4984. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4985. 1 'org-list-dt prepend)
  4986. ;; ARCHIVEd headings
  4987. (list (concat
  4988. org-outline-regexp-bol
  4989. "\\(.*:" org-archive-tag ":.*\\)")
  4990. '(1 'org-archived prepend))
  4991. ;; Specials
  4992. '(org-do-latex-and-related)
  4993. '(org-fontify-entities)
  4994. '(org-raise-scripts)
  4995. ;; Code
  4996. '(org-activate-code (1 'org-code t))
  4997. ;; COMMENT
  4998. (list (format
  4999. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5000. org-todo-regexp
  5001. org-comment-string)
  5002. '(9 'org-special-keyword t))
  5003. ;; Blocks and meta lines
  5004. '(org-fontify-meta-lines-and-blocks))))
  5005. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5006. (run-hooks 'org-font-lock-set-keywords-hook)
  5007. ;; Now set the full font-lock-keywords
  5008. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5009. (setq-local font-lock-defaults
  5010. '(org-font-lock-keywords t nil nil backward-paragraph))
  5011. (setq-local font-lock-extend-after-change-region-function
  5012. #'org-fontify-extend-region)
  5013. (kill-local-variable 'font-lock-keywords)
  5014. nil))
  5015. (defun org-toggle-pretty-entities ()
  5016. "Toggle the composition display of entities as UTF8 characters."
  5017. (interactive)
  5018. (setq-local org-pretty-entities (not org-pretty-entities))
  5019. (org-restart-font-lock)
  5020. (if org-pretty-entities
  5021. (message "Entities are now displayed as UTF8 characters")
  5022. (save-restriction
  5023. (widen)
  5024. (decompose-region (point-min) (point-max))
  5025. (message "Entities are now displayed as plain text"))))
  5026. (defvar-local org-custom-properties-overlays nil
  5027. "List of overlays used for custom properties.")
  5028. (defun org-toggle-custom-properties-visibility ()
  5029. "Display or hide properties in `org-custom-properties'."
  5030. (interactive)
  5031. (if org-custom-properties-overlays
  5032. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5033. (setq org-custom-properties-overlays nil))
  5034. (when org-custom-properties
  5035. (org-with-wide-buffer
  5036. (goto-char (point-min))
  5037. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5038. (while (re-search-forward regexp nil t)
  5039. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5040. (when (and end (< (point) end))
  5041. ;; Hide first custom property in current drawer.
  5042. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5043. (overlay-put o 'invisible t)
  5044. (overlay-put o 'org-custom-property t)
  5045. (push o org-custom-properties-overlays))
  5046. ;; Hide additional custom properties in the same drawer.
  5047. (while (re-search-forward regexp end t)
  5048. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5049. (overlay-put o 'invisible t)
  5050. (overlay-put o 'org-custom-property t)
  5051. (push o org-custom-properties-overlays)))))
  5052. ;; Each entry is limited to a single property drawer.
  5053. (outline-next-heading)))))))
  5054. (defun org-fontify-entities (limit)
  5055. "Find an entity to fontify."
  5056. (let (ee)
  5057. (when org-pretty-entities
  5058. (catch 'match
  5059. ;; "\_ "-family is left out on purpose. Only the first one,
  5060. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5061. ;; confusing when adding a second white space character.
  5062. (while (re-search-forward
  5063. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5064. limit t)
  5065. (when (and (not (org-at-comment-p))
  5066. (setq ee (org-entity-get (match-string 1)))
  5067. (= (length (nth 6 ee)) 1))
  5068. (let* ((end (if (equal (match-string 2) "{}")
  5069. (match-end 2)
  5070. (match-end 1))))
  5071. (add-text-properties
  5072. (match-beginning 0) end
  5073. (list 'font-lock-fontified t))
  5074. (compose-region (match-beginning 0) end
  5075. (nth 6 ee) nil)
  5076. (backward-char 1)
  5077. (throw 'match t))))
  5078. nil))))
  5079. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5080. "Fontify string S like in Org mode."
  5081. (with-temp-buffer
  5082. (insert s)
  5083. (let ((org-odd-levels-only odd-levels))
  5084. (org-mode)
  5085. (org-font-lock-ensure)
  5086. (buffer-string))))
  5087. (defvar org-m nil)
  5088. (defvar org-l nil)
  5089. (defvar org-f nil)
  5090. (defun org-get-level-face (n)
  5091. "Get the right face for match N in font-lock matching of headlines."
  5092. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5093. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5094. (if org-cycle-level-faces
  5095. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5096. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5097. (cond
  5098. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5099. ((eq n 2) org-f)
  5100. (t (unless org-level-color-stars-only org-f))))
  5101. (defun org-face-from-face-or-color (context inherit face-or-color)
  5102. "Create a face list that inherits INHERIT, but sets the foreground color.
  5103. When FACE-OR-COLOR is not a string, just return it."
  5104. (if (stringp face-or-color)
  5105. (list :inherit inherit
  5106. (cdr (assoc context org-faces-easy-properties))
  5107. face-or-color)
  5108. face-or-color))
  5109. (defun org-get-todo-face (kwd)
  5110. "Get the right face for a TODO keyword KWD.
  5111. If KWD is a number, get the corresponding match group."
  5112. (when (numberp kwd) (setq kwd (match-string kwd)))
  5113. (or (org-face-from-face-or-color
  5114. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5115. (and (member kwd org-done-keywords) 'org-done)
  5116. 'org-todo))
  5117. (defun org-get-priority-face (priority)
  5118. "Get the right face for PRIORITY.
  5119. PRIORITY is a character."
  5120. (or (org-face-from-face-or-color
  5121. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5122. 'org-priority))
  5123. (defun org-get-tag-face (tag)
  5124. "Get the right face for TAG.
  5125. If TAG is a number, get the corresponding match group."
  5126. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5127. (or (org-face-from-face-or-color
  5128. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5129. 'org-tag)))
  5130. (defun org-font-lock-add-priority-faces (limit)
  5131. "Add the special priority faces."
  5132. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5133. (add-text-properties
  5134. (match-beginning 1) (match-end 1)
  5135. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5136. 'font-lock-fontified t))))
  5137. (defun org-font-lock-add-tag-faces (limit)
  5138. "Add the special tag faces."
  5139. (when (and org-tag-faces org-tags-special-faces-re)
  5140. (while (re-search-forward org-tags-special-faces-re limit t)
  5141. (add-text-properties (match-beginning 1) (match-end 1)
  5142. (list 'face (org-get-tag-face 1)
  5143. 'font-lock-fontified t))
  5144. (backward-char 1))))
  5145. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5146. "Remove fontification and activation overlays from links."
  5147. (font-lock-default-unfontify-region beg end)
  5148. (let* ((buffer-undo-list t)
  5149. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5150. (inhibit-modification-hooks t)
  5151. deactivate-mark buffer-file-name buffer-file-truename)
  5152. (decompose-region beg end)
  5153. (remove-text-properties beg end
  5154. '(mouse-face t keymap t org-linked-text t
  5155. invisible t intangible t
  5156. org-emphasis t))
  5157. (org-remove-font-lock-display-properties beg end)))
  5158. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5159. ((raise 0.3) (height 0.7))
  5160. ((raise -0.5))
  5161. ((raise 0.5)))
  5162. "Display properties for showing superscripts and subscripts.")
  5163. (defun org-remove-font-lock-display-properties (beg end)
  5164. "Remove specific display properties that have been added by font lock.
  5165. The will remove the raise properties that are used to show superscripts
  5166. and subscripts."
  5167. (let (next prop)
  5168. (while (< beg end)
  5169. (setq next (next-single-property-change beg 'display nil end)
  5170. prop (get-text-property beg 'display))
  5171. (when (member prop org-script-display)
  5172. (put-text-property beg next 'display nil))
  5173. (setq beg next))))
  5174. (defun org-raise-scripts (limit)
  5175. "Add raise properties to sub/superscripts."
  5176. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5177. (re-search-forward
  5178. (if (eq org-use-sub-superscripts t)
  5179. org-match-substring-regexp
  5180. org-match-substring-with-braces-regexp)
  5181. limit t))
  5182. (let* ((pos (point)) table-p comment-p
  5183. (mpos (match-beginning 3))
  5184. (emph-p (get-text-property mpos 'org-emphasis))
  5185. (link-p (get-text-property mpos 'mouse-face))
  5186. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5187. (goto-char (point-at-bol))
  5188. (setq table-p (looking-at-p org-table-dataline-regexp)
  5189. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5190. (goto-char pos)
  5191. ;; Handle a_b^c
  5192. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5193. (unless (or comment-p emph-p link-p keyw-p)
  5194. (put-text-property (match-beginning 3) (match-end 0)
  5195. 'display
  5196. (if (equal (char-after (match-beginning 2)) ?^)
  5197. (nth (if table-p 3 1) org-script-display)
  5198. (nth (if table-p 2 0) org-script-display)))
  5199. (add-text-properties (match-beginning 2) (match-end 2)
  5200. (list 'invisible t))
  5201. (when (and (eq (char-after (match-beginning 3)) ?{)
  5202. (eq (char-before (match-end 3)) ?}))
  5203. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5204. (list 'invisible t))
  5205. (add-text-properties (1- (match-end 3)) (match-end 3)
  5206. (list 'invisible t))))
  5207. t)))
  5208. (defun org-remove-empty-overlays-at (pos)
  5209. "Remove outline overlays that do not contain non-white stuff."
  5210. (dolist (o (overlays-at pos))
  5211. (and (eq 'outline (overlay-get o 'invisible))
  5212. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5213. (overlay-end o))))
  5214. (delete-overlay o))))
  5215. (defun org-show-empty-lines-in-parent ()
  5216. "Move to the parent and re-show empty lines before visible headlines."
  5217. (save-excursion
  5218. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5219. (org-cycle-show-empty-lines context))))
  5220. (defun org-files-list ()
  5221. "Return `org-agenda-files' list, plus all open Org files.
  5222. This is useful for operations that need to scan all of a user's
  5223. open and agenda-wise Org files."
  5224. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5225. (dolist (buf (buffer-list))
  5226. (with-current-buffer buf
  5227. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5228. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5229. :test #'equal))))
  5230. files))
  5231. (defsubst org-entry-beginning-position ()
  5232. "Return the beginning position of the current entry."
  5233. (save-excursion (org-back-to-heading t) (point)))
  5234. (defsubst org-entry-end-position ()
  5235. "Return the end position of the current entry."
  5236. (save-excursion (outline-next-heading) (point)))
  5237. (defun org-subtree-end-visible-p ()
  5238. "Is the end of the current subtree visible?"
  5239. (pos-visible-in-window-p
  5240. (save-excursion (org-end-of-subtree t) (point))))
  5241. (defun org-first-headline-recenter ()
  5242. "Move cursor to the first headline and recenter the headline."
  5243. (let ((window (get-buffer-window)))
  5244. (when window
  5245. (goto-char (point-min))
  5246. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5247. (set-window-start window (line-beginning-position))))))
  5248. ;;; Visibility (headlines, blocks, drawers)
  5249. ;;;; Headlines visibility
  5250. (defun org-show-entry ()
  5251. "Show the body directly following this heading.
  5252. Show the heading too, if it is currently invisible."
  5253. (interactive)
  5254. (save-excursion
  5255. (ignore-errors
  5256. (org-back-to-heading t)
  5257. (org-flag-region
  5258. (line-end-position 0)
  5259. (save-excursion
  5260. (if (re-search-forward
  5261. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5262. (match-beginning 1)
  5263. (point-max)))
  5264. nil
  5265. 'outline))))
  5266. (defun org-show-children (&optional level)
  5267. "Show all direct subheadings of this heading.
  5268. Prefix arg LEVEL is how many levels below the current level
  5269. should be shown. Default is enough to cause the following
  5270. heading to appear."
  5271. (interactive "p")
  5272. (save-excursion
  5273. (org-back-to-heading t)
  5274. (let* ((current-level (funcall outline-level))
  5275. (max-level (org-get-valid-level
  5276. current-level
  5277. (if level (prefix-numeric-value level) 1)))
  5278. (end (save-excursion (org-end-of-subtree t t)))
  5279. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5280. (past-first-child nil)
  5281. ;; Make sure to skip inlinetasks.
  5282. (re (format regexp-fmt
  5283. current-level
  5284. (cond
  5285. ((not (featurep 'org-inlinetask)) "")
  5286. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5287. 3))
  5288. (t (1- org-inlinetask-min-level))))))
  5289. ;; Display parent heading.
  5290. (org-flag-heading nil)
  5291. (forward-line)
  5292. ;; Display children. First child may be deeper than expected
  5293. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5294. ;; MAX-LEVEL accordingly.
  5295. (while (re-search-forward re end t)
  5296. (unless past-first-child
  5297. (setq re (format regexp-fmt
  5298. current-level
  5299. (max (funcall outline-level) max-level)))
  5300. (setq past-first-child t))
  5301. (org-flag-heading nil)))))
  5302. (defun org-show-subtree ()
  5303. "Show everything after this heading at deeper levels."
  5304. (interactive)
  5305. (org-flag-region
  5306. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5307. ;;;; Blocks visibility
  5308. (defun org-hide-block-toggle-maybe ()
  5309. "Toggle visibility of block at point.
  5310. Unlike to `org-hide-block-toggle', this function does not throw
  5311. an error. Return a non-nil value when toggling is successful."
  5312. (interactive)
  5313. (ignore-errors (org-hide-block-toggle)))
  5314. (defun org-hide-block-toggle (&optional force)
  5315. "Toggle the visibility of the current block.
  5316. When optional argument FORCE is `off', make block visible. If it
  5317. is non-nil, hide it unconditionally. Throw an error when not at
  5318. a block. Return a non-nil value when toggling is successful."
  5319. (interactive)
  5320. (let ((element (org-element-at-point)))
  5321. (unless (memq (org-element-type element)
  5322. '(center-block comment-block dynamic-block example-block
  5323. export-block quote-block special-block
  5324. src-block verse-block))
  5325. (user-error "Not at a block"))
  5326. (let* ((post (org-element-property :post-affiliated element))
  5327. (start (save-excursion
  5328. (goto-char post)
  5329. (line-end-position)))
  5330. (end (save-excursion
  5331. (goto-char (org-element-property :end element))
  5332. (skip-chars-backward " \t\n")
  5333. (line-end-position))))
  5334. ;; Do nothing when not before or at the block opening line or at
  5335. ;; the block closing line.
  5336. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5337. (cond ((eq force 'off)
  5338. (org-flag-region start end nil 'org-hide-block))
  5339. (force
  5340. (org-flag-region start end t 'org-hide-block))
  5341. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5342. (org-flag-region start end nil 'org-hide-block))
  5343. (t
  5344. (org-flag-region start end t 'org-hide-block)))
  5345. ;; When the block is hidden away, make sure point is left in
  5346. ;; a visible part of the buffer.
  5347. (when (invisible-p (max (1- (point)) (point-min)))
  5348. (goto-char post))
  5349. ;; Signal success.
  5350. t))))
  5351. (defun org-hide-block-toggle-all ()
  5352. "Toggle the visibility of all blocks in the current buffer."
  5353. (org-block-map 'org-hide-block-toggle))
  5354. (defun org-hide-block-all ()
  5355. "Fold all blocks in the current buffer."
  5356. (interactive)
  5357. (org-show-all '(blocks))
  5358. (org-block-map 'org-hide-block-toggle-maybe))
  5359. ;;;; Drawers visibility
  5360. (defun org-cycle-hide-drawers (state &optional exceptions)
  5361. "Re-hide all drawers after a visibility state change.
  5362. STATE should be one of the symbols listed in the docstring of
  5363. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5364. a list of strings specifying which drawers should not be hidden."
  5365. (when (and (derived-mode-p 'org-mode)
  5366. (not (memq state '(overview folded contents))))
  5367. (save-excursion
  5368. (let* ((globalp (eq state 'all))
  5369. (beg (if globalp (point-min) (point)))
  5370. (end (if globalp (point-max)
  5371. (if (eq state 'children)
  5372. (save-excursion (outline-next-heading) (point))
  5373. (org-end-of-subtree t)))))
  5374. (goto-char beg)
  5375. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5376. (unless (member-ignore-case (match-string 1) exceptions)
  5377. (let ((drawer (org-element-at-point)))
  5378. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5379. (org-flag-drawer t drawer)
  5380. ;; Make sure to skip drawer entirely or we might flag
  5381. ;; it another time when matching its ending line with
  5382. ;; `org-drawer-regexp'.
  5383. (goto-char (org-element-property :end drawer))))))))))
  5384. (defun org-flag-drawer (flag &optional element)
  5385. "When FLAG is non-nil, hide the drawer we are at.
  5386. Otherwise make it visible. When optional argument ELEMENT is
  5387. a parsed drawer, as returned by `org-element-at-point', hide or
  5388. show that drawer instead."
  5389. (let ((drawer (or element
  5390. (and (save-excursion
  5391. (beginning-of-line)
  5392. (looking-at-p org-drawer-regexp))
  5393. (org-element-at-point)))))
  5394. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5395. (let ((post (org-element-property :post-affiliated drawer)))
  5396. (org-flag-region
  5397. (save-excursion (goto-char post) (line-end-position))
  5398. (save-excursion (goto-char (org-element-property :end drawer))
  5399. (skip-chars-backward " \t\n")
  5400. (line-end-position))
  5401. flag 'org-hide-drawer)
  5402. ;; When the drawer is hidden away, make sure point lies in
  5403. ;; a visible part of the buffer.
  5404. (when (invisible-p (max (1- (point)) (point-min)))
  5405. (goto-char post))))))
  5406. ;;;; Visibility cycling
  5407. (defvar-local org-cycle-global-status nil)
  5408. (put 'org-cycle-global-status 'org-state t)
  5409. (defvar-local org-cycle-subtree-status nil)
  5410. (put 'org-cycle-subtree-status 'org-state t)
  5411. (defun org-show-all (&optional types)
  5412. "Show all contents in the visible part of the buffer.
  5413. By default, the function expands headings, blocks and drawers.
  5414. When optional argument TYPE is a list of symbols among `blocks',
  5415. `drawers' and `headings', to only expand one specific type."
  5416. (interactive)
  5417. (dolist (type (or types '(blocks drawers headings)))
  5418. (org-flag-region (point-min) (point-max) nil
  5419. (pcase type
  5420. (`blocks 'org-hide-block)
  5421. (`drawers 'org-hide-drawer)
  5422. (`headings 'outline)
  5423. (_ (error "Invalid type: %S" type))))))
  5424. ;;;###autoload
  5425. (defun org-cycle (&optional arg)
  5426. "TAB-action and visibility cycling for Org mode.
  5427. This is the command invoked in Org mode by the `TAB' key. Its main
  5428. purpose is outline visibility cycling, but it also invokes other actions
  5429. in special contexts.
  5430. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5431. the entire
  5432. buffer through 3 states (global cycling)
  5433. 1. OVERVIEW: Show only top-level headlines.
  5434. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5435. 3. SHOW ALL: Show everything.
  5436. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5437. switch to the startup visibility,
  5438. determined by the variable `org-startup-folded', and by any VISIBILITY
  5439. properties in the buffer.
  5440. With a `\\[universal-argument] \\[universal-argument] \
  5441. \\[universal-argument]' prefix argument, show the entire buffer, including
  5442. any drawers.
  5443. When inside a table, re-align the table and move to the next field.
  5444. When point is at the beginning of a headline, rotate the subtree started
  5445. by this line through 3 different states (local cycling)
  5446. 1. FOLDED: Only the main headline is shown.
  5447. 2. CHILDREN: The main headline and the direct children are shown.
  5448. From this state, you can move to one of the children
  5449. and zoom in further.
  5450. 3. SUBTREE: Show the entire subtree, including body text.
  5451. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5452. When point is at the beginning of an empty headline and the variable
  5453. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5454. of the headline by demoting and promoting it to likely levels. This
  5455. speeds up creation document structure by pressing `TAB' once or several
  5456. times right after creating a new headline.
  5457. When there is a numeric prefix, go up to a heading with level ARG, do
  5458. a `show-subtree' and return to the previous cursor position. If ARG
  5459. is negative, go up that many levels.
  5460. When point is not at the beginning of a headline, execute the global
  5461. binding for `TAB', which is re-indenting the line. See the option
  5462. `org-cycle-emulate-tab' for details.
  5463. As a special case, if point is at the beginning of the buffer and there is
  5464. no headline in line 1, this function will act as if called with prefix arg
  5465. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5466. prefix arg, but only
  5467. if the variable `org-cycle-global-at-bob' is t."
  5468. (interactive "P")
  5469. (org-load-modules-maybe)
  5470. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5471. (and org-cycle-level-after-item/entry-creation
  5472. (or (org-cycle-level)
  5473. (org-cycle-item-indentation))))
  5474. (let* ((limit-level
  5475. (or org-cycle-max-level
  5476. (and (boundp 'org-inlinetask-min-level)
  5477. org-inlinetask-min-level
  5478. (1- org-inlinetask-min-level))))
  5479. (nstars (and limit-level
  5480. (if org-odd-levels-only
  5481. (and limit-level (1- (* limit-level 2)))
  5482. limit-level)))
  5483. (org-outline-regexp
  5484. (if (not (derived-mode-p 'org-mode))
  5485. outline-regexp
  5486. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5487. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5488. (not (looking-at org-outline-regexp))))
  5489. (org-cycle-hook
  5490. (if bob-special
  5491. (delq 'org-optimize-window-after-visibility-change
  5492. (copy-sequence org-cycle-hook))
  5493. org-cycle-hook))
  5494. (pos (point)))
  5495. (cond
  5496. ((equal arg '(16))
  5497. (setq last-command 'dummy)
  5498. (org-set-startup-visibility)
  5499. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5500. ((equal arg '(64))
  5501. (org-show-all)
  5502. (org-unlogged-message "Entire buffer visible, including drawers"))
  5503. ((equal arg '(4)) (org-cycle-internal-global))
  5504. ;; Try hiding block at point.
  5505. ((org-hide-block-toggle-maybe))
  5506. ;; Try cdlatex TAB completion
  5507. ((org-try-cdlatex-tab))
  5508. ;; Table: enter it or move to the next field.
  5509. ((org-at-table-p 'any)
  5510. (if (org-at-table.el-p)
  5511. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5512. Use `\\[org-edit-special]' to edit table.el tables"))
  5513. (if arg (org-table-edit-field t)
  5514. (org-table-justify-field-maybe)
  5515. (call-interactively 'org-table-next-field))))
  5516. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5517. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5518. (bob-special (org-cycle-internal-global))
  5519. ;; Drawers: delegate to `org-flag-drawer'.
  5520. ((save-excursion
  5521. (beginning-of-line 1)
  5522. (looking-at org-drawer-regexp))
  5523. (org-flag-drawer ; toggle block visibility
  5524. (not (get-char-property (match-end 0) 'invisible))))
  5525. ;; Show-subtree, ARG levels up from here.
  5526. ((integerp arg)
  5527. (save-excursion
  5528. (org-back-to-heading)
  5529. (outline-up-heading (if (< arg 0) (- arg)
  5530. (- (funcall outline-level) arg)))
  5531. (org-show-subtree)))
  5532. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5533. ((and (featurep 'org-inlinetask)
  5534. (org-inlinetask-at-task-p)
  5535. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5536. (org-inlinetask-toggle-visibility))
  5537. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5538. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5539. (save-excursion (move-beginning-of-line 1)
  5540. (looking-at org-outline-regexp)))
  5541. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5542. (org-cycle-internal-local))
  5543. ;; From there: TAB emulation and template completion.
  5544. (buffer-read-only (org-back-to-heading))
  5545. ((run-hook-with-args-until-success
  5546. 'org-tab-after-check-for-cycling-hook))
  5547. ((run-hook-with-args-until-success
  5548. 'org-tab-before-tab-emulation-hook))
  5549. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5550. (or (not (bolp))
  5551. (not (looking-at org-outline-regexp))))
  5552. (call-interactively (global-key-binding "\t")))
  5553. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5554. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5555. (or (and (eq org-cycle-emulate-tab 'white)
  5556. (= (match-end 0) (point-at-eol)))
  5557. (and (eq org-cycle-emulate-tab 'whitestart)
  5558. (>= (match-end 0) pos))))
  5559. t
  5560. (eq org-cycle-emulate-tab t))
  5561. (call-interactively (global-key-binding "\t")))
  5562. (t (save-excursion
  5563. (org-back-to-heading)
  5564. (org-cycle)))))))
  5565. (defun org-cycle-internal-global ()
  5566. "Do the global cycling action."
  5567. ;; Hack to avoid display of messages for .org attachments in Gnus
  5568. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5569. (cond
  5570. ((and (eq last-command this-command)
  5571. (eq org-cycle-global-status 'overview))
  5572. ;; We just created the overview - now do table of contents
  5573. ;; This can be slow in very large buffers, so indicate action
  5574. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5575. (unless ga (org-unlogged-message "CONTENTS..."))
  5576. (org-content)
  5577. (unless ga (org-unlogged-message "CONTENTS...done"))
  5578. (setq org-cycle-global-status 'contents)
  5579. (run-hook-with-args 'org-cycle-hook 'contents))
  5580. ((and (eq last-command this-command)
  5581. (eq org-cycle-global-status 'contents))
  5582. ;; We just showed the table of contents - now show everything
  5583. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5584. (org-show-all '(headings blocks))
  5585. (unless ga (org-unlogged-message "SHOW ALL"))
  5586. (setq org-cycle-global-status 'all)
  5587. (run-hook-with-args 'org-cycle-hook 'all))
  5588. (t
  5589. ;; Default action: go to overview
  5590. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5591. (org-overview)
  5592. (unless ga (org-unlogged-message "OVERVIEW"))
  5593. (setq org-cycle-global-status 'overview)
  5594. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5595. (defvar org-called-with-limited-levels nil
  5596. "Non-nil when `org-with-limited-levels' is currently active.")
  5597. (defun org-cycle-internal-local ()
  5598. "Do the local cycling action."
  5599. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5600. ;; First, determine end of headline (EOH), end of subtree or item
  5601. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5602. (save-excursion
  5603. (if (org-at-item-p)
  5604. (progn
  5605. (beginning-of-line)
  5606. (setq struct (org-list-struct))
  5607. (setq eoh (point-at-eol))
  5608. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5609. (setq has-children (org-list-has-child-p (point) struct)))
  5610. (org-back-to-heading)
  5611. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5612. (setq eos (save-excursion (org-end-of-subtree t t)
  5613. (when (bolp) (backward-char)) (point)))
  5614. (setq has-children
  5615. (or (save-excursion
  5616. (let ((level (funcall outline-level)))
  5617. (outline-next-heading)
  5618. (and (org-at-heading-p t)
  5619. (> (funcall outline-level) level))))
  5620. (save-excursion
  5621. (org-list-search-forward (org-item-beginning-re) eos t)))))
  5622. ;; Determine end invisible part of buffer (EOL)
  5623. (beginning-of-line 2)
  5624. (while (and (not (eobp)) ;This is like `next-line'.
  5625. (get-char-property (1- (point)) 'invisible))
  5626. (goto-char (next-single-char-property-change (point) 'invisible))
  5627. (and (eolp) (beginning-of-line 2)))
  5628. (setq eol (point)))
  5629. ;; Find out what to do next and set `this-command'
  5630. (cond
  5631. ((= eos eoh)
  5632. ;; Nothing is hidden behind this heading
  5633. (unless (org-before-first-heading-p)
  5634. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5635. (org-unlogged-message "EMPTY ENTRY")
  5636. (setq org-cycle-subtree-status nil)
  5637. (save-excursion
  5638. (goto-char eos)
  5639. (outline-next-heading)
  5640. (when (org-invisible-p) (org-flag-heading nil))))
  5641. ((and (or (>= eol eos)
  5642. (not (string-match "\\S-" (buffer-substring eol eos))))
  5643. (or has-children
  5644. (not (setq children-skipped
  5645. org-cycle-skip-children-state-if-no-children))))
  5646. ;; Entire subtree is hidden in one line: children view
  5647. (unless (org-before-first-heading-p)
  5648. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5649. (if (org-at-item-p)
  5650. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5651. (org-show-entry)
  5652. (org-with-limited-levels (org-show-children))
  5653. (org-show-set-visibility 'canonical)
  5654. ;; Fold every list in subtree to top-level items.
  5655. (when (eq org-cycle-include-plain-lists 'integrate)
  5656. (save-excursion
  5657. (org-back-to-heading)
  5658. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5659. (beginning-of-line 1)
  5660. (let* ((struct (org-list-struct))
  5661. (prevs (org-list-prevs-alist struct))
  5662. (end (org-list-get-bottom-point struct)))
  5663. (dolist (e (org-list-get-all-items (point) struct prevs))
  5664. (org-list-set-item-visibility e struct 'folded))
  5665. (goto-char (if (< end eos) end eos)))))))
  5666. (org-unlogged-message "CHILDREN")
  5667. (save-excursion
  5668. (goto-char eos)
  5669. (outline-next-heading)
  5670. (when (org-invisible-p) (org-flag-heading nil)))
  5671. (setq org-cycle-subtree-status 'children)
  5672. (unless (org-before-first-heading-p)
  5673. (run-hook-with-args 'org-cycle-hook 'children)))
  5674. ((or children-skipped
  5675. (and (eq last-command this-command)
  5676. (eq org-cycle-subtree-status 'children)))
  5677. ;; We just showed the children, or no children are there,
  5678. ;; now show everything.
  5679. (unless (org-before-first-heading-p)
  5680. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5681. (org-flag-region eoh eos nil 'outline)
  5682. (org-unlogged-message
  5683. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5684. (setq org-cycle-subtree-status 'subtree)
  5685. (unless (org-before-first-heading-p)
  5686. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5687. (t
  5688. ;; Default action: hide the subtree.
  5689. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5690. (org-flag-region eoh eos t 'outline)
  5691. (org-unlogged-message "FOLDED")
  5692. (setq org-cycle-subtree-status 'folded)
  5693. (unless (org-before-first-heading-p)
  5694. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5695. ;;;###autoload
  5696. (defun org-global-cycle (&optional arg)
  5697. "Cycle the global visibility. For details see `org-cycle'.
  5698. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5699. With a numeric prefix, show all headlines up to that level."
  5700. (interactive "P")
  5701. (let ((org-cycle-include-plain-lists
  5702. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5703. (cond
  5704. ((integerp arg)
  5705. (org-show-all '(headings blocks))
  5706. (outline-hide-sublevels arg)
  5707. (setq org-cycle-global-status 'contents))
  5708. ((equal arg '(4))
  5709. (org-set-startup-visibility)
  5710. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5711. (t
  5712. (org-cycle '(4))))))
  5713. (defun org-set-startup-visibility ()
  5714. "Set the visibility required by startup options and properties."
  5715. (cond
  5716. ((eq org-startup-folded t)
  5717. (org-overview))
  5718. ((eq org-startup-folded 'content)
  5719. (org-content))
  5720. ((or (eq org-startup-folded 'showeverything)
  5721. (eq org-startup-folded nil))
  5722. (org-show-all)))
  5723. (unless (eq org-startup-folded 'showeverything)
  5724. (when org-hide-block-startup (org-hide-block-all))
  5725. (org-set-visibility-according-to-property)
  5726. (org-cycle-hide-archived-subtrees 'all)
  5727. (org-cycle-hide-drawers 'all)
  5728. (org-cycle-show-empty-lines t)))
  5729. (defun org-set-visibility-according-to-property ()
  5730. "Switch subtree visibility according to VISIBILITY property."
  5731. (interactive)
  5732. (let ((regexp (org-re-property "VISIBILITY")))
  5733. (org-with-point-at 1
  5734. (while (re-search-forward regexp nil t)
  5735. (let ((state (match-string 3)))
  5736. (if (not (org-at-property-p)) (outline-next-heading)
  5737. (save-excursion
  5738. (org-back-to-heading t)
  5739. (org-flag-subtree t)
  5740. (org-reveal)
  5741. (pcase state
  5742. ("folded"
  5743. (org-flag-subtree t))
  5744. ("children"
  5745. (org-show-hidden-entry)
  5746. (org-show-children))
  5747. ("content"
  5748. (save-excursion
  5749. (save-restriction
  5750. (org-narrow-to-subtree)
  5751. (org-content))))
  5752. ((or "all" "showall")
  5753. (outline-show-subtree))
  5754. (_ nil)))
  5755. (org-end-of-subtree)))))))
  5756. (defun org-overview ()
  5757. "Switch to overview mode, showing only top-level headlines.
  5758. This shows all headlines with a level equal or greater than the level
  5759. of the first headline in the buffer. This is important, because if the
  5760. first headline is not level one, then (hide-sublevels 1) gives confusing
  5761. results."
  5762. (interactive)
  5763. (save-excursion
  5764. (let ((level
  5765. (save-excursion
  5766. (goto-char (point-min))
  5767. (when (re-search-forward org-outline-regexp-bol nil t)
  5768. (goto-char (match-beginning 0))
  5769. (funcall outline-level)))))
  5770. (and level (outline-hide-sublevels level)))))
  5771. (defun org-content (&optional arg)
  5772. "Show all headlines in the buffer, like a table of contents.
  5773. With numerical argument N, show content up to level N."
  5774. (interactive "P")
  5775. (org-overview)
  5776. (save-excursion
  5777. ;; Visit all headings and show their offspring
  5778. (and (integerp arg) (org-overview))
  5779. (goto-char (point-max))
  5780. (catch 'exit
  5781. (while (and (progn (condition-case nil
  5782. (outline-previous-visible-heading 1)
  5783. (error (goto-char (point-min))))
  5784. t)
  5785. (looking-at org-outline-regexp))
  5786. (if (integerp arg)
  5787. (org-show-children (1- arg))
  5788. (outline-show-branches))
  5789. (when (bobp) (throw 'exit nil))))))
  5790. (defun org-optimize-window-after-visibility-change (state)
  5791. "Adjust the window after a change in outline visibility.
  5792. This function is the default value of the hook `org-cycle-hook'."
  5793. (when (get-buffer-window (current-buffer))
  5794. (cond
  5795. ((eq state 'content) nil)
  5796. ((eq state 'all) nil)
  5797. ((eq state 'folded) nil)
  5798. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5799. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5800. (defun org-clean-visibility-after-subtree-move ()
  5801. "Fix visibility issues after moving a subtree."
  5802. ;; First, find a reasonable region to look at:
  5803. ;; Start two siblings above, end three below
  5804. (let* ((beg (save-excursion
  5805. (and (org-get-last-sibling)
  5806. (org-get-last-sibling))
  5807. (point)))
  5808. (end (save-excursion
  5809. (and (org-get-next-sibling)
  5810. (org-get-next-sibling)
  5811. (org-get-next-sibling))
  5812. (if (org-at-heading-p)
  5813. (point-at-eol)
  5814. (point))))
  5815. (level (looking-at "\\*+"))
  5816. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5817. (save-excursion
  5818. (save-restriction
  5819. (narrow-to-region beg end)
  5820. (when re
  5821. ;; Properly fold already folded siblings
  5822. (goto-char (point-min))
  5823. (while (re-search-forward re nil t)
  5824. (when (and (not (org-invisible-p))
  5825. (org-invisible-p (line-end-position)))
  5826. (outline-hide-entry))))
  5827. (org-cycle-hide-drawers 'all)
  5828. (org-cycle-show-empty-lines 'overview)))))
  5829. (defun org-cycle-show-empty-lines (state)
  5830. "Show empty lines above all visible headlines.
  5831. The region to be covered depends on STATE when called through
  5832. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5833. entire buffer covered. Note that an empty line is only shown if there
  5834. are at least `org-cycle-separator-lines' empty lines before the headline."
  5835. (when (/= org-cycle-separator-lines 0)
  5836. (save-excursion
  5837. (let* ((n (abs org-cycle-separator-lines))
  5838. (re (cond
  5839. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5840. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5841. (t (let ((ns (number-to-string (- n 2))))
  5842. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5843. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5844. beg end)
  5845. (cond
  5846. ((memq state '(overview contents t))
  5847. (setq beg (point-min) end (point-max)))
  5848. ((memq state '(children folded))
  5849. (setq beg (point)
  5850. end (progn (org-end-of-subtree t t)
  5851. (line-beginning-position 2)))))
  5852. (when beg
  5853. (goto-char beg)
  5854. (while (re-search-forward re end t)
  5855. (unless (get-char-property (match-end 1) 'invisible)
  5856. (let ((e (match-end 1))
  5857. (b (if (>= org-cycle-separator-lines 0)
  5858. (match-beginning 1)
  5859. (save-excursion
  5860. (goto-char (match-beginning 0))
  5861. (skip-chars-backward " \t\n")
  5862. (line-end-position)))))
  5863. (org-flag-region b e nil 'outline))))))))
  5864. ;; Never hide empty lines at the end of the file.
  5865. (save-excursion
  5866. (goto-char (point-max))
  5867. (outline-previous-heading)
  5868. (outline-end-of-heading)
  5869. (when (and (looking-at "[ \t\n]+")
  5870. (= (match-end 0) (point-max)))
  5871. (org-flag-region (point) (match-end 0) nil 'outline))))
  5872. ;;;; Reveal point location
  5873. (defun org-show-context (&optional key)
  5874. "Make sure point and context are visible.
  5875. Optional argument KEY, when non-nil, is a symbol. See
  5876. `org-show-context-detail' for allowed values and how much is to
  5877. be shown."
  5878. (org-show-set-visibility
  5879. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5880. ((cdr (assq key org-show-context-detail)))
  5881. (t (cdr (assq 'default org-show-context-detail))))))
  5882. (defun org-show-set-visibility (detail)
  5883. "Set visibility around point according to DETAIL.
  5884. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5885. `tree', `canonical' or t. See `org-show-context-detail' for more
  5886. information."
  5887. ;; Show current heading and possibly its entry, following headline
  5888. ;; or all children.
  5889. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5890. (org-flag-heading nil)
  5891. (org-show-entry)
  5892. ;; If point is hidden within a drawer or a block, make sure to
  5893. ;; expose it.
  5894. (dolist (o (overlays-at (point)))
  5895. (when (memq (overlay-get o 'invisible)
  5896. '(org-hide-block org-hide-drawer outline))
  5897. (delete-overlay o)))
  5898. (unless (org-before-first-heading-p)
  5899. (org-with-limited-levels
  5900. (cl-case detail
  5901. ((tree canonical t) (org-show-children))
  5902. ((nil minimal ancestors))
  5903. (t (save-excursion
  5904. (outline-next-heading)
  5905. (org-flag-heading nil)))))))
  5906. ;; Show all siblings.
  5907. (when (eq detail 'lineage) (org-show-siblings))
  5908. ;; Show ancestors, possibly with their children.
  5909. (when (memq detail '(ancestors lineage tree canonical t))
  5910. (save-excursion
  5911. (while (org-up-heading-safe)
  5912. (org-flag-heading nil)
  5913. (when (memq detail '(canonical t)) (org-show-entry))
  5914. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5915. (defvar org-reveal-start-hook nil
  5916. "Hook run before revealing a location.")
  5917. (defun org-reveal (&optional siblings)
  5918. "Show current entry, hierarchy above it, and the following headline.
  5919. This can be used to show a consistent set of context around
  5920. locations exposed with `org-show-context'.
  5921. With optional argument SIBLINGS, on each level of the hierarchy all
  5922. siblings are shown. This repairs the tree structure to what it would
  5923. look like when opened with hierarchical calls to `org-cycle'.
  5924. With a \\[universal-argument] \\[universal-argument] prefix, \
  5925. go to the parent and show the entire tree."
  5926. (interactive "P")
  5927. (run-hooks 'org-reveal-start-hook)
  5928. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5929. ((equal siblings '(16))
  5930. (save-excursion
  5931. (when (org-up-heading-safe)
  5932. (org-show-subtree)
  5933. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5934. (t (org-show-set-visibility 'lineage))))
  5935. ;;; Indirect buffer display of subtrees
  5936. (defvar org-indirect-dedicated-frame nil
  5937. "This is the frame being used for indirect tree display.")
  5938. (defvar org-last-indirect-buffer nil)
  5939. (defun org-tree-to-indirect-buffer (&optional arg)
  5940. "Create indirect buffer and narrow it to current subtree.
  5941. With a numerical prefix ARG, go up to this level and then take that tree.
  5942. If ARG is negative, go up that many levels.
  5943. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5944. indirect buffer previously made with this command, to avoid proliferation of
  5945. indirect buffers. However, when you call the command with a \
  5946. `\\[universal-argument]' prefix, or
  5947. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5948. so that you can work with several indirect buffers at the same time. If
  5949. `org-indirect-buffer-display' is `dedicated-frame', the \
  5950. `\\[universal-argument]' prefix also
  5951. requests that a new frame be made for the new buffer, so that the dedicated
  5952. frame is not changed."
  5953. (interactive "P")
  5954. (let ((cbuf (current-buffer))
  5955. (cwin (selected-window))
  5956. (pos (point))
  5957. beg end level heading ibuf)
  5958. (save-excursion
  5959. (org-back-to-heading t)
  5960. (when (numberp arg)
  5961. (setq level (org-outline-level))
  5962. (when (< arg 0) (setq arg (+ level arg)))
  5963. (while (> (setq level (org-outline-level)) arg)
  5964. (org-up-heading-safe)))
  5965. (setq beg (point)
  5966. heading (org-get-heading 'no-tags))
  5967. (org-end-of-subtree t t)
  5968. (when (org-at-heading-p) (backward-char 1))
  5969. (setq end (point)))
  5970. (when (and (buffer-live-p org-last-indirect-buffer)
  5971. (not (eq org-indirect-buffer-display 'new-frame))
  5972. (not arg))
  5973. (kill-buffer org-last-indirect-buffer))
  5974. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5975. org-last-indirect-buffer ibuf)
  5976. (cond
  5977. ((or (eq org-indirect-buffer-display 'new-frame)
  5978. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5979. (select-frame (make-frame))
  5980. (delete-other-windows)
  5981. (pop-to-buffer-same-window ibuf)
  5982. (org-set-frame-title heading))
  5983. ((eq org-indirect-buffer-display 'dedicated-frame)
  5984. (raise-frame
  5985. (select-frame (or (and org-indirect-dedicated-frame
  5986. (frame-live-p org-indirect-dedicated-frame)
  5987. org-indirect-dedicated-frame)
  5988. (setq org-indirect-dedicated-frame (make-frame)))))
  5989. (delete-other-windows)
  5990. (pop-to-buffer-same-window ibuf)
  5991. (org-set-frame-title (concat "Indirect: " heading)))
  5992. ((eq org-indirect-buffer-display 'current-window)
  5993. (pop-to-buffer-same-window ibuf))
  5994. ((eq org-indirect-buffer-display 'other-window)
  5995. (pop-to-buffer ibuf))
  5996. (t (error "Invalid value")))
  5997. (narrow-to-region beg end)
  5998. (org-show-all '(headings blocks))
  5999. (goto-char pos)
  6000. (run-hook-with-args 'org-cycle-hook 'all)
  6001. (and (window-live-p cwin) (select-window cwin))))
  6002. (defun org-get-indirect-buffer (&optional buffer heading)
  6003. (setq buffer (or buffer (current-buffer)))
  6004. (let ((n 1) (base (buffer-name buffer)) bname)
  6005. (while (buffer-live-p
  6006. (get-buffer
  6007. (setq bname
  6008. (concat base "-"
  6009. (if heading (concat heading "-" (number-to-string n))
  6010. (number-to-string n))))))
  6011. (setq n (1+ n)))
  6012. (condition-case nil
  6013. (make-indirect-buffer buffer bname 'clone)
  6014. (error (make-indirect-buffer buffer bname)))))
  6015. (defun org-set-frame-title (title)
  6016. "Set the title of the current frame to the string TITLE."
  6017. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6018. ;;;; Structure editing
  6019. ;;; Inserting headlines
  6020. (defun org--line-empty-p (n)
  6021. "Is the Nth next line empty?
  6022. Counts the current line as N = 1 and the previous line as N = 0;
  6023. see `beginning-of-line'."
  6024. (save-excursion
  6025. (and (not (bobp))
  6026. (or (beginning-of-line n) t)
  6027. (save-match-data
  6028. (looking-at "[ \t]*$")))))
  6029. (defun org-previous-line-empty-p ()
  6030. "Is the previous line a blank line?
  6031. When NEXT is non-nil, check the next line instead."
  6032. (org--line-empty-p 0))
  6033. (defun org-next-line-empty-p ()
  6034. "Is the previous line a blank line?
  6035. When NEXT is non-nil, check the next line instead."
  6036. (org--line-empty-p 2))
  6037. (defun org--blank-before-heading-p (&optional parent)
  6038. "Non-nil when an empty line should precede a new heading here.
  6039. When optional argument PARENT is non-nil, consider parent
  6040. headline instead of current one."
  6041. (pcase (assq 'heading org-blank-before-new-entry)
  6042. (`(heading . auto)
  6043. (save-excursion
  6044. (org-with-limited-levels
  6045. (unless (and (org-before-first-heading-p)
  6046. (not (outline-next-heading)))
  6047. (org-back-to-heading t)
  6048. (when parent (org-up-heading-safe))
  6049. (cond ((not (bobp))
  6050. (org-previous-line-empty-p))
  6051. ((outline-next-heading)
  6052. (org-previous-line-empty-p))
  6053. ;; Ignore trailing spaces on last buffer line.
  6054. ((progn (skip-chars-backward " \t") (bolp))
  6055. (org-previous-line-empty-p))
  6056. (t nil))))))
  6057. (`(heading . ,value) value)
  6058. (_ nil)))
  6059. (defun org-insert-heading (&optional arg invisible-ok top)
  6060. "Insert a new heading or an item with the same depth at point.
  6061. If point is at the beginning of a heading, insert a new heading
  6062. or a new headline above the current one. When at the beginning
  6063. of a regular line of text, turn it into a heading.
  6064. If point is in the middle of a line, split it and create a new
  6065. headline with the text in the current line after point (see
  6066. `org-M-RET-may-split-line' on how to modify this behavior). As
  6067. a special case, on a headline, splitting can only happen on the
  6068. title itself. E.g., this excludes breaking stars or tags.
  6069. With a `\\[universal-argument]' prefix, set \
  6070. `org-insert-heading-respect-content' to
  6071. a non-nil value for the duration of the command. This forces the
  6072. insertion of a heading after the current subtree, independently
  6073. on the location of point.
  6074. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6075. insert the heading at the end of the tree
  6076. above the current heading. For example, if point is within a
  6077. 2nd-level heading, then it will insert a 2nd-level heading at
  6078. the end of the 1st-level parent subtree.
  6079. When INVISIBLE-OK is set, stop at invisible headlines when going
  6080. back. This is important for non-interactive uses of the
  6081. command.
  6082. When optional argument TOP is non-nil, insert a level 1 heading,
  6083. unconditionally."
  6084. (interactive "P")
  6085. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6086. (level (org-current-level))
  6087. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6088. (cond
  6089. ((or org-insert-heading-respect-content
  6090. (member arg '((4) (16)))
  6091. (and (not invisible-ok)
  6092. (invisible-p (max (1- (point)) (point-min)))))
  6093. ;; Position point at the location of insertion. Make sure we
  6094. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6095. (org-with-limited-levels
  6096. (if (not level) (outline-next-heading) ;before first headline
  6097. (org-back-to-heading invisible-ok)
  6098. (when (equal arg '(16)) (org-up-heading-safe))
  6099. (org-end-of-subtree)))
  6100. (unless (bolp) (insert "\n"))
  6101. (unless (and blank? (org-previous-line-empty-p))
  6102. (org-N-empty-lines-before-current (if blank? 1 0)))
  6103. (insert stars " ")
  6104. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6105. ;; is visible.
  6106. (unless invisible-ok
  6107. (pcase (get-char-property-and-overlay (point) 'invisible)
  6108. (`(outline . ,o)
  6109. (move-overlay o (overlay-start o) (line-end-position 0)))
  6110. (_ nil))))
  6111. ;; At a headline...
  6112. ((org-at-heading-p)
  6113. (cond ((bolp)
  6114. (when blank? (save-excursion (insert "\n")))
  6115. (save-excursion (insert stars " \n"))
  6116. (unless (and blank? (org-previous-line-empty-p))
  6117. (org-N-empty-lines-before-current (if blank? 1 0)))
  6118. (end-of-line))
  6119. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6120. (org-match-line org-complex-heading-regexp)
  6121. (org-pos-in-match-range (point) 4))
  6122. ;; Grab the text that should moved to the new headline.
  6123. ;; Preserve tags.
  6124. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6125. (if (looking-at "[ \t]*$") (replace-match "")
  6126. (org-align-tags))
  6127. (end-of-line)
  6128. (when blank? (insert "\n"))
  6129. (insert "\n" stars " ")
  6130. (when (org-string-nw-p split) (insert split))))
  6131. (t
  6132. (end-of-line)
  6133. (when blank? (insert "\n"))
  6134. (insert "\n" stars " "))))
  6135. ;; On regular text, turn line into a headline or split, if
  6136. ;; appropriate.
  6137. ((bolp)
  6138. (insert stars " ")
  6139. (unless (and blank? (org-previous-line-empty-p))
  6140. (org-N-empty-lines-before-current (if blank? 1 0))))
  6141. (t
  6142. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6143. (end-of-line))
  6144. (insert "\n" stars " ")
  6145. (unless (and blank? (org-previous-line-empty-p))
  6146. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6147. (run-hooks 'org-insert-heading-hook))
  6148. (defun org-N-empty-lines-before-current (n)
  6149. "Make the number of empty lines before current exactly N.
  6150. So this will delete or add empty lines."
  6151. (let ((column (current-column)))
  6152. (beginning-of-line)
  6153. (unless (bobp)
  6154. (let ((start (save-excursion
  6155. (skip-chars-backward " \r\t\n")
  6156. (line-end-position))))
  6157. (delete-region start (line-end-position 0))))
  6158. (insert (make-string n ?\n))
  6159. (move-to-column column)))
  6160. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6161. "Return the heading of the current entry, without the stars.
  6162. When NO-TAGS is non-nil, don't include tags.
  6163. When NO-TODO is non-nil, don't include TODO keywords.
  6164. When NO-PRIORITY is non-nil, don't include priority cookie.
  6165. When NO-COMMENT is non-nil, don't include COMMENT string.
  6166. Return nil before first heading."
  6167. (unless (org-before-first-heading-p)
  6168. (save-excursion
  6169. (org-back-to-heading t)
  6170. (let ((case-fold-search nil))
  6171. (looking-at org-complex-heading-regexp)
  6172. (let ((todo (and (not no-todo) (match-string 2)))
  6173. (priority (and (not no-priority) (match-string 3)))
  6174. (headline (pcase (match-string 4)
  6175. (`nil "")
  6176. ((and (guard no-comment) h)
  6177. (replace-regexp-in-string
  6178. (eval-when-compile
  6179. (format "\\`%s[ \t]+" org-comment-string))
  6180. "" h))
  6181. (h h)))
  6182. (tags (and (not no-tags) (match-string 5))))
  6183. (mapconcat #'identity
  6184. (delq nil (list todo priority headline tags))
  6185. " "))))))
  6186. (defun org-heading-components ()
  6187. "Return the components of the current heading.
  6188. This is a list with the following elements:
  6189. - the level as an integer
  6190. - the reduced level, different if `org-odd-levels-only' is set.
  6191. - the TODO keyword, or nil
  6192. - the priority character, like ?A, or nil if no priority is given
  6193. - the headline text itself, or the tags string if no headline text
  6194. - the tags string, or nil."
  6195. (save-excursion
  6196. (org-back-to-heading t)
  6197. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6198. (list (length (match-string 1))
  6199. (org-reduced-level (length (match-string 1)))
  6200. (match-string-no-properties 2)
  6201. (and (match-end 3) (aref (match-string 3) 2))
  6202. (match-string-no-properties 4)
  6203. (match-string-no-properties 5)))))
  6204. (defun org-get-entry ()
  6205. "Get the entry text, after heading, entire subtree."
  6206. (save-excursion
  6207. (org-back-to-heading t)
  6208. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6209. (defun org-edit-headline (&optional heading)
  6210. "Edit the current headline.
  6211. Set it to HEADING when provided."
  6212. (interactive)
  6213. (org-with-wide-buffer
  6214. (org-back-to-heading t)
  6215. (let ((case-fold-search nil))
  6216. (when (looking-at org-complex-heading-regexp)
  6217. (let* ((old (match-string-no-properties 4))
  6218. (new (save-match-data
  6219. (org-trim (or heading (read-string "Edit: " old))))))
  6220. (unless (equal old new)
  6221. (if old (replace-match new t t nil 4)
  6222. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6223. (insert " " new))
  6224. (org-align-tags)
  6225. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6226. (defun org-insert-heading-after-current ()
  6227. "Insert a new heading with same level as current, after current subtree."
  6228. (interactive)
  6229. (org-back-to-heading)
  6230. (org-insert-heading)
  6231. (org-move-subtree-down)
  6232. (end-of-line 1))
  6233. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6234. "Insert heading with `org-insert-heading-respect-content' set to t."
  6235. (interactive)
  6236. (org-insert-heading '(4) invisible-ok))
  6237. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6238. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6239. (interactive)
  6240. (org-insert-todo-heading force-state '(4)))
  6241. (defun org-insert-todo-heading (arg &optional force-heading)
  6242. "Insert a new heading with the same level and TODO state as current heading.
  6243. If the heading has no TODO state, or if the state is DONE, use
  6244. the first state (TODO by default). Also with one prefix arg,
  6245. force first state. With two prefix args, force inserting at the
  6246. end of the parent subtree.
  6247. When called at a plain list item, insert a new item with an
  6248. unchecked check box."
  6249. (interactive "P")
  6250. (when (or force-heading (not (org-insert-item 'checkbox)))
  6251. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6252. force-heading))
  6253. (save-excursion
  6254. (org-forward-heading-same-level -1)
  6255. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6256. (let* ((new-mark-x
  6257. (if (or (equal arg '(4))
  6258. (not (match-beginning 2))
  6259. (member (match-string 2) org-done-keywords))
  6260. (car org-todo-keywords-1)
  6261. (match-string 2)))
  6262. (new-mark
  6263. (or
  6264. (run-hook-with-args-until-success
  6265. 'org-todo-get-default-hook new-mark-x nil)
  6266. new-mark-x)))
  6267. (beginning-of-line 1)
  6268. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6269. (if org-treat-insert-todo-heading-as-state-change
  6270. (org-todo new-mark)
  6271. (insert new-mark " "))))
  6272. (when org-provide-todo-statistics
  6273. (org-update-parent-todo-statistics))))
  6274. (defun org-insert-subheading (arg)
  6275. "Insert a new subheading and demote it.
  6276. Works for outline headings and for plain lists alike."
  6277. (interactive "P")
  6278. (org-insert-heading arg)
  6279. (cond
  6280. ((org-at-heading-p) (org-do-demote))
  6281. ((org-at-item-p) (org-indent-item))))
  6282. (defun org-insert-todo-subheading (arg)
  6283. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6284. Works for outline headings and for plain lists alike."
  6285. (interactive "P")
  6286. (org-insert-todo-heading arg)
  6287. (cond
  6288. ((org-at-heading-p) (org-do-demote))
  6289. ((org-at-item-p) (org-indent-item))))
  6290. ;;; Promotion and Demotion
  6291. (defvar org-after-demote-entry-hook nil
  6292. "Hook run after an entry has been demoted.
  6293. The cursor will be at the beginning of the entry.
  6294. When a subtree is being demoted, the hook will be called for each node.")
  6295. (defvar org-after-promote-entry-hook nil
  6296. "Hook run after an entry has been promoted.
  6297. The cursor will be at the beginning of the entry.
  6298. When a subtree is being promoted, the hook will be called for each node.")
  6299. (defun org-promote-subtree ()
  6300. "Promote the entire subtree.
  6301. See also `org-promote'."
  6302. (interactive)
  6303. (save-excursion
  6304. (org-with-limited-levels (org-map-tree 'org-promote)))
  6305. (org-fix-position-after-promote))
  6306. (defun org-demote-subtree ()
  6307. "Demote the entire subtree.
  6308. See `org-demote' and `org-promote'."
  6309. (interactive)
  6310. (save-excursion
  6311. (org-with-limited-levels (org-map-tree 'org-demote)))
  6312. (org-fix-position-after-promote))
  6313. (defun org-do-promote ()
  6314. "Promote the current heading higher up the tree.
  6315. If the region is active in `transient-mark-mode', promote all
  6316. headings in the region."
  6317. (interactive)
  6318. (save-excursion
  6319. (if (org-region-active-p)
  6320. (org-map-region 'org-promote (region-beginning) (region-end))
  6321. (org-promote)))
  6322. (org-fix-position-after-promote))
  6323. (defun org-do-demote ()
  6324. "Demote the current heading lower down the tree.
  6325. If the region is active in `transient-mark-mode', demote all
  6326. headings in the region."
  6327. (interactive)
  6328. (save-excursion
  6329. (if (org-region-active-p)
  6330. (org-map-region 'org-demote (region-beginning) (region-end))
  6331. (org-demote)))
  6332. (org-fix-position-after-promote))
  6333. (defun org-fix-position-after-promote ()
  6334. "Fix cursor position and indentation after demoting/promoting."
  6335. (let ((pos (point)))
  6336. (when (save-excursion
  6337. (beginning-of-line)
  6338. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6339. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6340. (cond ((eobp) (insert " "))
  6341. ((eolp) (insert " "))
  6342. ((equal (char-after) ?\s) (forward-char 1))))))
  6343. (defun org-current-level ()
  6344. "Return the level of the current entry, or nil if before the first headline.
  6345. The level is the number of stars at the beginning of the
  6346. headline. Use `org-reduced-level' to remove the effect of
  6347. `org-odd-levels'. Unlike to `org-outline-level', this function
  6348. ignores inlinetasks."
  6349. (let ((level (org-with-limited-levels (org-outline-level))))
  6350. (and (> level 0) level)))
  6351. (defun org-get-previous-line-level ()
  6352. "Return the outline depth of the last headline before the current line.
  6353. Returns 0 for the first headline in the buffer, and nil if before the
  6354. first headline."
  6355. (and (org-current-level)
  6356. (or (and (/= (line-beginning-position) (point-min))
  6357. (save-excursion (beginning-of-line 0) (org-current-level)))
  6358. 0)))
  6359. (defun org-reduced-level (l)
  6360. "Compute the effective level of a heading.
  6361. This takes into account the setting of `org-odd-levels-only'."
  6362. (cond
  6363. ((zerop l) 0)
  6364. (org-odd-levels-only (1+ (floor (/ l 2))))
  6365. (t l)))
  6366. (defun org-level-increment ()
  6367. "Return the number of stars that will be added or removed at a
  6368. time to headlines when structure editing, based on the value of
  6369. `org-odd-levels-only'."
  6370. (if org-odd-levels-only 2 1))
  6371. (defun org-get-valid-level (level &optional change)
  6372. "Rectify a level change under the influence of `org-odd-levels-only'.
  6373. LEVEL is a current level, CHANGE is by how much the level should
  6374. be modified. Even if CHANGE is nil, LEVEL may be returned
  6375. modified because even level numbers will become the next higher
  6376. odd number. Returns values greater than 0."
  6377. (if org-odd-levels-only
  6378. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6379. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6380. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6381. (max 1 (+ level (or change 0)))))
  6382. (defun org-promote ()
  6383. "Promote the current heading higher up the tree."
  6384. (org-with-wide-buffer
  6385. (org-back-to-heading t)
  6386. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6387. after-change-functions))
  6388. (level (save-match-data (funcall outline-level)))
  6389. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6390. (diff (abs (- level (length up-head) -1))))
  6391. (cond
  6392. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6393. (replace-match "# " nil t))
  6394. ((= level 1)
  6395. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6396. (t (replace-match up-head nil t)))
  6397. (unless (= level 1)
  6398. (when org-auto-align-tags (org-align-tags))
  6399. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6400. (run-hooks 'org-after-promote-entry-hook))))
  6401. (defun org-demote ()
  6402. "Demote the current heading lower down the tree."
  6403. (org-with-wide-buffer
  6404. (org-back-to-heading t)
  6405. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6406. after-change-functions))
  6407. (level (save-match-data (funcall outline-level)))
  6408. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6409. (diff (abs (- level (length down-head) -1))))
  6410. (replace-match down-head nil t)
  6411. (when org-auto-align-tags (org-align-tags))
  6412. (when org-adapt-indentation (org-fixup-indentation diff))
  6413. (run-hooks 'org-after-demote-entry-hook))))
  6414. (defun org-cycle-level ()
  6415. "Cycle the level of an empty headline through possible states.
  6416. This goes first to child, then to parent, level, then up the hierarchy.
  6417. After top level, it switches back to sibling level."
  6418. (interactive)
  6419. (let ((org-adapt-indentation nil))
  6420. (when (org-point-at-end-of-empty-headline)
  6421. (setq this-command 'org-cycle-level) ; Only needed for caching
  6422. (let ((cur-level (org-current-level))
  6423. (prev-level (org-get-previous-line-level)))
  6424. (cond
  6425. ;; If first headline in file, promote to top-level.
  6426. ((= prev-level 0)
  6427. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6428. do (org-do-promote)))
  6429. ;; If same level as prev, demote one.
  6430. ((= prev-level cur-level)
  6431. (org-do-demote))
  6432. ;; If parent is top-level, promote to top level if not already.
  6433. ((= prev-level 1)
  6434. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6435. do (org-do-promote)))
  6436. ;; If top-level, return to prev-level.
  6437. ((= cur-level 1)
  6438. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6439. do (org-do-demote)))
  6440. ;; If less than prev-level, promote one.
  6441. ((< cur-level prev-level)
  6442. (org-do-promote))
  6443. ;; If deeper than prev-level, promote until higher than
  6444. ;; prev-level.
  6445. ((> cur-level prev-level)
  6446. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6447. do (org-do-promote))))
  6448. t))))
  6449. (defun org-map-tree (fun)
  6450. "Call FUN for every heading underneath the current one."
  6451. (org-back-to-heading t)
  6452. (let ((level (funcall outline-level)))
  6453. (save-excursion
  6454. (funcall fun)
  6455. (while (and (progn
  6456. (outline-next-heading)
  6457. (> (funcall outline-level) level))
  6458. (not (eobp)))
  6459. (funcall fun)))))
  6460. (defun org-map-region (fun beg end)
  6461. "Call FUN for every heading between BEG and END."
  6462. (let ((org-ignore-region t))
  6463. (save-excursion
  6464. (setq end (copy-marker end))
  6465. (goto-char beg)
  6466. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6467. (< (point) end))
  6468. (funcall fun))
  6469. (while (and (progn
  6470. (outline-next-heading)
  6471. (< (point) end))
  6472. (not (eobp)))
  6473. (funcall fun)))))
  6474. (defun org-fixup-indentation (diff)
  6475. "Change the indentation in the current entry by DIFF.
  6476. DIFF is an integer. Indentation is done according to the
  6477. following rules:
  6478. - Planning information and property drawers are always indented
  6479. according to the new level of the headline;
  6480. - Footnote definitions and their contents are ignored;
  6481. - Inlinetasks' boundaries are not shifted;
  6482. - Empty lines are ignored;
  6483. - Other lines' indentation are shifted by DIFF columns, unless
  6484. it would introduce a structural change in the document, in
  6485. which case no shifting is done at all.
  6486. Assume point is at a heading or an inlinetask beginning."
  6487. (org-with-wide-buffer
  6488. (narrow-to-region (line-beginning-position)
  6489. (save-excursion
  6490. (if (org-with-limited-levels (org-at-heading-p))
  6491. (org-with-limited-levels (outline-next-heading))
  6492. (org-inlinetask-goto-end))
  6493. (point)))
  6494. (forward-line)
  6495. ;; Indent properly planning info and property drawer.
  6496. (when (looking-at-p org-planning-line-re)
  6497. (org-indent-line)
  6498. (forward-line))
  6499. (when (looking-at org-property-drawer-re)
  6500. (goto-char (match-end 0))
  6501. (forward-line)
  6502. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6503. (catch 'no-shift
  6504. (when (zerop diff) (throw 'no-shift nil))
  6505. ;; If DIFF is negative, first check if a shift is possible at all
  6506. ;; (e.g., it doesn't break structure). This can only happen if
  6507. ;; some contents are not properly indented.
  6508. (let ((case-fold-search t))
  6509. (when (< diff 0)
  6510. (let ((diff (- diff))
  6511. (forbidden-re (concat org-outline-regexp
  6512. "\\|"
  6513. (substring org-footnote-definition-re 1))))
  6514. (save-excursion
  6515. (while (not (eobp))
  6516. (cond
  6517. ((looking-at-p "[ \t]*$") (forward-line))
  6518. ((and (looking-at-p org-footnote-definition-re)
  6519. (let ((e (org-element-at-point)))
  6520. (and (eq (org-element-type e) 'footnote-definition)
  6521. (goto-char (org-element-property :end e))))))
  6522. ((looking-at-p org-outline-regexp) (forward-line))
  6523. ;; Give up if shifting would move before column 0 or
  6524. ;; if it would introduce a headline or a footnote
  6525. ;; definition.
  6526. (t
  6527. (skip-chars-forward " \t")
  6528. (let ((ind (current-column)))
  6529. (when (or (< ind diff)
  6530. (and (= ind diff) (looking-at-p forbidden-re)))
  6531. (throw 'no-shift nil)))
  6532. ;; Ignore contents of example blocks and source
  6533. ;; blocks if their indentation is meant to be
  6534. ;; preserved. Jump to block's closing line.
  6535. (beginning-of-line)
  6536. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6537. (let ((e (org-element-at-point)))
  6538. (and (memq (org-element-type e)
  6539. '(example-block src-block))
  6540. (or org-src-preserve-indentation
  6541. (org-element-property :preserve-indent e))
  6542. (goto-char (org-element-property :end e))
  6543. (progn (skip-chars-backward " \r\t\n")
  6544. (beginning-of-line)
  6545. t))))
  6546. (forward-line))))))))
  6547. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6548. ;; by DIFF. Also skip contents of source or example blocks
  6549. ;; when indentation is meant to be preserved.
  6550. (while (not (eobp))
  6551. (cond
  6552. ((and (looking-at-p org-footnote-definition-re)
  6553. (let ((e (org-element-at-point)))
  6554. (and (eq (org-element-type e) 'footnote-definition)
  6555. (goto-char (org-element-property :end e))))))
  6556. ((looking-at-p org-outline-regexp) (forward-line))
  6557. ((looking-at-p "[ \t]*$") (forward-line))
  6558. (t
  6559. (indent-line-to (+ (current-indentation) diff))
  6560. (beginning-of-line)
  6561. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6562. (let ((e (org-element-at-point)))
  6563. (and (memq (org-element-type e)
  6564. '(example-block src-block))
  6565. (or org-src-preserve-indentation
  6566. (org-element-property :preserve-indent e))
  6567. (goto-char (org-element-property :end e))
  6568. (progn (skip-chars-backward " \r\t\n")
  6569. (beginning-of-line)
  6570. t))))
  6571. (forward-line)))))))))
  6572. (defun org-convert-to-odd-levels ()
  6573. "Convert an Org file with all levels allowed to one with odd levels.
  6574. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6575. level 5 etc."
  6576. (interactive)
  6577. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6578. (let ((outline-level 'org-outline-level)
  6579. (org-odd-levels-only nil) n)
  6580. (save-excursion
  6581. (goto-char (point-min))
  6582. (while (re-search-forward "^\\*\\*+ " nil t)
  6583. (setq n (- (length (match-string 0)) 2))
  6584. (while (>= (setq n (1- n)) 0)
  6585. (org-demote))
  6586. (end-of-line 1))))))
  6587. (defun org-convert-to-oddeven-levels ()
  6588. "Convert an Org file with only odd levels to one with odd/even levels.
  6589. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6590. file contains a section with an even level, conversion would
  6591. destroy the structure of the file. An error is signaled in this
  6592. case."
  6593. (interactive)
  6594. (goto-char (point-min))
  6595. ;; First check if there are no even levels
  6596. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6597. (org-show-set-visibility 'canonical)
  6598. (error "Not all levels are odd in this file. Conversion not possible"))
  6599. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6600. (let ((outline-regexp org-outline-regexp)
  6601. (outline-level 'org-outline-level)
  6602. (org-odd-levels-only nil) n)
  6603. (save-excursion
  6604. (goto-char (point-min))
  6605. (while (re-search-forward "^\\*\\*+ " nil t)
  6606. (setq n (/ (1- (length (match-string 0))) 2))
  6607. (while (>= (setq n (1- n)) 0)
  6608. (org-promote))
  6609. (end-of-line 1))))))
  6610. (defun org-tr-level (n)
  6611. "Make N odd if required."
  6612. (if org-odd-levels-only (1+ (/ n 2)) n))
  6613. ;;; Vertical tree motion, cutting and pasting of subtrees
  6614. (defun org-move-subtree-up (&optional arg)
  6615. "Move the current subtree up past ARG headlines of the same level."
  6616. (interactive "p")
  6617. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6618. (defun org-move-subtree-down (&optional arg)
  6619. "Move the current subtree down past ARG headlines of the same level."
  6620. (interactive "p")
  6621. (setq arg (prefix-numeric-value arg))
  6622. (org-preserve-local-variables
  6623. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6624. 'org-get-last-sibling))
  6625. (ins-point (make-marker))
  6626. (cnt (abs arg))
  6627. (col (current-column))
  6628. beg end txt folded)
  6629. ;; Select the tree
  6630. (org-back-to-heading)
  6631. (setq beg (point))
  6632. (save-match-data
  6633. (save-excursion (outline-end-of-heading)
  6634. (setq folded (org-invisible-p)))
  6635. (progn (org-end-of-subtree nil t)
  6636. (unless (eobp) (backward-char))))
  6637. (outline-next-heading)
  6638. (setq end (point))
  6639. (goto-char beg)
  6640. ;; Find insertion point, with error handling
  6641. (while (> cnt 0)
  6642. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6643. (goto-char beg)
  6644. (user-error "Cannot move past superior level or buffer limit"))
  6645. (setq cnt (1- cnt)))
  6646. (when (> arg 0)
  6647. ;; Moving forward - still need to move over subtree
  6648. (org-end-of-subtree t t)
  6649. (save-excursion
  6650. (org-back-over-empty-lines)
  6651. (or (bolp) (newline))))
  6652. (move-marker ins-point (point))
  6653. (setq txt (buffer-substring beg end))
  6654. (org-save-markers-in-region beg end)
  6655. (delete-region beg end)
  6656. (org-remove-empty-overlays-at beg)
  6657. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6658. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6659. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6660. (let ((bbb (point)))
  6661. (insert-before-markers txt)
  6662. (org-reinstall-markers-in-region bbb)
  6663. (move-marker ins-point bbb))
  6664. (or (bolp) (insert "\n"))
  6665. (goto-char ins-point)
  6666. (org-skip-whitespace)
  6667. (move-marker ins-point nil)
  6668. (if folded
  6669. (org-flag-subtree t)
  6670. (org-show-entry)
  6671. (org-show-children))
  6672. (org-clean-visibility-after-subtree-move)
  6673. ;; move back to the initial column we were at
  6674. (move-to-column col))))
  6675. (defvar org-subtree-clip ""
  6676. "Clipboard for cut and paste of subtrees.
  6677. This is actually only a copy of the kill, because we use the normal kill
  6678. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6679. (defvar org-subtree-clip-folded nil
  6680. "Was the last copied subtree folded?
  6681. This is used to fold the tree back after pasting.")
  6682. (defun org-cut-subtree (&optional n)
  6683. "Cut the current subtree into the clipboard.
  6684. With prefix arg N, cut this many sequential subtrees.
  6685. This is a short-hand for marking the subtree and then cutting it."
  6686. (interactive "p")
  6687. (org-copy-subtree n 'cut))
  6688. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6689. "Copy the current subtree into the clipboard.
  6690. With prefix arg N, copy this many sequential subtrees.
  6691. This is a short-hand for marking the subtree and then copying it.
  6692. If CUT is non-nil, actually cut the subtree.
  6693. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6694. of some markers in the region, even if CUT is non-nil. This is
  6695. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6696. (interactive "p")
  6697. (org-preserve-local-variables
  6698. (let (beg end folded (beg0 (point)))
  6699. (if (called-interactively-p 'any)
  6700. (org-back-to-heading nil) ; take what looks like a subtree
  6701. (org-back-to-heading t)) ; take what is really there
  6702. (setq beg (point))
  6703. (skip-chars-forward " \t\r\n")
  6704. (save-match-data
  6705. (if nosubtrees
  6706. (outline-next-heading)
  6707. (save-excursion (outline-end-of-heading)
  6708. (setq folded (org-invisible-p)))
  6709. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6710. (org-end-of-subtree t t)))
  6711. ;; Include the end of an inlinetask
  6712. (when (and (featurep 'org-inlinetask)
  6713. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6714. "END[ \t]*$")))
  6715. (end-of-line))
  6716. (setq end (point))
  6717. (goto-char beg0)
  6718. (when (> end beg)
  6719. (setq org-subtree-clip-folded folded)
  6720. (when (or cut force-store-markers)
  6721. (org-save-markers-in-region beg end))
  6722. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6723. (setq org-subtree-clip (current-kill 0))
  6724. (message "%s: Subtree(s) with %d characters"
  6725. (if cut "Cut" "Copied")
  6726. (length org-subtree-clip))))))
  6727. (defun org-paste-subtree (&optional level tree for-yank remove)
  6728. "Paste the clipboard as a subtree, with modification of headline level.
  6729. The entire subtree is promoted or demoted in order to match a new headline
  6730. level.
  6731. If the cursor is at the beginning of a headline, the same level as
  6732. that headline is used to paste the tree.
  6733. If not, the new level is derived from the *visible* headings
  6734. before and after the insertion point, and taken to be the inferior headline
  6735. level of the two. So if the previous visible heading is level 3 and the
  6736. next is level 4 (or vice versa), level 4 will be used for insertion.
  6737. This makes sure that the subtree remains an independent subtree and does
  6738. not swallow low level entries.
  6739. You can also force a different level, either by using a numeric prefix
  6740. argument, or by inserting the heading marker by hand. For example, if the
  6741. cursor is after \"*****\", then the tree will be shifted to level 5.
  6742. If optional TREE is given, use this text instead of the kill ring.
  6743. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6744. move back over whitespace before inserting, and move point to the end of
  6745. the inserted text when done.
  6746. When REMOVE is non-nil, remove the subtree from the clipboard."
  6747. (interactive "P")
  6748. (setq tree (or tree (and kill-ring (current-kill 0))))
  6749. (unless (org-kill-is-subtree-p tree)
  6750. (user-error
  6751. (substitute-command-keys
  6752. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6753. (org-with-limited-levels
  6754. (let* ((visp (not (org-invisible-p)))
  6755. (txt tree)
  6756. (old-level (if (string-match org-outline-regexp-bol txt)
  6757. (- (match-end 0) (match-beginning 0) 1)
  6758. -1))
  6759. (force-level
  6760. (cond
  6761. (level (prefix-numeric-value level))
  6762. ;; When point is after the stars in an otherwise empty
  6763. ;; headline, use the number of stars as the forced level.
  6764. ((and (org-match-line "^\\*+[ \t]*$")
  6765. (not (eq ?* (char-after))))
  6766. (org-outline-level))
  6767. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6768. (previous-level
  6769. (save-excursion
  6770. (org-previous-visible-heading 1)
  6771. (if (org-at-heading-p) (org-outline-level) 1)))
  6772. (next-level
  6773. (save-excursion
  6774. (if (org-at-heading-p) (org-outline-level)
  6775. (org-next-visible-heading 1)
  6776. (if (org-at-heading-p) (org-outline-level) 1))))
  6777. (new-level (or force-level (max previous-level next-level)))
  6778. (shift (if (or (= old-level -1)
  6779. (= new-level -1)
  6780. (= old-level new-level))
  6781. 0
  6782. (- new-level old-level)))
  6783. (delta (if (> shift 0) -1 1))
  6784. (func (if (> shift 0) #'org-demote #'org-promote))
  6785. (org-odd-levels-only nil)
  6786. beg end newend)
  6787. ;; Remove the forced level indicator.
  6788. (when (and force-level (not level))
  6789. (delete-region (line-beginning-position) (point)))
  6790. ;; Paste before the next visible heading or at end of buffer,
  6791. ;; unless point is at the beginning of a headline.
  6792. (unless (and (bolp) (org-at-heading-p))
  6793. (org-next-visible-heading 1)
  6794. (unless (bolp) (insert "\n")))
  6795. (setq beg (point))
  6796. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6797. (insert-before-markers txt)
  6798. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6799. (setq newend (point))
  6800. (org-reinstall-markers-in-region beg)
  6801. (setq end (point))
  6802. (goto-char beg)
  6803. (skip-chars-forward " \t\n\r")
  6804. (setq beg (point))
  6805. (when (and (org-invisible-p) visp)
  6806. (save-excursion (outline-show-heading)))
  6807. ;; Shift if necessary.
  6808. (unless (= shift 0)
  6809. (save-restriction
  6810. (narrow-to-region beg end)
  6811. (while (not (= shift 0))
  6812. (org-map-region func (point-min) (point-max))
  6813. (setq shift (+ delta shift)))
  6814. (goto-char (point-min))
  6815. (setq newend (point-max))))
  6816. (when (or for-yank (called-interactively-p 'interactive))
  6817. (message "Clipboard pasted as level %d subtree" new-level))
  6818. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6819. kill-ring
  6820. (equal org-subtree-clip (current-kill 0))
  6821. org-subtree-clip-folded)
  6822. ;; The tree was folded before it was killed/copied
  6823. (org-flag-subtree t))
  6824. (when for-yank (goto-char newend))
  6825. (when remove (pop kill-ring)))))
  6826. (defun org-kill-is-subtree-p (&optional txt)
  6827. "Check if the current kill is an outline subtree, or a set of trees.
  6828. Returns nil if kill does not start with a headline, or if the first
  6829. headline level is not the largest headline level in the tree.
  6830. So this will actually accept several entries of equal levels as well,
  6831. which is OK for `org-paste-subtree'.
  6832. If optional TXT is given, check this string instead of the current kill."
  6833. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6834. (re (org-get-limited-outline-regexp))
  6835. (^re (concat "^" re))
  6836. (start-level (and kill
  6837. (string-match
  6838. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6839. kill)
  6840. (- (match-end 2) (match-beginning 2) 1)))
  6841. (start (1+ (or (match-beginning 2) -1))))
  6842. (if (not start-level)
  6843. (progn
  6844. nil) ;; does not even start with a heading
  6845. (catch 'exit
  6846. (while (setq start (string-match ^re kill (1+ start)))
  6847. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6848. (throw 'exit nil)))
  6849. t))))
  6850. (defvar org-markers-to-move nil
  6851. "Markers that should be moved with a cut-and-paste operation.
  6852. Those markers are stored together with their positions relative to
  6853. the start of the region.")
  6854. (defun org-save-markers-in-region (beg end)
  6855. "Check markers in region.
  6856. If these markers are between BEG and END, record their position relative
  6857. to BEG, so that after moving the block of text, we can put the markers back
  6858. into place.
  6859. This function gets called just before an entry or tree gets cut from the
  6860. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6861. called immediately, to move the markers with the entries."
  6862. (setq org-markers-to-move nil)
  6863. (when (featurep 'org-clock)
  6864. (org-clock-save-markers-for-cut-and-paste beg end))
  6865. (when (featurep 'org-agenda)
  6866. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6867. (defun org-check-and-save-marker (marker beg end)
  6868. "Check if MARKER is between BEG and END.
  6869. If yes, remember the marker and the distance to BEG."
  6870. (when (and (marker-buffer marker)
  6871. (equal (marker-buffer marker) (current-buffer))
  6872. (>= marker beg) (< marker end))
  6873. (push (cons marker (- marker beg)) org-markers-to-move)))
  6874. (defun org-reinstall-markers-in-region (beg)
  6875. "Move all remembered markers to their position relative to BEG."
  6876. (dolist (x org-markers-to-move)
  6877. (move-marker (car x) (+ beg (cdr x))))
  6878. (setq org-markers-to-move nil))
  6879. (defun org-narrow-to-subtree ()
  6880. "Narrow buffer to the current subtree."
  6881. (interactive)
  6882. (save-excursion
  6883. (save-match-data
  6884. (org-with-limited-levels
  6885. (narrow-to-region
  6886. (progn (org-back-to-heading t) (point))
  6887. (progn (org-end-of-subtree t t)
  6888. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6889. (point)))))))
  6890. (defun org-toggle-narrow-to-subtree ()
  6891. "Narrow to the subtree at point or widen a narrowed buffer."
  6892. (interactive)
  6893. (if (buffer-narrowed-p)
  6894. (widen)
  6895. (org-narrow-to-subtree)))
  6896. (defun org-narrow-to-block ()
  6897. "Narrow buffer to the current block."
  6898. (interactive)
  6899. (let* ((case-fold-search t)
  6900. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6901. "^[ \t]*#\\+end_.*")))
  6902. (if blockp
  6903. (narrow-to-region (car blockp) (cdr blockp))
  6904. (user-error "Not in a block"))))
  6905. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6906. "Clone the task (subtree) at point N times.
  6907. The clones will be inserted as siblings.
  6908. In interactive use, the user will be prompted for the number of
  6909. clones to be produced. If the entry has a timestamp, the user
  6910. will also be prompted for a time shift, which may be a repeater
  6911. as used in time stamps, for example `+3d'. To disable this,
  6912. you can call the function with a universal prefix argument.
  6913. When a valid repeater is given and the entry contains any time
  6914. stamps, the clones will become a sequence in time, with time
  6915. stamps in the subtree shifted for each clone produced. If SHIFT
  6916. is nil or the empty string, time stamps will be left alone. The
  6917. ID property of the original subtree is removed.
  6918. In each clone, all the CLOCK entries will be removed. This
  6919. prevents Org from considering that the clocked times overlap.
  6920. If the original subtree did contain time stamps with a repeater,
  6921. the following will happen:
  6922. - the repeater will be removed in each clone
  6923. - an additional clone will be produced, with the current, unshifted
  6924. date(s) in the entry.
  6925. - the original entry will be placed *after* all the clones, with
  6926. repeater intact.
  6927. - the start days in the repeater in the original entry will be shifted
  6928. to past the last clone.
  6929. In this way you can spell out a number of instances of a repeating task,
  6930. and still retain the repeater to cover future instances of the task.
  6931. As described above, N+1 clones are produced when the original
  6932. subtree has a repeater. Setting N to 0, then, can be used to
  6933. remove the repeater from a subtree and create a shifted clone
  6934. with the original repeater."
  6935. (interactive "nNumber of clones to produce: ")
  6936. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6937. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6938. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6939. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6940. (shift
  6941. (or shift
  6942. (if (and (not (equal current-prefix-arg '(4)))
  6943. (save-excursion
  6944. (goto-char beg)
  6945. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6946. (read-from-minibuffer
  6947. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6948. ""))) ;No time shift
  6949. (doshift
  6950. (and (org-string-nw-p shift)
  6951. (or (string-match "\\`[ \t]*\\([\\+\\-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6952. shift)
  6953. (user-error "Invalid shift specification %s" shift)))))
  6954. (goto-char end-of-tree)
  6955. (unless (bolp) (insert "\n"))
  6956. (let* ((end (point))
  6957. (template (buffer-substring beg end))
  6958. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6959. (shift-what (pcase (and doshift (match-string 2 shift))
  6960. (`nil nil)
  6961. ("d" 'day)
  6962. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6963. ("m" 'month)
  6964. ("y" 'year)
  6965. (_ (error "Unsupported time unit"))))
  6966. (nmin 1)
  6967. (nmax n)
  6968. (n-no-remove -1)
  6969. (idprop (org-entry-get nil "ID")))
  6970. (when (and doshift
  6971. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6972. template))
  6973. (delete-region beg end)
  6974. (setq end beg)
  6975. (setq nmin 0)
  6976. (setq nmax (1+ nmax))
  6977. (setq n-no-remove nmax))
  6978. (goto-char end)
  6979. (cl-loop for n from nmin to nmax do
  6980. (insert
  6981. ;; Prepare clone.
  6982. (with-temp-buffer
  6983. (insert template)
  6984. (org-mode)
  6985. (goto-char (point-min))
  6986. (org-show-subtree)
  6987. (and idprop (if org-clone-delete-id
  6988. (org-entry-delete nil "ID")
  6989. (org-id-get-create t)))
  6990. (unless (= n 0)
  6991. (while (re-search-forward org-clock-line-re nil t)
  6992. (delete-region (line-beginning-position)
  6993. (line-beginning-position 2)))
  6994. (goto-char (point-min))
  6995. (while (re-search-forward org-drawer-regexp nil t)
  6996. (org-remove-empty-drawer-at (point))))
  6997. (goto-char (point-min))
  6998. (when doshift
  6999. (while (re-search-forward org-ts-regexp-both nil t)
  7000. (org-timestamp-change (* n shift-n) shift-what))
  7001. (unless (= n n-no-remove)
  7002. (goto-char (point-min))
  7003. (while (re-search-forward org-ts-regexp nil t)
  7004. (save-excursion
  7005. (goto-char (match-beginning 0))
  7006. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7007. (delete-region (match-beginning 1) (match-end 1)))))))
  7008. (buffer-string)))))
  7009. (goto-char beg)))
  7010. ;;; Outline Sorting
  7011. (defun org-sort (&optional with-case)
  7012. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7013. Optional argument WITH-CASE means sort case-sensitively."
  7014. (interactive "P")
  7015. (org-call-with-arg
  7016. (cond ((org-at-table-p) #'org-table-sort-lines)
  7017. ((org-at-item-p) #'org-sort-list)
  7018. (t #'org-sort-entries))
  7019. with-case))
  7020. (defun org-sort-remove-invisible (s)
  7021. "Remove invisible part of links and emphasis markers from string S."
  7022. (remove-text-properties 0 (length s) org-rm-props s)
  7023. (replace-regexp-in-string
  7024. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7025. (replace-regexp-in-string
  7026. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7027. (org-link-display-format s)
  7028. t t) t t))
  7029. (defvar org-priority-regexp) ; defined later in the file
  7030. (defvar org-after-sorting-entries-or-items-hook nil
  7031. "Hook that is run after a bunch of entries or items have been sorted.
  7032. When children are sorted, the cursor is in the parent line when this
  7033. hook gets called. When a region or a plain list is sorted, the cursor
  7034. will be in the first entry of the sorted region/list.")
  7035. (defun org-sort-entries
  7036. (&optional with-case sorting-type getkey-func compare-func property
  7037. interactive?)
  7038. "Sort entries on a certain level of an outline tree.
  7039. If there is an active region, the entries in the region are sorted.
  7040. Else, if the cursor is before the first entry, sort the top-level items.
  7041. Else, the children of the entry at point are sorted.
  7042. Sorting can be alphabetically, numerically, by date/time as given by
  7043. a time stamp, by a property, by priority order, or by a custom function.
  7044. The command prompts for the sorting type unless it has been given to the
  7045. function through the SORTING-TYPE argument, which needs to be a character,
  7046. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7047. the precise meaning of each character:
  7048. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7049. c By creation time, which is assumed to be the first inactive time stamp
  7050. at the beginning of a line.
  7051. d By deadline date/time.
  7052. k By clocking time.
  7053. n Numerically, by converting the beginning of the entry/item to a number.
  7054. o By order of TODO keywords.
  7055. p By priority according to the cookie.
  7056. r By the value of a property.
  7057. s By scheduled date/time.
  7058. t By date/time, either the first active time stamp in the entry, or, if
  7059. none exist, by the first inactive one.
  7060. Capital letters will reverse the sort order.
  7061. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7062. called with point at the beginning of the record. It must return a
  7063. value that is compatible with COMPARE-FUNC, the function used to
  7064. compare entries.
  7065. Comparing entries ignores case by default. However, with an optional argument
  7066. WITH-CASE, the sorting considers case as well.
  7067. Sorting is done against the visible part of the headlines, it ignores hidden
  7068. links.
  7069. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7070. A non-nil value for INTERACTIVE? is used to signal that this
  7071. function is being called interactively."
  7072. (interactive (list current-prefix-arg nil nil nil nil t))
  7073. (let ((case-func (if with-case 'identity 'downcase))
  7074. start beg end stars re re2
  7075. txt what tmp)
  7076. ;; Find beginning and end of region to sort
  7077. (cond
  7078. ((org-region-active-p)
  7079. ;; we will sort the region
  7080. (setq end (region-end)
  7081. what "region")
  7082. (goto-char (region-beginning))
  7083. (unless (org-at-heading-p) (outline-next-heading))
  7084. (setq start (point)))
  7085. ((or (org-at-heading-p)
  7086. (ignore-errors (progn (org-back-to-heading) t)))
  7087. ;; we will sort the children of the current headline
  7088. (org-back-to-heading)
  7089. (setq start (point)
  7090. end (progn (org-end-of-subtree t t)
  7091. (or (bolp) (insert "\n"))
  7092. (when (>= (org-back-over-empty-lines) 1)
  7093. (forward-line 1))
  7094. (point))
  7095. what "children")
  7096. (goto-char start)
  7097. (outline-show-subtree)
  7098. (outline-next-heading))
  7099. (t
  7100. ;; we will sort the top-level entries in this file
  7101. (goto-char (point-min))
  7102. (or (org-at-heading-p) (outline-next-heading))
  7103. (setq start (point))
  7104. (goto-char (point-max))
  7105. (beginning-of-line 1)
  7106. (when (looking-at ".*?\\S-")
  7107. ;; File ends in a non-white line
  7108. (end-of-line 1)
  7109. (insert "\n"))
  7110. (setq end (point-max))
  7111. (setq what "top-level")
  7112. (goto-char start)
  7113. (org-show-all '(headings blocks))))
  7114. (setq beg (point))
  7115. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7116. (looking-at "\\(\\*+\\)")
  7117. (setq stars (match-string 1)
  7118. re (concat "^" (regexp-quote stars) " +")
  7119. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7120. txt (buffer-substring beg end))
  7121. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7122. (when (and (not (equal stars "*")) (string-match re2 txt))
  7123. (user-error "Region to sort contains a level above the first entry"))
  7124. (unless sorting-type
  7125. (message
  7126. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7127. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7128. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7129. what)
  7130. (setq sorting-type (read-char-exclusive)))
  7131. (unless getkey-func
  7132. (and (= (downcase sorting-type) ?f)
  7133. (setq getkey-func
  7134. (or (and interactive?
  7135. (org-read-function
  7136. "Function for extracting keys: "))
  7137. (error "Missing key extractor")))))
  7138. (and (= (downcase sorting-type) ?r)
  7139. (not property)
  7140. (setq property
  7141. (completing-read "Property: "
  7142. (mapcar #'list (org-buffer-property-keys t))
  7143. nil t)))
  7144. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7145. (message "Sorting entries...")
  7146. (save-restriction
  7147. (narrow-to-region start end)
  7148. (let ((restore-clock?
  7149. ;; The clock marker is lost when using `sort-subr'; mark
  7150. ;; the clock with temporary `:org-clock-marker-backup'
  7151. ;; text property.
  7152. (when (and (eq (org-clock-is-active) (current-buffer))
  7153. (<= start (marker-position org-clock-marker))
  7154. (>= end (marker-position org-clock-marker)))
  7155. (with-silent-modifications
  7156. (put-text-property (1- org-clock-marker) org-clock-marker
  7157. :org-clock-marker-backup t))
  7158. t))
  7159. (dcst (downcase sorting-type))
  7160. (case-fold-search nil)
  7161. (now (current-time)))
  7162. (org-preserve-local-variables
  7163. (sort-subr
  7164. (/= dcst sorting-type)
  7165. ;; This function moves to the beginning character of the
  7166. ;; "record" to be sorted.
  7167. (lambda nil
  7168. (if (re-search-forward re nil t)
  7169. (goto-char (match-beginning 0))
  7170. (goto-char (point-max))))
  7171. ;; This function moves to the last character of the "record" being
  7172. ;; sorted.
  7173. (lambda nil
  7174. (save-match-data
  7175. (condition-case nil
  7176. (outline-forward-same-level 1)
  7177. (error
  7178. (goto-char (point-max))))))
  7179. ;; This function returns the value that gets sorted against.
  7180. (lambda ()
  7181. (cond
  7182. ((= dcst ?n)
  7183. (string-to-number
  7184. (org-sort-remove-invisible (org-get-heading t t t t))))
  7185. ((= dcst ?a)
  7186. (funcall case-func
  7187. (org-sort-remove-invisible (org-get-heading t t t t))))
  7188. ((= dcst ?k)
  7189. (or (get-text-property (point) :org-clock-minutes) 0))
  7190. ((= dcst ?t)
  7191. (let ((end (save-excursion (outline-next-heading) (point))))
  7192. (if (or (re-search-forward org-ts-regexp end t)
  7193. (re-search-forward org-ts-regexp-both end t))
  7194. (org-time-string-to-seconds (match-string 0))
  7195. (float-time now))))
  7196. ((= dcst ?c)
  7197. (let ((end (save-excursion (outline-next-heading) (point))))
  7198. (if (re-search-forward
  7199. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7200. end t)
  7201. (org-time-string-to-seconds (match-string 0))
  7202. (float-time now))))
  7203. ((= dcst ?s)
  7204. (let ((end (save-excursion (outline-next-heading) (point))))
  7205. (if (re-search-forward org-scheduled-time-regexp end t)
  7206. (org-time-string-to-seconds (match-string 1))
  7207. (float-time now))))
  7208. ((= dcst ?d)
  7209. (let ((end (save-excursion (outline-next-heading) (point))))
  7210. (if (re-search-forward org-deadline-time-regexp end t)
  7211. (org-time-string-to-seconds (match-string 1))
  7212. (float-time now))))
  7213. ((= dcst ?p)
  7214. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7215. (string-to-char (match-string 2))
  7216. org-default-priority))
  7217. ((= dcst ?r)
  7218. (or (org-entry-get nil property) ""))
  7219. ((= dcst ?o)
  7220. (when (looking-at org-complex-heading-regexp)
  7221. (let* ((m (match-string 2))
  7222. (s (if (member m org-done-keywords) '- '+)))
  7223. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7224. ((= dcst ?f)
  7225. (if getkey-func
  7226. (progn
  7227. (setq tmp (funcall getkey-func))
  7228. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7229. tmp)
  7230. (error "Invalid key function `%s'" getkey-func)))
  7231. (t (error "Invalid sorting type `%c'" sorting-type))))
  7232. nil
  7233. (cond
  7234. ((= dcst ?a) 'org-string-collate-lessp)
  7235. ((= dcst ?f)
  7236. (or compare-func
  7237. (and interactive?
  7238. (org-read-function
  7239. (concat "Function for comparing keys "
  7240. "(empty for default `sort-subr' predicate): ")
  7241. 'allow-empty))))
  7242. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7243. (org-cycle-hide-drawers 'all)
  7244. (when restore-clock?
  7245. (move-marker org-clock-marker
  7246. (1+ (next-single-property-change
  7247. start :org-clock-marker-backup)))
  7248. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7249. '(:org-clock-marker-backup t)))))
  7250. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7251. (message "Sorting entries...done")))
  7252. (defun org-contextualize-keys (alist contexts)
  7253. "Return valid elements in ALIST depending on CONTEXTS.
  7254. `org-agenda-custom-commands' or `org-capture-templates' are the
  7255. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7256. or `org-capture-templates-contexts' are the associated contexts
  7257. definitions."
  7258. (let ((contexts
  7259. ;; normalize contexts
  7260. (mapcar
  7261. (lambda(c) (cond ((listp (cadr c))
  7262. (list (car c) (car c) (nth 1 c)))
  7263. ((string= "" (cadr c))
  7264. (list (car c) (car c) (nth 2 c)))
  7265. (t c)))
  7266. contexts))
  7267. (a alist) r s)
  7268. ;; loop over all commands or templates
  7269. (dolist (c a)
  7270. (let (vrules repl)
  7271. (cond
  7272. ((not (assoc (car c) contexts))
  7273. (push c r))
  7274. ((and (assoc (car c) contexts)
  7275. (setq vrules (org-contextualize-validate-key
  7276. (car c) contexts)))
  7277. (mapc (lambda (vr)
  7278. (unless (equal (car vr) (cadr vr))
  7279. (setq repl vr)))
  7280. vrules)
  7281. (if (not repl) (push c r)
  7282. (push (cadr repl) s)
  7283. (push
  7284. (cons (car c)
  7285. (cdr (or (assoc (cadr repl) alist)
  7286. (error "Undefined key `%s' as contextual replacement for `%s'"
  7287. (cadr repl) (car c)))))
  7288. r))))))
  7289. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7290. (delq
  7291. nil
  7292. (delete-dups
  7293. (mapcar (lambda (x)
  7294. (let ((tpl (car x)))
  7295. (unless (delq
  7296. nil
  7297. (mapcar (lambda (y)
  7298. (equal y tpl))
  7299. s))
  7300. x)))
  7301. (reverse r))))))
  7302. (defun org-contextualize-validate-key (key contexts)
  7303. "Check CONTEXTS for agenda or capture KEY."
  7304. (let (res)
  7305. (dolist (r contexts)
  7306. (dolist (rr (car (last r)))
  7307. (when
  7308. (and (equal key (car r))
  7309. (if (functionp rr) (funcall rr)
  7310. (or (and (eq (car rr) 'in-file)
  7311. (buffer-file-name)
  7312. (string-match (cdr rr) (buffer-file-name)))
  7313. (and (eq (car rr) 'in-mode)
  7314. (string-match (cdr rr) (symbol-name major-mode)))
  7315. (and (eq (car rr) 'in-buffer)
  7316. (string-match (cdr rr) (buffer-name)))
  7317. (when (and (eq (car rr) 'not-in-file)
  7318. (buffer-file-name))
  7319. (not (string-match (cdr rr) (buffer-file-name))))
  7320. (when (eq (car rr) 'not-in-mode)
  7321. (not (string-match (cdr rr) (symbol-name major-mode))))
  7322. (when (eq (car rr) 'not-in-buffer)
  7323. (not (string-match (cdr rr) (buffer-name)))))))
  7324. (push r res))))
  7325. (delete-dups (delq nil res))))
  7326. ;; Defined to provide a value for defcustom, since there is no
  7327. ;; string-collate-greaterp in Emacs.
  7328. (defun org-string-collate-greaterp (s1 s2)
  7329. "Return non-nil if S1 is greater than S2 in collation order."
  7330. (not (org-string-collate-lessp s1 s2)))
  7331. ;;;###autoload
  7332. (defun org-run-like-in-org-mode (cmd)
  7333. "Run a command, pretending that the current buffer is in Org mode.
  7334. This will temporarily bind local variables that are typically bound in
  7335. Org mode to the values they have in Org mode, and then interactively
  7336. call CMD."
  7337. (org-load-modules-maybe)
  7338. (let (binds)
  7339. (dolist (var (org-get-local-variables))
  7340. (when (or (not (boundp (car var)))
  7341. (eq (symbol-value (car var))
  7342. (default-value (car var))))
  7343. (push (list (car var) `(quote ,(cadr var))) binds)))
  7344. (eval `(let ,binds
  7345. (call-interactively (quote ,cmd))))))
  7346. (defun org-get-category (&optional pos force-refresh)
  7347. "Get the category applying to position POS."
  7348. (save-match-data
  7349. (when force-refresh (org-refresh-category-properties))
  7350. (let ((pos (or pos (point))))
  7351. (or (get-text-property pos 'org-category)
  7352. (progn (org-refresh-category-properties)
  7353. (get-text-property pos 'org-category))))))
  7354. ;;; Refresh properties
  7355. (defun org-refresh-properties (dprop tprop)
  7356. "Refresh buffer text properties.
  7357. DPROP is the drawer property and TPROP is either the
  7358. corresponding text property to set, or an alist with each element
  7359. being a text property (as a symbol) and a function to apply to
  7360. the value of the drawer property."
  7361. (let* ((case-fold-search t)
  7362. (inhibit-read-only t)
  7363. (inherit? (org-property-inherit-p dprop))
  7364. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7365. (global (and inherit? (org--property-global-value dprop nil))))
  7366. (with-silent-modifications
  7367. (org-with-point-at 1
  7368. ;; Set global values (e.g., values defined through
  7369. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7370. (when global (put-text-property (point-min) (point-max) tprop global))
  7371. ;; Set local values.
  7372. (while (re-search-forward property-re nil t)
  7373. (when (org-at-property-p)
  7374. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7375. (outline-next-heading))))))
  7376. (defun org-refresh-property (tprop p &optional inherit)
  7377. "Refresh the buffer text property TPROP from the drawer property P.
  7378. The refresh happens only for the current headline, or the whole
  7379. sub-tree if optional argument INHERIT is non-nil."
  7380. (unless (org-before-first-heading-p)
  7381. (save-excursion
  7382. (org-back-to-heading t)
  7383. (let ((start (point))
  7384. (end (save-excursion
  7385. (if inherit (org-end-of-subtree t t)
  7386. (or (outline-next-heading) (point-max))))))
  7387. (if (symbolp tprop)
  7388. ;; TPROP is a text property symbol.
  7389. (put-text-property start end tprop p)
  7390. ;; TPROP is an alist with (property . function) elements.
  7391. (pcase-dolist (`(,prop . ,f) tprop)
  7392. (put-text-property start end prop (funcall f p))))))))
  7393. (defun org-refresh-category-properties ()
  7394. "Refresh category text properties in the buffer."
  7395. (let ((case-fold-search t)
  7396. (inhibit-read-only t)
  7397. (default-category
  7398. (cond ((null org-category)
  7399. (if buffer-file-name
  7400. (file-name-sans-extension
  7401. (file-name-nondirectory buffer-file-name))
  7402. "???"))
  7403. ((symbolp org-category) (symbol-name org-category))
  7404. (t org-category))))
  7405. (with-silent-modifications
  7406. (org-with-wide-buffer
  7407. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7408. ;; This is the default category for the buffer. If none is
  7409. ;; found, fall-back to `org-category' or buffer file name.
  7410. (put-text-property
  7411. (point-min) (point-max)
  7412. 'org-category
  7413. (catch 'buffer-category
  7414. (goto-char (point-max))
  7415. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7416. (let ((element (org-element-at-point)))
  7417. (when (eq (org-element-type element) 'keyword)
  7418. (throw 'buffer-category
  7419. (org-element-property :value element)))))
  7420. default-category))
  7421. ;; Set sub-tree specific categories.
  7422. (goto-char (point-min))
  7423. (let ((regexp (org-re-property "CATEGORY")))
  7424. (while (re-search-forward regexp nil t)
  7425. (let ((value (match-string-no-properties 3)))
  7426. (when (org-at-property-p)
  7427. (put-text-property
  7428. (save-excursion (org-back-to-heading t) (point))
  7429. (save-excursion (org-end-of-subtree t t) (point))
  7430. 'org-category
  7431. value)))))))))
  7432. (defun org-refresh-stats-properties ()
  7433. "Refresh stats text properties in the buffer."
  7434. (with-silent-modifications
  7435. (org-with-point-at 1
  7436. (let ((regexp (concat org-outline-regexp-bol
  7437. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7438. (while (re-search-forward regexp nil t)
  7439. (let* ((numerator (string-to-number (match-string 1)))
  7440. (denominator (and (match-end 2)
  7441. (string-to-number (match-string 2))))
  7442. (stats (cond ((not denominator) numerator) ;percent
  7443. ((= denominator 0) 0)
  7444. (t (/ (* numerator 100) denominator)))))
  7445. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7446. 'org-stats stats)))))))
  7447. (defun org-refresh-effort-properties ()
  7448. "Refresh effort properties"
  7449. (org-refresh-properties
  7450. org-effort-property
  7451. '((effort . identity)
  7452. (effort-minutes . org-duration-to-minutes))))
  7453. (defun org-find-file-at-mouse (ev)
  7454. "Open file link or URL at mouse."
  7455. (interactive "e")
  7456. (mouse-set-point ev)
  7457. (org-open-at-point 'in-emacs))
  7458. (defun org-open-at-mouse (ev)
  7459. "Open file link or URL at mouse.
  7460. See the docstring of `org-open-file' for details."
  7461. (interactive "e")
  7462. (mouse-set-point ev)
  7463. (when (eq major-mode 'org-agenda-mode)
  7464. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7465. (org-open-at-point))
  7466. (defvar org-window-config-before-follow-link nil
  7467. "The window configuration before following a link.
  7468. This is saved in case the need arises to restore it.")
  7469. (defun org--file-default-apps ()
  7470. "Return the default applications for this operating system."
  7471. (pcase system-type
  7472. (`darwin org-file-apps-macos)
  7473. (`windows-nt org-file-apps-windowsnt)
  7474. (_ org-file-apps-gnu)))
  7475. (defun org--file-apps-entry-dlink-p (entry)
  7476. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7477. It assumes that is the case when the entry uses a regular
  7478. expression which has at least one grouping construct and the
  7479. action is either a Lisp form or a command string containing
  7480. \"%1\", i.e., using at least one subexpression match as
  7481. a parameter."
  7482. (pcase entry
  7483. (`(,selector . ,action)
  7484. (and (stringp selector)
  7485. (> (regexp-opt-depth selector) 0)
  7486. (or (and (stringp action)
  7487. (string-match "%[0-9]" action))
  7488. (consp action))))
  7489. (_ nil)))
  7490. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7491. "Convert extensions to regular expressions in the cars of LIST.
  7492. Also, weed out any non-string entries, because the return value
  7493. is used only for regexp matching.
  7494. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7495. point to the symbol `emacs', indicating that the file should be
  7496. opened in Emacs."
  7497. (append
  7498. (delq nil
  7499. (mapcar (lambda (x)
  7500. (unless (not (stringp (car x)))
  7501. (if (string-match "\\W" (car x))
  7502. x
  7503. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7504. list))
  7505. (when add-auto-mode
  7506. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7507. ;;;###autoload
  7508. (defun org-open-file (path &optional in-emacs line search)
  7509. "Open the file at PATH.
  7510. First, this expands any special file name abbreviations. Then the
  7511. configuration variable `org-file-apps' is checked if it contains an
  7512. entry for this file type, and if yes, the corresponding command is launched.
  7513. If no application is found, Emacs simply visits the file.
  7514. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7515. With a double \\[universal-argument] \\[universal-argument] \
  7516. prefix arg, Org tries to avoid opening in Emacs
  7517. and to use an external application to visit the file.
  7518. Optional LINE specifies a line to go to, optional SEARCH a string
  7519. to search for. If LINE or SEARCH is given, the file will be
  7520. opened in Emacs, unless an entry from `org-file-apps' that makes
  7521. use of groups in a regexp matches.
  7522. If you want to change the way frames are used when following a
  7523. link, please customize `org-link-frame-setup'.
  7524. If the file does not exist, throw an error."
  7525. (let* ((file (if (equal path "") buffer-file-name
  7526. (substitute-in-file-name (expand-file-name path))))
  7527. (file-apps (append org-file-apps (org--file-default-apps)))
  7528. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7529. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7530. file-apps))
  7531. (remp (and (assq 'remote apps) (file-remote-p file)))
  7532. (dirp (unless remp (file-directory-p file)))
  7533. (file (if (and dirp org-open-directory-means-index-dot-org)
  7534. (concat (file-name-as-directory file) "index.org")
  7535. file))
  7536. (a-m-a-p (assq 'auto-mode apps))
  7537. (dfile (downcase file))
  7538. ;; Reconstruct the original link from the PATH, LINE and
  7539. ;; SEARCH args.
  7540. (link (cond (line (concat file "::" (number-to-string line)))
  7541. (search (concat file "::" search))
  7542. (t file)))
  7543. (dlink (downcase link))
  7544. (ext
  7545. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7546. (match-string 1 dfile)))
  7547. (save-position-maybe
  7548. (let ((old-buffer (current-buffer))
  7549. (old-pos (point))
  7550. (old-mode major-mode))
  7551. (lambda ()
  7552. (and (derived-mode-p 'org-mode)
  7553. (eq old-mode 'org-mode)
  7554. (or (not (eq old-buffer (current-buffer)))
  7555. (not (eq old-pos (point))))
  7556. (org-mark-ring-push old-pos old-buffer)))))
  7557. cmd link-match-data)
  7558. (cond
  7559. ((member in-emacs '((16) system))
  7560. (setq cmd (cdr (assq 'system apps))))
  7561. (in-emacs (setq cmd 'emacs))
  7562. (t
  7563. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7564. (and dirp (cdr (assq 'directory apps)))
  7565. ;; First, try matching against apps-dlink if we
  7566. ;; get a match here, store the match data for
  7567. ;; later.
  7568. (let ((match (assoc-default dlink apps-dlink
  7569. 'string-match)))
  7570. (if match
  7571. (progn (setq link-match-data (match-data))
  7572. match)
  7573. (progn (setq in-emacs (or in-emacs line search))
  7574. nil))) ; if we have no match in apps-dlink,
  7575. ; always open the file in emacs if line or search
  7576. ; is given (for backwards compatibility)
  7577. (assoc-default dfile
  7578. (org--file-apps-regexp-alist apps a-m-a-p)
  7579. 'string-match)
  7580. (cdr (assoc ext apps))
  7581. (cdr (assq t apps))))))
  7582. (when (eq cmd 'system)
  7583. (setq cmd (cdr (assq 'system apps))))
  7584. (when (eq cmd 'default)
  7585. (setq cmd (cdr (assoc t apps))))
  7586. (when (eq cmd 'mailcap)
  7587. (require 'mailcap)
  7588. (mailcap-parse-mailcaps)
  7589. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7590. (command (mailcap-mime-info mime-type)))
  7591. (if (stringp command)
  7592. (setq cmd command)
  7593. (setq cmd 'emacs))))
  7594. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7595. (not (file-exists-p file))
  7596. (not org-open-non-existing-files))
  7597. (user-error "No such file: %s" file))
  7598. (cond
  7599. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7600. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7601. (while (string-match "['\"]%s['\"]" cmd)
  7602. (setq cmd (replace-match "%s" t t cmd)))
  7603. (setq cmd (replace-regexp-in-string
  7604. "%s"
  7605. (shell-quote-argument (convert-standard-filename file))
  7606. cmd
  7607. nil t))
  7608. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7609. (save-match-data
  7610. (let ((match-index 1)
  7611. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7612. (set-match-data link-match-data)
  7613. (while (<= match-index number-of-groups)
  7614. (let ((regex (concat "%" (number-to-string match-index)))
  7615. (replace-with (match-string match-index dlink)))
  7616. (while (string-match regex cmd)
  7617. (setq cmd (replace-match replace-with t t cmd))))
  7618. (setq match-index (+ match-index 1)))))
  7619. (save-window-excursion
  7620. (message "Running %s...done" cmd)
  7621. (start-process-shell-command cmd nil cmd)
  7622. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7623. ((or (stringp cmd)
  7624. (eq cmd 'emacs))
  7625. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7626. (widen)
  7627. (cond (line (org-goto-line line)
  7628. (when (derived-mode-p 'org-mode) (org-reveal)))
  7629. (search (condition-case err
  7630. (org-link-search search)
  7631. ;; Save position before error-ing out so user
  7632. ;; can easily move back to the original buffer.
  7633. (error (funcall save-position-maybe)
  7634. (error (nth 1 err)))))))
  7635. ((functionp cmd)
  7636. (save-match-data
  7637. (set-match-data link-match-data)
  7638. (condition-case nil
  7639. (funcall cmd file link)
  7640. ;; FIXME: Remove this check when most default installations
  7641. ;; of Emacs have at least Org 9.0.
  7642. ((debug wrong-number-of-arguments wrong-type-argument
  7643. invalid-function)
  7644. (user-error "Please see Org News for version 9.0 about \
  7645. `org-file-apps'--Lisp error: %S" cmd)))))
  7646. ((consp cmd)
  7647. ;; FIXME: Remove this check when most default installations of
  7648. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7649. ;; fall back to `org-link-frame-setup' for an old usage of
  7650. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7651. (user-error "Please see Org News for version 9.0 about \
  7652. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7653. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7654. (funcall save-position-maybe)))
  7655. ;;;###autoload
  7656. (defun org-open-at-point-global ()
  7657. "Follow a link or a time-stamp like Org mode does.
  7658. Also follow links and emails as seen by `thing-at-point'.
  7659. This command can be called in any mode to follow an external
  7660. link or a time-stamp that has Org mode syntax. Its behavior
  7661. is undefined when called on internal links like fuzzy links.
  7662. Raise a user error when there is nothing to follow."
  7663. (interactive)
  7664. (let ((tap-url (thing-at-point 'url))
  7665. (tap-email (thing-at-point 'email)))
  7666. (cond ((org-in-regexp org-link-any-re)
  7667. (org-link-open-from-string (match-string-no-properties 0)))
  7668. ((or (org-in-regexp org-ts-regexp-both nil t)
  7669. (org-in-regexp org-tsr-regexp-both nil t))
  7670. (org-follow-timestamp-link))
  7671. (tap-url (org-link-open-from-string tap-url))
  7672. (tap-email (org-link-open-from-string
  7673. (concat "mailto:" tap-email)))
  7674. (t (user-error "No link found")))))
  7675. (defvar org-open-at-point-functions nil
  7676. "Hook that is run when following a link at point.
  7677. Functions in this hook must return t if they identify and follow
  7678. a link at point. If they don't find anything interesting at point,
  7679. they must return nil.")
  7680. (defun org-open-at-point (&optional arg)
  7681. "Open link, timestamp, footnote or tags at point.
  7682. When point is on a link, follow it. Normally, files will be
  7683. opened by an appropriate application. If the optional prefix
  7684. argument ARG is non-nil, Emacs will visit the file. With
  7685. a double prefix argument, try to open outside of Emacs, in the
  7686. application the system uses for this file type.
  7687. When point is on a timestamp, open the agenda at the day
  7688. specified.
  7689. When point is a footnote definition, move to the first reference
  7690. found. If it is on a reference, move to the associated
  7691. definition.
  7692. When point is on a headline, display a list of every link in the
  7693. entry, so it is possible to pick one, or all, of them. If point
  7694. is on a tag, call `org-tags-view' instead.
  7695. On top of syntactically correct links, this function also tries
  7696. to open links and time-stamps in comments, node properties, and
  7697. keywords if point is on something looking like a timestamp or
  7698. a link."
  7699. (interactive "P")
  7700. (org-load-modules-maybe)
  7701. (setq org-window-config-before-follow-link (current-window-configuration))
  7702. (org-remove-occur-highlights nil nil t)
  7703. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7704. (let* ((context
  7705. ;; Only consider supported types, even if they are not the
  7706. ;; closest one.
  7707. (org-element-lineage
  7708. (org-element-context)
  7709. '(clock comment comment-block footnote-definition
  7710. footnote-reference headline inline-src-block inlinetask
  7711. keyword link node-property planning src-block timestamp)
  7712. t))
  7713. (type (org-element-type context))
  7714. (value (org-element-property :value context)))
  7715. (cond
  7716. ((not type) (user-error "No link found"))
  7717. ;; No valid link at point. For convenience, look if something
  7718. ;; looks like a link under point in some specific places.
  7719. ((memq type '(comment comment-block node-property keyword))
  7720. (call-interactively #'org-open-at-point-global))
  7721. ;; On a headline or an inlinetask, but not on a timestamp,
  7722. ;; a link, a footnote reference.
  7723. ((memq type '(headline inlinetask))
  7724. (org-match-line org-complex-heading-regexp)
  7725. (if (and (match-beginning 5)
  7726. (>= (point) (match-beginning 5))
  7727. (< (point) (match-end 5)))
  7728. ;; On tags.
  7729. (org-tags-view
  7730. arg
  7731. (save-excursion
  7732. (let* ((beg (match-beginning 5))
  7733. (end (match-end 5))
  7734. (beg-tag (or (search-backward ":" beg 'at-limit) (point)))
  7735. (end-tag (search-forward ":" end nil 2)))
  7736. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7737. ;; Not on tags.
  7738. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7739. (`(nil . ,_)
  7740. (require 'org-attach)
  7741. (message "Opening attachment-dir")
  7742. (if (equal arg '(4))
  7743. (org-attach-reveal-in-emacs)
  7744. (org-attach-reveal)))
  7745. (`(,links . ,links-end)
  7746. (dolist (link (if (stringp links) (list links) links))
  7747. (search-forward link nil links-end)
  7748. (goto-char (match-beginning 0))
  7749. (org-open-at-point arg))))))
  7750. ;; On a footnote reference or at definition's label.
  7751. ((or (eq type 'footnote-reference)
  7752. (and (eq type 'footnote-definition)
  7753. (save-excursion
  7754. ;; Do not validate action when point is on the
  7755. ;; spaces right after the footnote label, in order
  7756. ;; to be on par with behavior on links.
  7757. (skip-chars-forward " \t")
  7758. (let ((begin
  7759. (org-element-property :contents-begin context)))
  7760. (if begin (< (point) begin)
  7761. (= (org-element-property :post-affiliated context)
  7762. (line-beginning-position)))))))
  7763. (org-footnote-action))
  7764. ;; On a planning line. Check if we are really on a timestamp.
  7765. ((and (eq type 'planning)
  7766. (org-in-regexp org-ts-regexp-both nil t))
  7767. (org-follow-timestamp-link))
  7768. ;; On a clock line, make sure point is on the timestamp
  7769. ;; before opening it.
  7770. ((and (eq type 'clock)
  7771. value
  7772. (>= (point) (org-element-property :begin value))
  7773. (<= (point) (org-element-property :end value)))
  7774. (org-follow-timestamp-link))
  7775. ((eq type 'src-block) (org-babel-open-src-block-result))
  7776. ;; Do nothing on white spaces after an object.
  7777. ((>= (point)
  7778. (save-excursion
  7779. (goto-char (org-element-property :end context))
  7780. (skip-chars-backward " \t")
  7781. (point)))
  7782. (user-error "No link found"))
  7783. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7784. ((eq type 'timestamp) (org-follow-timestamp-link))
  7785. ((eq type 'link) (org-link-open context arg))
  7786. (t (user-error "No link found")))))
  7787. (run-hook-with-args 'org-follow-link-hook))
  7788. ;;;###autoload
  7789. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7790. "Offer links in the current entry and return the selected link.
  7791. If there is only one link, return it.
  7792. If NTH is an integer, return the NTH link found.
  7793. If ZERO is a string, check also this string for a link, and if
  7794. there is one, return it."
  7795. (with-current-buffer buffer
  7796. (org-with-wide-buffer
  7797. (goto-char marker)
  7798. (let ((cnt ?0)
  7799. have-zero end links link c)
  7800. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7801. (push (match-string 0 zero) links)
  7802. (setq cnt (1- cnt) have-zero t))
  7803. (save-excursion
  7804. (org-back-to-heading t)
  7805. (setq end (save-excursion (outline-next-heading) (point)))
  7806. (while (re-search-forward org-link-any-re end t)
  7807. (push (match-string 0) links))
  7808. (setq links (org-uniquify (reverse links))))
  7809. (cond
  7810. ((null links)
  7811. (message "No links"))
  7812. ((equal (length links) 1)
  7813. (setq link (car links)))
  7814. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7815. (setq link (nth (if have-zero nth (1- nth)) links)))
  7816. (t ; we have to select a link
  7817. (save-excursion
  7818. (save-window-excursion
  7819. (delete-other-windows)
  7820. (with-output-to-temp-buffer "*Select Link*"
  7821. (dolist (l links)
  7822. (cond
  7823. ((not (string-match org-link-bracket-re l))
  7824. (princ (format "[%c] %s\n" (cl-incf cnt)
  7825. (org-unbracket-string "<" ">" l))))
  7826. ((match-end 2)
  7827. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7828. (match-string 2 l) (match-string 1 l))))
  7829. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7830. (match-string 1 l)))))))
  7831. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7832. (message "Select link to open, RET to open all:")
  7833. (setq c (read-char-exclusive))
  7834. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7835. (when (equal c ?q) (user-error "Abort"))
  7836. (if (equal c ?\C-m)
  7837. (setq link links)
  7838. (setq nth (- c ?0))
  7839. (when have-zero (setq nth (1+ nth)))
  7840. (unless (and (integerp nth) (>= (length links) nth))
  7841. (user-error "Invalid link selection"))
  7842. (setq link (nth (1- nth) links)))))
  7843. (cons link end)))))
  7844. ;;; File search
  7845. (defun org-do-occur (regexp &optional cleanup)
  7846. "Call the Emacs command `occur'.
  7847. If CLEANUP is non-nil, remove the printout of the regular expression
  7848. in the *Occur* buffer. This is useful if the regex is long and not useful
  7849. to read."
  7850. (occur regexp)
  7851. (when cleanup
  7852. (let ((cwin (selected-window)) win beg end)
  7853. (when (setq win (get-buffer-window "*Occur*"))
  7854. (select-window win))
  7855. (goto-char (point-min))
  7856. (when (re-search-forward "match[a-z]+" nil t)
  7857. (setq beg (match-end 0))
  7858. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7859. (setq end (1- (match-beginning 0)))))
  7860. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7861. (goto-char (point-min))
  7862. (select-window cwin))))
  7863. ;;; The Mark Ring
  7864. (defvar org-mark-ring nil
  7865. "Mark ring for positions before jumps in Org mode.")
  7866. (defvar org-mark-ring-last-goto nil
  7867. "Last position in the mark ring used to go back.")
  7868. ;; Fill and close the ring
  7869. (setq org-mark-ring nil)
  7870. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7871. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7872. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7873. org-mark-ring)
  7874. (defun org-mark-ring-push (&optional pos buffer)
  7875. "Put the current position into the mark ring and rotate it.
  7876. Also push position into the Emacs mark ring. If optional
  7877. argument POS and BUFFER are not nil, mark this location instead."
  7878. (interactive)
  7879. (let ((pos (or pos (point)))
  7880. (buffer (or buffer (current-buffer))))
  7881. (with-current-buffer buffer
  7882. (org-with-point-at pos (push-mark nil t)))
  7883. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7884. (move-marker (car org-mark-ring) pos buffer))
  7885. (message
  7886. (substitute-command-keys
  7887. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7888. (defun org-mark-ring-goto (&optional n)
  7889. "Jump to the previous position in the mark ring.
  7890. With prefix arg N, jump back that many stored positions. When
  7891. called several times in succession, walk through the entire ring.
  7892. Org mode commands jumping to a different position in the current file,
  7893. or to another Org file, automatically push the old position onto the ring."
  7894. (interactive "p")
  7895. (let (p m)
  7896. (if (eq last-command this-command)
  7897. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7898. (setq p org-mark-ring))
  7899. (setq org-mark-ring-last-goto p)
  7900. (setq m (car p))
  7901. (pop-to-buffer-same-window (marker-buffer m))
  7902. (goto-char m)
  7903. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7904. ;;; Following specific links
  7905. (defvar org-agenda-buffer-tmp-name)
  7906. (defvar org-agenda-start-on-weekday)
  7907. (defun org-follow-timestamp-link ()
  7908. "Open an agenda view for the time-stamp date/range at point."
  7909. (cond
  7910. ((org-at-date-range-p t)
  7911. (let ((org-agenda-start-on-weekday)
  7912. (t1 (match-string 1))
  7913. (t2 (match-string 2)) tt1 tt2)
  7914. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7915. tt2 (time-to-days (org-time-string-to-time t2)))
  7916. (let ((org-agenda-buffer-tmp-name
  7917. (format "*Org Agenda(a:%s)"
  7918. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7919. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7920. ((org-at-timestamp-p 'lax)
  7921. (let ((org-agenda-buffer-tmp-name
  7922. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7923. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7924. (substring (match-string 1) 0 10)))
  7925. 1)))
  7926. (t (error "This should not happen"))))
  7927. ;;; Following file links
  7928. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7929. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7930. (declare-function mailcap-mime-info
  7931. "mailcap" (string &optional request no-decode))
  7932. (defvar org-wait nil)
  7933. ;;;; Refiling
  7934. (defun org-get-org-file ()
  7935. "Read a filename, with default directory `org-directory'."
  7936. (let ((default (or org-default-notes-file remember-data-file)))
  7937. (read-file-name (format "File name [%s]: " default)
  7938. (file-name-as-directory org-directory)
  7939. default)))
  7940. (defun org-notes-order-reversed-p ()
  7941. "Check if the current file should receive notes in reversed order."
  7942. (cond
  7943. ((not org-reverse-note-order) nil)
  7944. ((eq t org-reverse-note-order) t)
  7945. ((not (listp org-reverse-note-order)) nil)
  7946. (t (catch 'exit
  7947. (dolist (entry org-reverse-note-order)
  7948. (when (string-match (car entry) buffer-file-name)
  7949. (throw 'exit (cdr entry))))))))
  7950. (defvar org-refile-target-table nil
  7951. "The list of refile targets, created by `org-refile'.")
  7952. (defvar org-agenda-new-buffers nil
  7953. "Buffers created to visit agenda files.")
  7954. (defvar org-refile-cache nil
  7955. "Cache for refile targets.")
  7956. (defvar org-refile-markers nil
  7957. "All the markers used for caching refile locations.")
  7958. (defun org-refile-marker (pos)
  7959. "Get a new refile marker, but only if caching is in use."
  7960. (if (not org-refile-use-cache)
  7961. pos
  7962. (let ((m (make-marker)))
  7963. (move-marker m pos)
  7964. (push m org-refile-markers)
  7965. m)))
  7966. (defun org-refile-cache-clear ()
  7967. "Clear the refile cache and disable all the markers."
  7968. (dolist (m org-refile-markers) (move-marker m nil))
  7969. (setq org-refile-markers nil)
  7970. (setq org-refile-cache nil)
  7971. (message "Refile cache has been cleared"))
  7972. (defun org-refile-cache-check-set (set)
  7973. "Check if all the markers in the cache still have live buffers."
  7974. (let (marker)
  7975. (catch 'exit
  7976. (while (and set (setq marker (nth 3 (pop set))))
  7977. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  7978. (when (and marker (null (marker-buffer marker)))
  7979. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  7980. (sit-for 3)
  7981. (throw 'exit nil)))
  7982. t)))
  7983. (defun org-refile-cache-put (set &rest identifiers)
  7984. "Push the refile targets SET into the cache, under IDENTIFIERS."
  7985. (let* ((key (sha1 (prin1-to-string identifiers)))
  7986. (entry (assoc key org-refile-cache)))
  7987. (if entry
  7988. (setcdr entry set)
  7989. (push (cons key set) org-refile-cache))))
  7990. (defun org-refile-cache-get (&rest identifiers)
  7991. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  7992. (cond
  7993. ((not org-refile-cache) nil)
  7994. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  7995. (t
  7996. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  7997. org-refile-cache))))
  7998. (and set (org-refile-cache-check-set set) set)))))
  7999. (defvar org-outline-path-cache nil
  8000. "Alist between buffer positions and outline paths.
  8001. It value is an alist (POSITION . PATH) where POSITION is the
  8002. buffer position at the beginning of an entry and PATH is a list
  8003. of strings describing the outline path for that entry, in reverse
  8004. order.")
  8005. (defun org-refile-get-targets (&optional default-buffer)
  8006. "Produce a table with refile targets."
  8007. (let ((case-fold-search nil)
  8008. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8009. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8010. targets tgs files desc descre)
  8011. (message "Getting targets...")
  8012. (with-current-buffer (or default-buffer (current-buffer))
  8013. (dolist (entry entries)
  8014. (setq files (car entry) desc (cdr entry))
  8015. (cond
  8016. ((null files) (setq files (list (current-buffer))))
  8017. ((eq files 'org-agenda-files)
  8018. (setq files (org-agenda-files 'unrestricted)))
  8019. ((and (symbolp files) (fboundp files))
  8020. (setq files (funcall files)))
  8021. ((and (symbolp files) (boundp files))
  8022. (setq files (symbol-value files))))
  8023. (when (stringp files) (setq files (list files)))
  8024. (cond
  8025. ((eq (car desc) :tag)
  8026. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8027. ((eq (car desc) :todo)
  8028. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8029. ((eq (car desc) :regexp)
  8030. (setq descre (cdr desc)))
  8031. ((eq (car desc) :level)
  8032. (setq descre (concat "^\\*\\{" (number-to-string
  8033. (if org-odd-levels-only
  8034. (1- (* 2 (cdr desc)))
  8035. (cdr desc)))
  8036. "\\}[ \t]")))
  8037. ((eq (car desc) :maxlevel)
  8038. (setq descre (concat "^\\*\\{1," (number-to-string
  8039. (if org-odd-levels-only
  8040. (1- (* 2 (cdr desc)))
  8041. (cdr desc)))
  8042. "\\}[ \t]")))
  8043. (t (error "Bad refiling target description %s" desc)))
  8044. (dolist (f files)
  8045. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8046. (or
  8047. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8048. (progn
  8049. (when (bufferp f)
  8050. (setq f (buffer-file-name (buffer-base-buffer f))))
  8051. (setq f (and f (expand-file-name f)))
  8052. (when (eq org-refile-use-outline-path 'file)
  8053. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8054. (when (eq org-refile-use-outline-path 'buffer-name)
  8055. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8056. (when (eq org-refile-use-outline-path 'full-file-path)
  8057. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8058. (org-with-wide-buffer
  8059. (goto-char (point-min))
  8060. (setq org-outline-path-cache nil)
  8061. (while (re-search-forward descre nil t)
  8062. (beginning-of-line)
  8063. (let ((case-fold-search nil))
  8064. (looking-at org-complex-heading-regexp))
  8065. (let ((begin (point))
  8066. (heading (match-string-no-properties 4)))
  8067. (unless (or (and
  8068. org-refile-target-verify-function
  8069. (not
  8070. (funcall org-refile-target-verify-function)))
  8071. (not heading))
  8072. (let ((re (format org-complex-heading-regexp-format
  8073. (regexp-quote heading)))
  8074. (target
  8075. (if (not org-refile-use-outline-path) heading
  8076. (mapconcat
  8077. #'identity
  8078. (append
  8079. (pcase org-refile-use-outline-path
  8080. (`file (list (file-name-nondirectory
  8081. (buffer-file-name
  8082. (buffer-base-buffer)))))
  8083. (`full-file-path
  8084. (list (buffer-file-name
  8085. (buffer-base-buffer))))
  8086. (`buffer-name
  8087. (list (buffer-name
  8088. (buffer-base-buffer))))
  8089. (_ nil))
  8090. (mapcar (lambda (s) (replace-regexp-in-string
  8091. "/" "\\/" s nil t))
  8092. (org-get-outline-path t t)))
  8093. "/"))))
  8094. (push (list target f re (org-refile-marker (point)))
  8095. tgs)))
  8096. (when (= (point) begin)
  8097. ;; Verification function has not moved point.
  8098. (end-of-line)))))))
  8099. (when org-refile-use-cache
  8100. (org-refile-cache-put tgs (buffer-file-name) descre))
  8101. (setq targets (append tgs targets))))))
  8102. (message "Getting targets...done")
  8103. (delete-dups (nreverse targets))))
  8104. (defun org--get-outline-path-1 (&optional use-cache)
  8105. "Return outline path to current headline.
  8106. Outline path is a list of strings, in reverse order. When
  8107. optional argument USE-CACHE is non-nil, make use of a cache. See
  8108. `org-get-outline-path' for details.
  8109. Assume buffer is widened and point is on a headline."
  8110. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8111. (let ((p (point))
  8112. (heading (let ((case-fold-search nil))
  8113. (looking-at org-complex-heading-regexp)
  8114. (if (not (match-end 4)) ""
  8115. ;; Remove statistics cookies.
  8116. (org-trim
  8117. (org-link-display-format
  8118. (replace-regexp-in-string
  8119. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8120. (match-string-no-properties 4))))))))
  8121. (if (org-up-heading-safe)
  8122. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8123. (when use-cache
  8124. (push (cons p path) org-outline-path-cache))
  8125. path)
  8126. ;; This is a new root node. Since we assume we are moving
  8127. ;; forward, we can drop previous cache so as to limit number
  8128. ;; of associations there.
  8129. (let ((path (list heading)))
  8130. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8131. path)))))
  8132. (defun org-get-outline-path (&optional with-self use-cache)
  8133. "Return the outline path to the current entry.
  8134. An outline path is a list of ancestors for current headline, as
  8135. a list of strings. Statistics cookies are removed and links are
  8136. replaced with their description, if any, or their path otherwise.
  8137. When optional argument WITH-SELF is non-nil, the path also
  8138. includes the current headline.
  8139. When optional argument USE-CACHE is non-nil, cache outline paths
  8140. between calls to this function so as to avoid backtracking. This
  8141. argument is useful when planning to find more than one outline
  8142. path in the same document. In that case, there are two
  8143. conditions to satisfy:
  8144. - `org-outline-path-cache' is set to nil before starting the
  8145. process;
  8146. - outline paths are computed by increasing buffer positions."
  8147. (org-with-wide-buffer
  8148. (and (or (and with-self (org-back-to-heading t))
  8149. (org-up-heading-safe))
  8150. (reverse (org--get-outline-path-1 use-cache)))))
  8151. (defun org-format-outline-path (path &optional width prefix separator)
  8152. "Format the outline path PATH for display.
  8153. WIDTH is the maximum number of characters that is available.
  8154. PREFIX is a prefix to be included in the returned string,
  8155. such as the file name.
  8156. SEPARATOR is inserted between the different parts of the path,
  8157. the default is \"/\"."
  8158. (setq width (or width 79))
  8159. (setq path (delq nil path))
  8160. (unless (> width 0)
  8161. (user-error "Argument `width' must be positive"))
  8162. (setq separator (or separator "/"))
  8163. (let* ((org-odd-levels-only nil)
  8164. (fpath (concat
  8165. prefix (and prefix path separator)
  8166. (mapconcat
  8167. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8168. (cl-loop for head in path
  8169. for n from 0
  8170. collect (org-add-props
  8171. head nil 'face
  8172. (nth (% n org-n-level-faces) org-level-faces)))
  8173. separator))))
  8174. (when (> (length fpath) width)
  8175. (if (< width 7)
  8176. ;; It's unlikely that `width' will be this small, but don't
  8177. ;; waste characters by adding ".." if it is.
  8178. (setq fpath (substring fpath 0 width))
  8179. (setf (substring fpath (- width 2)) "..")))
  8180. fpath))
  8181. (defun org-display-outline-path (&optional file current separator just-return-string)
  8182. "Display the current outline path in the echo area.
  8183. If FILE is non-nil, prepend the output with the file name.
  8184. If CURRENT is non-nil, append the current heading to the output.
  8185. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8186. the different parts of the path and defaults to \"/\".
  8187. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8188. (interactive "P")
  8189. (let* (case-fold-search
  8190. (bfn (buffer-file-name (buffer-base-buffer)))
  8191. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8192. res)
  8193. (when current (setq path (append path
  8194. (save-excursion
  8195. (org-back-to-heading t)
  8196. (when (looking-at org-complex-heading-regexp)
  8197. (list (match-string 4)))))))
  8198. (setq res
  8199. (org-format-outline-path
  8200. path
  8201. (1- (frame-width))
  8202. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8203. separator))
  8204. (if just-return-string
  8205. (org-no-properties res)
  8206. (org-unlogged-message "%s" res))))
  8207. (defvar org-refile-history nil
  8208. "History for refiling operations.")
  8209. (defvar org-after-refile-insert-hook nil
  8210. "Hook run after `org-refile' has inserted its stuff at the new location.
  8211. Note that this is still *before* the stuff will be removed from
  8212. the *old* location.")
  8213. (defvar org-capture-last-stored-marker)
  8214. (defvar org-refile-keep nil
  8215. "Non-nil means `org-refile' will copy instead of refile.")
  8216. (defun org-copy ()
  8217. "Like `org-refile', but copy."
  8218. (interactive)
  8219. (let ((org-refile-keep t))
  8220. (org-refile nil nil nil "Copy")))
  8221. (defun org-refile (&optional arg default-buffer rfloc msg)
  8222. "Move the entry or entries at point to another heading.
  8223. The list of target headings is compiled using the information in
  8224. `org-refile-targets', which see.
  8225. At the target location, the entry is filed as a subitem of the
  8226. target heading. Depending on `org-reverse-note-order', the new
  8227. subitem will either be the first or the last subitem.
  8228. If there is an active region, all entries in that region will be
  8229. refiled. However, the region must fulfill the requirement that
  8230. the first heading sets the top-level of the moved text.
  8231. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8232. location
  8233. and not actually move anything.
  8234. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8235. location where the last
  8236. refiling operation has put the subtree.
  8237. With a numeric prefix argument of `2', refile to the running clock.
  8238. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8239. being set to t and copy to the target location, don't move it.
  8240. Beware that keeping refiled entries may result in duplicated ID
  8241. properties.
  8242. RFLOC can be a refile location obtained in a different way.
  8243. MSG is a string to replace \"Refile\" in the default prompt with
  8244. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8245. See also `org-refile-use-outline-path'.
  8246. If you are using target caching (see `org-refile-use-cache'), you
  8247. have to clear the target cache in order to find new targets.
  8248. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8249. prefix argument (`C-u C-u C-u C-c C-w')."
  8250. (interactive "P")
  8251. (if (member arg '(0 (64)))
  8252. (org-refile-cache-clear)
  8253. (let* ((actionmsg (cond (msg msg)
  8254. ((equal arg 3) "Refile (and keep)")
  8255. (t "Refile")))
  8256. (regionp (org-region-active-p))
  8257. (region-start (and regionp (region-beginning)))
  8258. (region-end (and regionp (region-end)))
  8259. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8260. pos it nbuf file level reversed)
  8261. (setq last-command nil)
  8262. (when regionp
  8263. (goto-char region-start)
  8264. (beginning-of-line)
  8265. (setq region-start (point))
  8266. (unless (or (org-kill-is-subtree-p
  8267. (buffer-substring region-start region-end))
  8268. (prog1 org-refile-active-region-within-subtree
  8269. (let ((s (point-at-eol)))
  8270. (org-toggle-heading)
  8271. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8272. (user-error "The region is not a (sequence of) subtree(s)")))
  8273. (if (equal arg '(16))
  8274. (org-refile-goto-last-stored)
  8275. (when (or
  8276. (and (equal arg 2)
  8277. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8278. (prog1
  8279. (setq it (list (or org-clock-heading "running clock")
  8280. (buffer-file-name
  8281. (marker-buffer org-clock-hd-marker))
  8282. ""
  8283. (marker-position org-clock-hd-marker)))
  8284. (setq arg nil)))
  8285. (setq it
  8286. (or rfloc
  8287. (let (heading-text)
  8288. (save-excursion
  8289. (unless (and arg (listp arg))
  8290. (org-back-to-heading t)
  8291. (setq heading-text
  8292. (replace-regexp-in-string
  8293. org-link-bracket-re
  8294. "\\2"
  8295. (or (nth 4 (org-heading-components))
  8296. ""))))
  8297. (org-refile-get-location
  8298. (cond ((and arg (listp arg)) "Goto")
  8299. (regionp (concat actionmsg " region to"))
  8300. (t (concat actionmsg " subtree \""
  8301. heading-text "\" to")))
  8302. default-buffer
  8303. (and (not (equal '(4) arg))
  8304. org-refile-allow-creating-parent-nodes)))))))
  8305. (setq file (nth 1 it)
  8306. pos (nth 3 it))
  8307. (when (and (not arg)
  8308. pos
  8309. (equal (buffer-file-name) file)
  8310. (if regionp
  8311. (and (>= pos region-start)
  8312. (<= pos region-end))
  8313. (and (>= pos (point))
  8314. (< pos (save-excursion
  8315. (org-end-of-subtree t t))))))
  8316. (error "Cannot refile to position inside the tree or region"))
  8317. (setq nbuf (or (find-buffer-visiting file)
  8318. (find-file-noselect file)))
  8319. (if (and arg (not (equal arg 3)))
  8320. (progn
  8321. (pop-to-buffer-same-window nbuf)
  8322. (goto-char (cond (pos)
  8323. ((org-notes-order-reversed-p) (point-min))
  8324. (t (point-max))))
  8325. (org-show-context 'org-goto))
  8326. (if regionp
  8327. (progn
  8328. (org-kill-new (buffer-substring region-start region-end))
  8329. (org-save-markers-in-region region-start region-end))
  8330. (org-copy-subtree 1 nil t))
  8331. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8332. (find-file-noselect file)))
  8333. (setq reversed (org-notes-order-reversed-p))
  8334. (org-with-wide-buffer
  8335. (if pos
  8336. (progn
  8337. (goto-char pos)
  8338. (setq level (org-get-valid-level (funcall outline-level) 1))
  8339. (goto-char
  8340. (if reversed
  8341. (or (outline-next-heading) (point-max))
  8342. (or (save-excursion (org-get-next-sibling))
  8343. (org-end-of-subtree t t)
  8344. (point-max)))))
  8345. (setq level 1)
  8346. (if (not reversed)
  8347. (goto-char (point-max))
  8348. (goto-char (point-min))
  8349. (or (outline-next-heading) (goto-char (point-max)))))
  8350. (unless (bolp) (newline))
  8351. (org-paste-subtree level nil nil t)
  8352. ;; Record information, according to `org-log-refile'.
  8353. ;; Do not prompt for a note when refiling multiple
  8354. ;; headlines, however. Simply add a time stamp.
  8355. (cond
  8356. ((not org-log-refile))
  8357. (regionp
  8358. (org-map-region
  8359. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8360. (point)
  8361. (+ (point) (- region-end region-start))))
  8362. (t
  8363. (org-add-log-setup 'refile nil nil org-log-refile)))
  8364. (and org-auto-align-tags
  8365. (let ((org-loop-over-headlines-in-active-region nil))
  8366. (org-align-tags)))
  8367. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8368. :last-refile)))
  8369. (when bookmark-name
  8370. (with-demoted-errors
  8371. (bookmark-set bookmark-name))))
  8372. ;; If we are refiling for capture, make sure that the
  8373. ;; last-capture pointers point here
  8374. (when (bound-and-true-p org-capture-is-refiling)
  8375. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8376. :last-capture-marker)))
  8377. (when bookmark-name
  8378. (with-demoted-errors
  8379. (bookmark-set bookmark-name))))
  8380. (move-marker org-capture-last-stored-marker (point)))
  8381. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8382. (run-hooks 'org-after-refile-insert-hook)))
  8383. (unless org-refile-keep
  8384. (if regionp
  8385. (delete-region (point) (+ (point) (- region-end region-start)))
  8386. (org-preserve-local-variables
  8387. (delete-region
  8388. (and (org-back-to-heading t) (point))
  8389. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8390. (when (featurep 'org-inlinetask)
  8391. (org-inlinetask-remove-END-maybe))
  8392. (setq org-markers-to-move nil)
  8393. (message "%s to \"%s\" in file %s: done" actionmsg
  8394. (car it) file)))))))
  8395. (defun org-refile-goto-last-stored ()
  8396. "Go to the location where the last refile was stored."
  8397. (interactive)
  8398. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8399. (message "This is the location of the last refile"))
  8400. (defun org-refile--get-location (refloc tbl)
  8401. "When user refile to REFLOC, find the associated target in TBL.
  8402. Also check `org-refile-target-table'."
  8403. (car (delq
  8404. nil
  8405. (mapcar
  8406. (lambda (r) (or (assoc r tbl)
  8407. (assoc r org-refile-target-table)))
  8408. (list (replace-regexp-in-string "/$" "" refloc)
  8409. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8410. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8411. "Prompt the user for a refile location, using PROMPT.
  8412. PROMPT should not be suffixed with a colon and a space, because
  8413. this function appends the default value from
  8414. `org-refile-history' automatically, if that is not empty."
  8415. (let ((org-refile-targets org-refile-targets)
  8416. (org-refile-use-outline-path org-refile-use-outline-path))
  8417. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8418. (unless org-refile-target-table
  8419. (user-error "No refile targets"))
  8420. (let* ((cbuf (current-buffer))
  8421. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8422. (cfunc (if (and org-refile-use-outline-path
  8423. org-outline-path-complete-in-steps)
  8424. #'org-olpath-completing-read
  8425. #'completing-read))
  8426. (extra (if org-refile-use-outline-path "/" ""))
  8427. (cbnex (concat (buffer-name) extra))
  8428. (filename (and cfn (expand-file-name cfn)))
  8429. (tbl (mapcar
  8430. (lambda (x)
  8431. (if (and (not (member org-refile-use-outline-path
  8432. '(file full-file-path)))
  8433. (not (equal filename (nth 1 x))))
  8434. (cons (concat (car x) extra " ("
  8435. (file-name-nondirectory (nth 1 x)) ")")
  8436. (cdr x))
  8437. (cons (concat (car x) extra) (cdr x))))
  8438. org-refile-target-table))
  8439. (completion-ignore-case t)
  8440. cdef
  8441. (prompt (concat prompt
  8442. (or (and (car org-refile-history)
  8443. (concat " (default " (car org-refile-history) ")"))
  8444. (and (assoc cbnex tbl) (setq cdef cbnex)
  8445. (concat " (default " cbnex ")"))) ": "))
  8446. pa answ parent-target child parent old-hist)
  8447. (setq old-hist org-refile-history)
  8448. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8449. nil 'org-refile-history (or cdef (car org-refile-history))))
  8450. (if (setq pa (org-refile--get-location answ tbl))
  8451. (progn
  8452. (org-refile-check-position pa)
  8453. (when (or (not org-refile-history)
  8454. (not (eq old-hist org-refile-history))
  8455. (not (equal (car pa) (car org-refile-history))))
  8456. (setq org-refile-history
  8457. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8458. org-refile-history
  8459. (cdr org-refile-history))))
  8460. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8461. (pop org-refile-history)))
  8462. pa)
  8463. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8464. (progn
  8465. (setq parent (match-string 1 answ)
  8466. child (match-string 2 answ))
  8467. (setq parent-target (org-refile--get-location parent tbl))
  8468. (when (and parent-target
  8469. (or (eq new-nodes t)
  8470. (and (eq new-nodes 'confirm)
  8471. (y-or-n-p (format "Create new node \"%s\"? "
  8472. child)))))
  8473. (org-refile-new-child parent-target child)))
  8474. (user-error "Invalid target location")))))
  8475. (declare-function org-string-nw-p "org-macs" (s))
  8476. (defun org-refile-check-position (refile-pointer)
  8477. "Check if the refile pointer matches the headline to which it points."
  8478. (let* ((file (nth 1 refile-pointer))
  8479. (re (nth 2 refile-pointer))
  8480. (pos (nth 3 refile-pointer))
  8481. buffer)
  8482. (if (and (not (markerp pos)) (not file))
  8483. (user-error "Please indicate a target file in the refile path")
  8484. (when (org-string-nw-p re)
  8485. (setq buffer (if (markerp pos)
  8486. (marker-buffer pos)
  8487. (or (find-buffer-visiting file)
  8488. (find-file-noselect file))))
  8489. (with-current-buffer buffer
  8490. (org-with-wide-buffer
  8491. (goto-char pos)
  8492. (beginning-of-line 1)
  8493. (unless (looking-at-p re)
  8494. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8495. (defun org-refile-new-child (parent-target child)
  8496. "Use refile target PARENT-TARGET to add new CHILD below it."
  8497. (unless parent-target
  8498. (error "Cannot find parent for new node"))
  8499. (let ((file (nth 1 parent-target))
  8500. (pos (nth 3 parent-target))
  8501. level)
  8502. (with-current-buffer (or (find-buffer-visiting file)
  8503. (find-file-noselect file))
  8504. (org-with-wide-buffer
  8505. (if pos
  8506. (goto-char pos)
  8507. (goto-char (point-max))
  8508. (unless (bolp) (newline)))
  8509. (when (looking-at org-outline-regexp)
  8510. (setq level (funcall outline-level))
  8511. (org-end-of-subtree t t))
  8512. (org-back-over-empty-lines)
  8513. (insert "\n" (make-string
  8514. (if pos (org-get-valid-level level 1) 1) ?*)
  8515. " " child "\n")
  8516. (beginning-of-line 0)
  8517. (list (concat (car parent-target) "/" child) file "" (point))))))
  8518. (defun org-olpath-completing-read (prompt collection &rest args)
  8519. "Read an outline path like a file name."
  8520. (let ((thetable collection))
  8521. (apply #'completing-read
  8522. prompt
  8523. (lambda (string predicate &optional flag)
  8524. (cond
  8525. ((eq flag nil) (try-completion string thetable))
  8526. ((eq flag t)
  8527. (let ((l (length string)))
  8528. (mapcar (lambda (x)
  8529. (let ((r (substring x l))
  8530. (f (if (string-match " ([^)]*)$" x)
  8531. (match-string 0 x)
  8532. "")))
  8533. (if (string-match "/" r)
  8534. (concat string (substring r 0 (match-end 0)) f)
  8535. x)))
  8536. (all-completions string thetable predicate))))
  8537. ;; Exact match?
  8538. ((eq flag 'lambda) (assoc string thetable))))
  8539. args)))
  8540. ;;;; Dynamic blocks
  8541. (defun org-find-dblock (name)
  8542. "Find the first dynamic block with name NAME in the buffer.
  8543. If not found, stay at current position and return nil."
  8544. (let ((case-fold-search t) pos)
  8545. (save-excursion
  8546. (goto-char (point-min))
  8547. (setq pos (and (re-search-forward
  8548. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8549. (match-beginning 0))))
  8550. (when pos (goto-char pos))
  8551. pos))
  8552. (defun org-create-dblock (plist)
  8553. "Create a dynamic block section, with parameters taken from PLIST.
  8554. PLIST must contain a :name entry which is used as the name of the block."
  8555. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8556. (end-of-line 1)
  8557. (newline))
  8558. (let ((col (current-column))
  8559. (name (plist-get plist :name)))
  8560. (insert "#+BEGIN: " name)
  8561. (while plist
  8562. (if (eq (car plist) :name)
  8563. (setq plist (cddr plist))
  8564. (insert " " (prin1-to-string (pop plist)))))
  8565. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8566. (beginning-of-line -2)))
  8567. (defun org-prepare-dblock ()
  8568. "Prepare dynamic block for refresh.
  8569. This empties the block, puts the cursor at the insert position and returns
  8570. the property list including an extra property :name with the block name."
  8571. (unless (looking-at org-dblock-start-re)
  8572. (user-error "Not at a dynamic block"))
  8573. (let* ((begdel (1+ (match-end 0)))
  8574. (name (org-no-properties (match-string 1)))
  8575. (params (append (list :name name)
  8576. (read (concat "(" (match-string 3) ")")))))
  8577. (save-excursion
  8578. (beginning-of-line 1)
  8579. (skip-chars-forward " \t")
  8580. (setq params (plist-put params :indentation-column (current-column))))
  8581. (unless (re-search-forward org-dblock-end-re nil t)
  8582. (error "Dynamic block not terminated"))
  8583. (setq params
  8584. (append params
  8585. (list :content (buffer-substring
  8586. begdel (match-beginning 0)))))
  8587. (delete-region begdel (match-beginning 0))
  8588. (goto-char begdel)
  8589. (open-line 1)
  8590. params))
  8591. (defun org-map-dblocks (&optional command)
  8592. "Apply COMMAND to all dynamic blocks in the current buffer.
  8593. If COMMAND is not given, use `org-update-dblock'."
  8594. (let ((cmd (or command 'org-update-dblock)))
  8595. (save-excursion
  8596. (goto-char (point-min))
  8597. (while (re-search-forward org-dblock-start-re nil t)
  8598. (goto-char (match-beginning 0))
  8599. (save-excursion
  8600. (condition-case nil
  8601. (funcall cmd)
  8602. (error (message "Error during update of dynamic block"))))
  8603. (unless (re-search-forward org-dblock-end-re nil t)
  8604. (error "Dynamic block not terminated"))))))
  8605. (defvar org-dynamic-block-alist nil
  8606. "Alist defining all the Org dynamic blocks.
  8607. The key is the dynamic block type name, as a string. The value
  8608. is the function used to insert the dynamic block.
  8609. Use `org-dynamic-block-define' to populate it.")
  8610. (defun org-dynamic-block-function (type)
  8611. "Return function associated to a given dynamic block type.
  8612. TYPE is the dynamic block type, as a string."
  8613. (cdr (assoc type org-dynamic-block-alist)))
  8614. (defun org-dynamic-block-types ()
  8615. "List all defined dynamic block types."
  8616. (mapcar #'car org-dynamic-block-alist))
  8617. (defun org-dynamic-block-define (type func)
  8618. "Define dynamic block TYPE with FUNC.
  8619. TYPE is a string. FUNC is the function creating the dynamic
  8620. block of such type."
  8621. (pcase (assoc type org-dynamic-block-alist)
  8622. (`nil (push (cons type func) org-dynamic-block-alist))
  8623. (def (setcdr def func))))
  8624. (defun org-dynamic-block-insert-dblock (type)
  8625. "Insert a dynamic block of type TYPE.
  8626. When used interactively, select the dynamic block types among
  8627. defined types, per `org-dynamic-block-define'."
  8628. (interactive (list (completing-read "Dynamic block: "
  8629. (org-dynamic-block-types))))
  8630. (pcase (org-dynamic-block-function type)
  8631. (`nil (error "No such dynamic block: %S" type))
  8632. ((and f (pred functionp)) (funcall f))
  8633. (_ (error "Invalid function for dynamic block %S" type))))
  8634. (defun org-dblock-update (&optional arg)
  8635. "User command for updating dynamic blocks.
  8636. Update the dynamic block at point. With prefix ARG, update all dynamic
  8637. blocks in the buffer."
  8638. (interactive "P")
  8639. (if arg
  8640. (org-update-all-dblocks)
  8641. (or (looking-at org-dblock-start-re)
  8642. (org-beginning-of-dblock))
  8643. (org-update-dblock)))
  8644. (defun org-update-dblock ()
  8645. "Update the dynamic block at point.
  8646. This means to empty the block, parse for parameters and then call
  8647. the correct writing function."
  8648. (interactive)
  8649. (save-excursion
  8650. (let* ((win (selected-window))
  8651. (pos (point))
  8652. (line (org-current-line))
  8653. (params (org-prepare-dblock))
  8654. (name (plist-get params :name))
  8655. (indent (plist-get params :indentation-column))
  8656. (cmd (intern (concat "org-dblock-write:" name))))
  8657. (message "Updating dynamic block `%s' at line %d..." name line)
  8658. (funcall cmd params)
  8659. (message "Updating dynamic block `%s' at line %d...done" name line)
  8660. (goto-char pos)
  8661. (when (and indent (> indent 0))
  8662. (setq indent (make-string indent ?\ ))
  8663. (save-excursion
  8664. (select-window win)
  8665. (org-beginning-of-dblock)
  8666. (forward-line 1)
  8667. (while (not (looking-at org-dblock-end-re))
  8668. (insert indent)
  8669. (beginning-of-line 2))
  8670. (when (looking-at org-dblock-end-re)
  8671. (and (looking-at "[ \t]+")
  8672. (replace-match ""))
  8673. (insert indent)))))))
  8674. (defun org-beginning-of-dblock ()
  8675. "Find the beginning of the dynamic block at point.
  8676. Error if there is no such block at point."
  8677. (let ((pos (point))
  8678. beg)
  8679. (end-of-line 1)
  8680. (if (and (re-search-backward org-dblock-start-re nil t)
  8681. (setq beg (match-beginning 0))
  8682. (re-search-forward org-dblock-end-re nil t)
  8683. (> (match-end 0) pos))
  8684. (goto-char beg)
  8685. (goto-char pos)
  8686. (error "Not in a dynamic block"))))
  8687. (defun org-update-all-dblocks ()
  8688. "Update all dynamic blocks in the buffer.
  8689. This function can be used in a hook."
  8690. (interactive)
  8691. (when (derived-mode-p 'org-mode)
  8692. (org-map-dblocks 'org-update-dblock)))
  8693. ;;;; Completion
  8694. (declare-function org-export-backend-options "ox" (cl-x) t)
  8695. (defun org-get-export-keywords ()
  8696. "Return a list of all currently understood export keywords.
  8697. Export keywords include options, block names, attributes and
  8698. keywords relative to each registered export back-end."
  8699. (let (keywords)
  8700. (dolist (backend
  8701. (bound-and-true-p org-export-registered-backends)
  8702. (delq nil keywords))
  8703. ;; Back-end name (for keywords, like #+LATEX:)
  8704. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8705. (dolist (option-entry (org-export-backend-options backend))
  8706. ;; Back-end options.
  8707. (push (nth 1 option-entry) keywords)))))
  8708. (defconst org-options-keywords
  8709. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8710. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8711. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8712. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8713. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8714. (defcustom org-structure-template-alist
  8715. '(("a" . "export ascii")
  8716. ("c" . "center")
  8717. ("C" . "comment")
  8718. ("e" . "example")
  8719. ("E" . "export")
  8720. ("h" . "export html")
  8721. ("l" . "export latex")
  8722. ("q" . "quote")
  8723. ("s" . "src")
  8724. ("v" . "verse"))
  8725. "An alist of keys and block types.
  8726. `org-insert-structure-template' will display a menu with this
  8727. list of templates to choose from. The block type is inserted,
  8728. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8729. The menu keys are defined by the car of each entry in this alist.
  8730. If two entries have the keys \"a\" and \"aa\" respectively, the
  8731. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8732. latter will be inserted by typing \"aa\". If an entry with the
  8733. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8734. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8735. block can be inserted by pressing TAB after the string \"<KEY\"."
  8736. :group 'org-edit-structure
  8737. :type '(repeat
  8738. (cons (string :tag "Key")
  8739. (string :tag "Template")))
  8740. :package-version '(Org . "9.2"))
  8741. (defun org--check-org-structure-template-alist (&optional checklist)
  8742. "Check whether `org-structure-template-alist' is set up correctly.
  8743. In particular, check if the Org 9.2 format is used as opposed to
  8744. previous format.
  8745. "
  8746. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8747. (or (eval checklist)
  8748. org-structure-template-alist))))
  8749. (when elm
  8750. (org-display-warning
  8751. (format "
  8752. Please update the entries of `%s'.
  8753. In Org 9.2 the format was changed from something like
  8754. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8755. to something like
  8756. (\"s\" . \"src\")
  8757. Please refer to the documentation of `org-structure-template-alist'.
  8758. The following entries must be updated:
  8759. %s"
  8760. (or checklist 'org-structure-template-alist)
  8761. (pp-to-string elm))))))
  8762. (defun org--insert-structure-template-mks ()
  8763. "Present `org-structure-template-alist' with `org-mks'.
  8764. Menus are added if keys require more than one keystroke. Tabs
  8765. are added to single key entries when more than one stroke is
  8766. needed. Keys longer than two characters are reduced to two
  8767. characters."
  8768. (org--check-org-structure-template-alist)
  8769. (let* (case-fold-search
  8770. (templates (append org-structure-template-alist
  8771. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8772. (keys (mapcar #'car templates))
  8773. (start-letters
  8774. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8775. ;; Sort each element of `org-structure-template-alist' into
  8776. ;; sublists according to the first letter.
  8777. (superlist
  8778. (mapcar (lambda (letter)
  8779. (list letter
  8780. (cl-remove-if-not
  8781. (apply-partially #'string-match-p (concat "^" letter))
  8782. templates :key #'car)))
  8783. start-letters)))
  8784. (org-mks
  8785. (apply #'append
  8786. ;; Make an `org-mks' table. If only one element is
  8787. ;; present in a sublist, make it part of the top-menu,
  8788. ;; otherwise make a submenu according to the starting
  8789. ;; letter and populate it.
  8790. (mapcar (lambda (sublist)
  8791. (if (eq 1 (length (cadr sublist)))
  8792. (mapcar (lambda (elm)
  8793. (list (substring (car elm) 0 1)
  8794. (cdr elm) ""))
  8795. (cadr sublist))
  8796. ;; Create submenu.
  8797. (let* ((topkey (car sublist))
  8798. (elms (cadr sublist))
  8799. (keys (mapcar #'car elms))
  8800. (long (> (length elms) 3)))
  8801. (append
  8802. (list
  8803. ;; Make a description of the submenu.
  8804. (list topkey
  8805. (concat
  8806. (mapconcat #'cdr
  8807. (cl-subseq elms 0 (if long 3 (length elms)))
  8808. ", ")
  8809. (when long ", ..."))))
  8810. ;; List of entries in submenu.
  8811. (cl-mapcar #'list
  8812. (org--insert-structure-template-unique-keys keys)
  8813. (mapcar #'cdr elms)
  8814. (make-list (length elms) ""))))))
  8815. superlist))
  8816. "Select a key\n============"
  8817. "Key: ")))
  8818. (defun org--insert-structure-template-unique-keys (keys)
  8819. "Make a list of unique, two characters long elements from KEYS.
  8820. Elements of length one have a tab appended. Elements of length
  8821. two are kept as is. Longer elements are truncated to length two.
  8822. If an element cannot be made unique, an error is raised."
  8823. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8824. menu-keys)
  8825. (dolist (key orderd-keys)
  8826. (let ((potential-key
  8827. (cl-case (length key)
  8828. (1 (concat key "\t"))
  8829. (2 key)
  8830. (otherwise
  8831. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8832. (mapcar (apply-partially #'concat (substring key 0 1))
  8833. (split-string (substring key 1) "" t)))))))
  8834. (if (or (not potential-key) (assoc potential-key menu-keys))
  8835. (user-error "Could not make unique key for %s." key)
  8836. (push (cons potential-key key) menu-keys))))
  8837. (mapcar #'car
  8838. (cl-sort menu-keys #'<
  8839. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8840. (defun org-insert-structure-template (type)
  8841. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8842. Select a block from `org-structure-template-alist' then type
  8843. either RET, TAB or SPC to write the block type. With an active
  8844. region, wrap the region in the block. Otherwise, insert an empty
  8845. block."
  8846. (interactive
  8847. (list (pcase (org--insert-structure-template-mks)
  8848. (`("\t" . ,_) (read-string "Structure type: "))
  8849. (`(,_ ,choice . ,_) choice))))
  8850. (let* ((region? (use-region-p))
  8851. (region-start (and region? (region-beginning)))
  8852. (region-end (and region? (copy-marker (region-end))))
  8853. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8854. (verbatim? (string-match-p
  8855. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8856. type)))
  8857. (when region? (goto-char region-start))
  8858. (let ((column (current-indentation)))
  8859. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8860. (beginning-of-line)
  8861. (insert "\n"))
  8862. (save-excursion
  8863. (indent-to column)
  8864. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8865. (when region?
  8866. (when verbatim? (org-escape-code-in-region (point) region-end))
  8867. (goto-char region-end)
  8868. ;; Ignore empty lines at the end of the region.
  8869. (skip-chars-backward " \r\t\n")
  8870. (end-of-line))
  8871. (unless (bolp) (insert "\n"))
  8872. (indent-to column)
  8873. (insert (format "#+end_%s" (car (split-string type))))
  8874. (if (looking-at "[ \t]*$") (replace-match "")
  8875. (insert "\n"))
  8876. (when (and (eobp) (not (bolp))) (insert "\n")))
  8877. (if extended? (end-of-line)
  8878. (forward-line)
  8879. (skip-chars-forward " \t")))))
  8880. ;;;; TODO, DEADLINE, Comments
  8881. (defun org-toggle-comment ()
  8882. "Change the COMMENT state of an entry."
  8883. (interactive)
  8884. (save-excursion
  8885. (org-back-to-heading)
  8886. (let ((case-fold-search nil))
  8887. (looking-at org-complex-heading-regexp))
  8888. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8889. (skip-chars-forward " \t")
  8890. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8891. (if (org-in-commented-heading-p t)
  8892. (delete-region (point)
  8893. (progn (search-forward " " (line-end-position) 'move)
  8894. (skip-chars-forward " \t")
  8895. (point)))
  8896. (insert org-comment-string)
  8897. (unless (eolp) (insert " ")))))
  8898. (defvar org-last-todo-state-is-todo nil
  8899. "This is non-nil when the last TODO state change led to a TODO state.
  8900. If the last change removed the TODO tag or switched to DONE, then
  8901. this is nil.")
  8902. (defvar org-todo-setup-filter-hook nil
  8903. "Hook for functions that pre-filter todo specs.
  8904. Each function takes a todo spec and returns either nil or the spec
  8905. transformed into canonical form." )
  8906. (defvar org-todo-get-default-hook nil
  8907. "Hook for functions that get a default item for todo.
  8908. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8909. nil or a string to be used for the todo mark." )
  8910. (defvar org-agenda-headline-snapshot-before-repeat)
  8911. (defun org-current-effective-time ()
  8912. "Return current time adjusted for `org-extend-today-until' variable."
  8913. (let* ((ct (org-current-time))
  8914. (dct (decode-time ct))
  8915. (ct1
  8916. (cond
  8917. (org-use-last-clock-out-time-as-effective-time
  8918. (or (org-clock-get-last-clock-out-time) ct))
  8919. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8920. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8921. (t ct))))
  8922. ct1))
  8923. (defun org-todo-yesterday (&optional arg)
  8924. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8925. (interactive "P")
  8926. (if (eq major-mode 'org-agenda-mode)
  8927. (apply 'org-agenda-todo-yesterday arg)
  8928. (let* ((org-use-effective-time t)
  8929. (hour (nth 2 (decode-time (org-current-time))))
  8930. (org-extend-today-until (1+ hour)))
  8931. (org-todo arg))))
  8932. (defvar org-block-entry-blocking ""
  8933. "First entry preventing the TODO state change.")
  8934. (defun org-cancel-repeater ()
  8935. "Cancel a repeater by setting its numeric value to zero."
  8936. (interactive)
  8937. (save-excursion
  8938. (org-back-to-heading t)
  8939. (let ((bound1 (point))
  8940. (bound0 (save-excursion (outline-next-heading) (point))))
  8941. (when (and (re-search-forward
  8942. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8943. org-deadline-time-regexp "\\)\\|\\("
  8944. org-ts-regexp "\\)")
  8945. bound0 t)
  8946. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8947. bound1 t))
  8948. (replace-match "0" t nil nil 1)))))
  8949. (defvar org-state)
  8950. (defvar org-blocked-by-checkboxes)
  8951. (defun org-todo (&optional arg)
  8952. "Change the TODO state of an item.
  8953. The state of an item is given by a keyword at the start of the heading,
  8954. like
  8955. *** TODO Write paper
  8956. *** DONE Call mom
  8957. The different keywords are specified in the variable `org-todo-keywords'.
  8958. By default the available states are \"TODO\" and \"DONE\". So, for this
  8959. example: when the item starts with TODO, it is changed to DONE.
  8960. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8961. DONE are present, add TODO at the beginning of the heading.
  8962. You can set up single-charcter keys to fast-select the new state. See the
  8963. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8964. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8965. and take a
  8966. logging note.
  8967. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8968. next set of TODO \
  8969. keywords (nextset).
  8970. Another way to achieve this is `S-C-<right>'.
  8971. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8972. prefix, circumvent any state blocking.
  8973. With numeric prefix arg, switch to the Nth state.
  8974. With a numeric prefix arg of 0, inhibit note taking for the change.
  8975. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8976. When called through ELisp, arg is also interpreted in the following way:
  8977. `none' -> empty state
  8978. \"\" -> switch to empty state
  8979. `done' -> switch to DONE
  8980. `nextset' -> switch to the next set of keywords
  8981. `previousset' -> switch to the previous set of keywords
  8982. \"WAITING\" -> switch to the specified keyword, but only if it
  8983. really is a member of `org-todo-keywords'."
  8984. (interactive "P")
  8985. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8986. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8987. 'region-start-level 'region))
  8988. org-loop-over-headlines-in-active-region)
  8989. (org-map-entries
  8990. `(org-todo ,arg)
  8991. org-loop-over-headlines-in-active-region
  8992. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  8993. (when (equal arg '(16)) (setq arg 'nextset))
  8994. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8995. (let ((org-blocker-hook org-blocker-hook)
  8996. commentp
  8997. case-fold-search)
  8998. (when (equal arg '(64))
  8999. (setq arg nil org-blocker-hook nil))
  9000. (when (and org-blocker-hook
  9001. (or org-inhibit-blocking
  9002. (org-entry-get nil "NOBLOCKING")))
  9003. (setq org-blocker-hook nil))
  9004. (save-excursion
  9005. (catch 'exit
  9006. (org-back-to-heading t)
  9007. (when (org-in-commented-heading-p t)
  9008. (org-toggle-comment)
  9009. (setq commentp t))
  9010. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9011. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9012. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9013. (let* ((match-data (match-data))
  9014. (startpos (copy-marker (line-beginning-position)))
  9015. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  9016. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9017. (org-log-done org-log-done)
  9018. (org-log-repeat org-log-repeat)
  9019. (org-todo-log-states org-todo-log-states)
  9020. (org-inhibit-logging
  9021. (if (equal arg 0)
  9022. (progn (setq arg nil) 'note) org-inhibit-logging))
  9023. (this (match-string 1))
  9024. (hl-pos (match-beginning 0))
  9025. (head (org-get-todo-sequence-head this))
  9026. (ass (assoc head org-todo-kwd-alist))
  9027. (interpret (nth 1 ass))
  9028. (done-word (nth 3 ass))
  9029. (final-done-word (nth 4 ass))
  9030. (org-last-state (or this ""))
  9031. (completion-ignore-case t)
  9032. (member (member this org-todo-keywords-1))
  9033. (tail (cdr member))
  9034. (org-state (cond
  9035. ((and org-todo-key-trigger org-use-fast-todo-selection)
  9036. ;; Use fast selection.
  9037. (org-fast-todo-selection this))
  9038. ;; FIXME: the following should go
  9039. ((and (equal arg '(4))
  9040. (or (not org-use-fast-todo-selection)
  9041. (not org-todo-key-trigger)))
  9042. ;; Read a state with completion.
  9043. (completing-read
  9044. "State: " (mapcar #'list org-todo-keywords-1)
  9045. nil t))
  9046. ((eq arg 'right)
  9047. (if this
  9048. (if tail (car tail) nil)
  9049. (car org-todo-keywords-1)))
  9050. ((eq arg 'left)
  9051. (unless (equal member org-todo-keywords-1)
  9052. (if this
  9053. (nth (- (length org-todo-keywords-1)
  9054. (length tail) 2)
  9055. org-todo-keywords-1)
  9056. (org-last org-todo-keywords-1))))
  9057. ;; FIXMEL the following should be removed.
  9058. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  9059. (setq arg nil))) ;hack to fall back to cycling
  9060. (arg
  9061. ;; User or caller requests a specific state.
  9062. (cond
  9063. ((equal arg "") nil)
  9064. ((eq arg 'none) nil)
  9065. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9066. ((eq arg 'nextset)
  9067. (or (car (cdr (member head org-todo-heads)))
  9068. (car org-todo-heads)))
  9069. ((eq arg 'previousset)
  9070. (let ((org-todo-heads (reverse org-todo-heads)))
  9071. (or (car (cdr (member head org-todo-heads)))
  9072. (car org-todo-heads))))
  9073. ((car (member arg org-todo-keywords-1)))
  9074. ((stringp arg)
  9075. (user-error "State `%s' not valid in this file" arg))
  9076. ((nth (1- (prefix-numeric-value arg))
  9077. org-todo-keywords-1))))
  9078. ((null member) (or head (car org-todo-keywords-1)))
  9079. ((equal this final-done-word) nil) ;-> make empty
  9080. ((null tail) nil) ;-> first entry
  9081. ((memq interpret '(type priority))
  9082. (if (eq this-command last-command)
  9083. (car tail)
  9084. (if (> (length tail) 0)
  9085. (or done-word (car org-done-keywords))
  9086. nil)))
  9087. (t
  9088. (car tail))))
  9089. (org-state (or
  9090. (run-hook-with-args-until-success
  9091. 'org-todo-get-default-hook org-state org-last-state)
  9092. org-state))
  9093. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9094. (change-plist (list :type 'todo-state-change :from this :to org-state
  9095. :position startpos))
  9096. dolog now-done-p)
  9097. (when org-blocker-hook
  9098. (let (org-blocked-by-checkboxes block-reason)
  9099. (setq org-last-todo-state-is-todo
  9100. (not (member this org-done-keywords)))
  9101. (unless (save-excursion
  9102. (save-match-data
  9103. (org-with-wide-buffer
  9104. (run-hook-with-args-until-failure
  9105. 'org-blocker-hook change-plist))))
  9106. (setq block-reason (if org-blocked-by-checkboxes
  9107. "contained checkboxes"
  9108. (format "\"%s\"" org-block-entry-blocking)))
  9109. (if (called-interactively-p 'interactive)
  9110. (user-error "TODO state change from %s to %s blocked (by %s)"
  9111. this org-state block-reason)
  9112. ;; Fail silently.
  9113. (message "TODO state change from %s to %s blocked (by %s)"
  9114. this org-state block-reason)
  9115. (throw 'exit nil)))))
  9116. (store-match-data match-data)
  9117. (replace-match next t t)
  9118. (cond ((equal this org-state)
  9119. (message "TODO state was already %s" (org-trim next)))
  9120. ((not (pos-visible-in-window-p hl-pos))
  9121. (message "TODO state changed to %s" (org-trim next))))
  9122. (unless head
  9123. (setq head (org-get-todo-sequence-head org-state)
  9124. ass (assoc head org-todo-kwd-alist)
  9125. interpret (nth 1 ass)
  9126. done-word (nth 3 ass)
  9127. final-done-word (nth 4 ass)))
  9128. (when (memq arg '(nextset previousset))
  9129. (message "Keyword-Set %d/%d: %s"
  9130. (- (length org-todo-sets) -1
  9131. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9132. (length org-todo-sets)
  9133. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9134. (setq org-last-todo-state-is-todo
  9135. (not (member org-state org-done-keywords)))
  9136. (setq now-done-p (and (member org-state org-done-keywords)
  9137. (not (member this org-done-keywords))))
  9138. (and logging (org-local-logging logging))
  9139. (when (or (and (or org-todo-log-states org-log-done)
  9140. (not (eq org-inhibit-logging t))
  9141. (not (memq arg '(nextset previousset))))
  9142. force-log)
  9143. ;; We need to look at recording a time and note.
  9144. (setq dolog (or (if force-log 'note)
  9145. (nth 1 (assoc org-state org-todo-log-states))
  9146. (nth 2 (assoc this org-todo-log-states))))
  9147. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9148. (setq dolog 'time))
  9149. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9150. (and org-state
  9151. (member org-state org-not-done-keywords)
  9152. (not (member this org-not-done-keywords))))
  9153. ;; This is now a todo state and was not one before
  9154. ;; If there was a CLOSED time stamp, get rid of it.
  9155. (org-add-planning-info nil nil 'closed))
  9156. (when (and now-done-p org-log-done)
  9157. ;; It is now done, and it was not done before.
  9158. (org-add-planning-info 'closed (org-current-effective-time))
  9159. (when (and (not dolog) (eq 'note org-log-done))
  9160. (org-add-log-setup 'done org-state this 'note)))
  9161. (when (and org-state dolog)
  9162. ;; This is a non-nil state, and we need to log it.
  9163. (org-add-log-setup 'state org-state this dolog)))
  9164. ;; Fixup tag positioning.
  9165. (org-todo-trigger-tag-changes org-state)
  9166. (when org-auto-align-tags (org-align-tags))
  9167. (when org-provide-todo-statistics
  9168. (org-update-parent-todo-statistics))
  9169. (when (bound-and-true-p org-clock-out-when-done)
  9170. (org-clock-out-if-current))
  9171. (run-hooks 'org-after-todo-state-change-hook)
  9172. (when (and arg (not (member org-state org-done-keywords)))
  9173. (setq head (org-get-todo-sequence-head org-state)))
  9174. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9175. ;; Do we need to trigger a repeat?
  9176. (when now-done-p
  9177. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9178. ;; This is for the agenda, take a snapshot of the headline.
  9179. (save-match-data
  9180. (setq org-agenda-headline-snapshot-before-repeat
  9181. (org-get-heading))))
  9182. (org-auto-repeat-maybe org-state))
  9183. ;; Fixup cursor location if close to the keyword.
  9184. (when (and (outline-on-heading-p)
  9185. (not (bolp))
  9186. (save-excursion (beginning-of-line 1)
  9187. (looking-at org-todo-line-regexp))
  9188. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9189. (goto-char (or (match-end 2) (match-end 1)))
  9190. (and (looking-at " ")
  9191. (not (looking-at " *:"))
  9192. (just-one-space)))
  9193. (when org-trigger-hook
  9194. (save-excursion
  9195. (run-hook-with-args 'org-trigger-hook change-plist)))
  9196. (when commentp (org-toggle-comment))))))))
  9197. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9198. "Block turning an entry into a TODO, using the hierarchy.
  9199. This checks whether the current task should be blocked from state
  9200. changes. Such blocking occurs when:
  9201. 1. The task has children which are not all in a completed state.
  9202. 2. A task has a parent with the property :ORDERED:, and there
  9203. are siblings prior to the current task with incomplete
  9204. status.
  9205. 3. The parent of the task is blocked because it has siblings that should
  9206. be done first, or is child of a block grandparent TODO entry."
  9207. (if (not org-enforce-todo-dependencies)
  9208. t ; if locally turned off don't block
  9209. (catch 'dont-block
  9210. ;; If this is not a todo state change, or if this entry is already DONE,
  9211. ;; do not block
  9212. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9213. (member (plist-get change-plist :from)
  9214. (cons 'done org-done-keywords))
  9215. (member (plist-get change-plist :to)
  9216. (cons 'todo org-not-done-keywords))
  9217. (not (plist-get change-plist :to)))
  9218. (throw 'dont-block t))
  9219. ;; If this task has children, and any are undone, it's blocked
  9220. (save-excursion
  9221. (org-back-to-heading t)
  9222. (let ((this-level (funcall outline-level)))
  9223. (outline-next-heading)
  9224. (let ((child-level (funcall outline-level)))
  9225. (while (and (not (eobp))
  9226. (> child-level this-level))
  9227. ;; this todo has children, check whether they are all
  9228. ;; completed
  9229. (when (and (not (org-entry-is-done-p))
  9230. (org-entry-is-todo-p))
  9231. (setq org-block-entry-blocking (org-get-heading))
  9232. (throw 'dont-block nil))
  9233. (outline-next-heading)
  9234. (setq child-level (funcall outline-level))))))
  9235. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9236. ;; any previous siblings are undone, it's blocked
  9237. (save-excursion
  9238. (org-back-to-heading t)
  9239. (let* ((pos (point))
  9240. (parent-pos (and (org-up-heading-safe) (point)))
  9241. (case-fold-search nil))
  9242. (unless parent-pos (throw 'dont-block t)) ; no parent
  9243. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9244. (forward-line 1)
  9245. (re-search-forward org-not-done-heading-regexp pos t))
  9246. (setq org-block-entry-blocking (match-string 0))
  9247. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9248. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9249. (while t
  9250. (goto-char parent-pos)
  9251. (unless (looking-at org-not-done-heading-regexp)
  9252. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9253. (setq pos (point))
  9254. (setq parent-pos (and (org-up-heading-safe) (point)))
  9255. (unless parent-pos (throw 'dont-block t)) ; no parent
  9256. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9257. (forward-line 1)
  9258. (re-search-forward org-not-done-heading-regexp pos t)
  9259. (setq org-block-entry-blocking (org-get-heading)))
  9260. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9261. (defcustom org-track-ordered-property-with-tag nil
  9262. "Should the ORDERED property also be shown as a tag?
  9263. The ORDERED property decides if an entry should require subtasks to be
  9264. completed in sequence. Since a property is not very visible, setting
  9265. this option means that toggling the ORDERED property with the command
  9266. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9267. not relevant for the behavior, but it makes things more visible.
  9268. Note that toggling the tag with tags commands will not change the property
  9269. and therefore not influence behavior!
  9270. This can be t, meaning the tag ORDERED should be used, It can also be a
  9271. string to select a different tag for this task."
  9272. :group 'org-todo
  9273. :type '(choice
  9274. (const :tag "No tracking" nil)
  9275. (const :tag "Track with ORDERED tag" t)
  9276. (string :tag "Use other tag")))
  9277. (defun org-toggle-ordered-property ()
  9278. "Toggle the ORDERED property of the current entry.
  9279. For better visibility, you can track the value of this property with a tag.
  9280. See variable `org-track-ordered-property-with-tag'."
  9281. (interactive)
  9282. (let* ((t1 org-track-ordered-property-with-tag)
  9283. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9284. (save-excursion
  9285. (org-back-to-heading)
  9286. (if (org-entry-get nil "ORDERED")
  9287. (progn
  9288. (org-delete-property "ORDERED")
  9289. (and tag (org-toggle-tag tag 'off))
  9290. (message "Subtasks can be completed in arbitrary order"))
  9291. (org-entry-put nil "ORDERED" "t")
  9292. (and tag (org-toggle-tag tag 'on))
  9293. (message "Subtasks must be completed in sequence")))))
  9294. (defun org-block-todo-from-checkboxes (change-plist)
  9295. "Block turning an entry into a TODO, using checkboxes.
  9296. This checks whether the current task should be blocked from state
  9297. changes because there are unchecked boxes in this entry."
  9298. (if (not org-enforce-todo-checkbox-dependencies)
  9299. t ; if locally turned off don't block
  9300. (catch 'dont-block
  9301. ;; If this is not a todo state change, or if this entry is already DONE,
  9302. ;; do not block
  9303. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9304. (member (plist-get change-plist :from)
  9305. (cons 'done org-done-keywords))
  9306. (member (plist-get change-plist :to)
  9307. (cons 'todo org-not-done-keywords))
  9308. (not (plist-get change-plist :to)))
  9309. (throw 'dont-block t))
  9310. ;; If this task has checkboxes that are not checked, it's blocked
  9311. (save-excursion
  9312. (org-back-to-heading t)
  9313. (let ((beg (point)) end)
  9314. (outline-next-heading)
  9315. (setq end (point))
  9316. (goto-char beg)
  9317. (when (org-list-search-forward
  9318. (concat (org-item-beginning-re)
  9319. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9320. "\\[[- ]\\]")
  9321. end t)
  9322. (when (boundp 'org-blocked-by-checkboxes)
  9323. (setq org-blocked-by-checkboxes t))
  9324. (throw 'dont-block nil))))
  9325. t))) ; do not block
  9326. (defun org-entry-blocked-p ()
  9327. "Non-nil if entry at point is blocked."
  9328. (and (not (org-entry-get nil "NOBLOCKING"))
  9329. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9330. (not (run-hook-with-args-until-failure
  9331. 'org-blocker-hook
  9332. (list :type 'todo-state-change
  9333. :position (point)
  9334. :from 'todo
  9335. :to 'done)))))
  9336. (defun org-update-statistics-cookies (all)
  9337. "Update the statistics cookie, either from TODO or from checkboxes.
  9338. This should be called with the cursor in a line with a statistics
  9339. cookie. When called with a \\[universal-argument] prefix, update
  9340. all statistics cookies in the buffer."
  9341. (interactive "P")
  9342. (if all
  9343. (progn
  9344. (org-update-checkbox-count 'all)
  9345. (org-map-entries 'org-update-parent-todo-statistics))
  9346. (if (not (org-at-heading-p))
  9347. (org-update-checkbox-count)
  9348. (let ((pos (point-marker))
  9349. end l1 l2)
  9350. (ignore-errors (org-back-to-heading t))
  9351. (if (not (org-at-heading-p))
  9352. (org-update-checkbox-count)
  9353. (setq l1 (org-outline-level))
  9354. (setq end (save-excursion
  9355. (outline-next-heading)
  9356. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9357. (point)))
  9358. (if (and (save-excursion
  9359. (re-search-forward
  9360. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9361. (not (save-excursion (re-search-forward
  9362. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9363. (org-update-checkbox-count)
  9364. (if (and l2 (> l2 l1))
  9365. (progn
  9366. (goto-char end)
  9367. (org-update-parent-todo-statistics))
  9368. (goto-char pos)
  9369. (beginning-of-line 1)
  9370. (while (re-search-forward
  9371. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9372. (point-at-eol) t)
  9373. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9374. (goto-char pos)
  9375. (move-marker pos nil)))))
  9376. (defvar org-entry-property-inherited-from) ;; defined below
  9377. (defun org-update-parent-todo-statistics ()
  9378. "Update any statistics cookie in the parent of the current headline.
  9379. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9380. the entire subtree and this will travel up the hierarchy and update
  9381. statistics everywhere."
  9382. (let* ((prop (save-excursion (org-up-heading-safe)
  9383. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9384. (recursive (or (not org-hierarchical-todo-statistics)
  9385. (and prop (string-match "\\<recursive\\>" prop))))
  9386. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9387. 0))
  9388. (first t)
  9389. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9390. level ltoggle l1 new ndel
  9391. (cnt-all 0) (cnt-done 0) is-percent kwd
  9392. checkbox-beg cookie-present)
  9393. (catch 'exit
  9394. (save-excursion
  9395. (beginning-of-line 1)
  9396. (setq ltoggle (funcall outline-level))
  9397. ;; Three situations are to consider:
  9398. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9399. ;; to the top-level ancestor on the headline;
  9400. ;; 2. If parent has "recursive" property, repeat up to the
  9401. ;; headline setting that property, taking inheritance into
  9402. ;; account;
  9403. ;; 3. Else, move up to direct parent and proceed only once.
  9404. (while (and (setq level (org-up-heading-safe))
  9405. (or recursive first)
  9406. (>= (point) lim))
  9407. (setq first nil cookie-present nil)
  9408. (unless (and level
  9409. (not (string-match
  9410. "\\<checkbox\\>"
  9411. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9412. "")))))
  9413. (throw 'exit nil))
  9414. (while (re-search-forward box-re (point-at-eol) t)
  9415. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9416. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9417. (save-match-data
  9418. (unless (outline-next-heading) (throw 'exit nil))
  9419. (while (and (looking-at org-complex-heading-regexp)
  9420. (> (setq l1 (length (match-string 1))) level))
  9421. (setq kwd (and (or recursive (= l1 ltoggle))
  9422. (match-string 2)))
  9423. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9424. (and (eq org-provide-todo-statistics t)
  9425. (or (member kwd org-done-keywords)))
  9426. (and (listp org-provide-todo-statistics)
  9427. (stringp (car org-provide-todo-statistics))
  9428. (or (member kwd org-provide-todo-statistics)
  9429. (member kwd org-done-keywords)))
  9430. (and (listp org-provide-todo-statistics)
  9431. (listp (car org-provide-todo-statistics))
  9432. (or (member kwd (car org-provide-todo-statistics))
  9433. (and (member kwd org-done-keywords)
  9434. (member kwd (cadr org-provide-todo-statistics))))))
  9435. (setq cnt-all (1+ cnt-all))
  9436. (and (eq org-provide-todo-statistics t)
  9437. kwd
  9438. (setq cnt-all (1+ cnt-all))))
  9439. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9440. (member kwd org-done-keywords))
  9441. (and (listp org-provide-todo-statistics)
  9442. (listp (car org-provide-todo-statistics))
  9443. (member kwd org-done-keywords)
  9444. (member kwd (cadr org-provide-todo-statistics)))
  9445. (and (listp org-provide-todo-statistics)
  9446. (stringp (car org-provide-todo-statistics))
  9447. (member kwd org-done-keywords)))
  9448. (setq cnt-done (1+ cnt-done)))
  9449. (outline-next-heading)))
  9450. (setq new
  9451. (if is-percent
  9452. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9453. (max 1 cnt-all)))
  9454. (format "[%d/%d]" cnt-done cnt-all))
  9455. ndel (- (match-end 0) checkbox-beg))
  9456. (goto-char checkbox-beg)
  9457. (insert new)
  9458. (delete-region (point) (+ (point) ndel))
  9459. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9460. (when cookie-present
  9461. (run-hook-with-args 'org-after-todo-statistics-hook
  9462. cnt-done (- cnt-all cnt-done))))))
  9463. (run-hooks 'org-todo-statistics-hook)))
  9464. (defvar org-after-todo-statistics-hook nil
  9465. "Hook that is called after a TODO statistics cookie has been updated.
  9466. Each function is called with two arguments: the number of not-done entries
  9467. and the number of done entries.
  9468. For example, the following function, when added to this hook, will switch
  9469. an entry to DONE when all children are done, and back to TODO when new
  9470. entries are set to a TODO status. Note that this hook is only called
  9471. when there is a statistics cookie in the headline!
  9472. (defun org-summary-todo (n-done n-not-done)
  9473. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9474. (let (org-log-done org-log-states) ; turn off logging
  9475. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9476. ")
  9477. (defvar org-todo-statistics-hook nil
  9478. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9479. This hook runs even if there is no statistics cookie present, in which case
  9480. `org-after-todo-statistics-hook' would not run.")
  9481. (defun org-todo-trigger-tag-changes (state)
  9482. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9483. (let ((l org-todo-state-tags-triggers)
  9484. changes)
  9485. (when (or (not state) (equal state ""))
  9486. (setq changes (append changes (cdr (assoc "" l)))))
  9487. (when (and (stringp state) (> (length state) 0))
  9488. (setq changes (append changes (cdr (assoc state l)))))
  9489. (when (member state org-not-done-keywords)
  9490. (setq changes (append changes (cdr (assq 'todo l)))))
  9491. (when (member state org-done-keywords)
  9492. (setq changes (append changes (cdr (assq 'done l)))))
  9493. (dolist (c changes)
  9494. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9495. (defun org-local-logging (value)
  9496. "Get logging settings from a property VALUE."
  9497. ;; Directly set the variables, they are already local.
  9498. (setq org-log-done nil
  9499. org-log-repeat nil
  9500. org-todo-log-states nil)
  9501. (dolist (w (split-string value))
  9502. (let (a)
  9503. (cond
  9504. ((setq a (assoc w org-startup-options))
  9505. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9506. (set (nth 1 a) (nth 2 a))))
  9507. ((setq a (org-extract-log-state-settings w))
  9508. (and (member (car a) org-todo-keywords-1)
  9509. (push a org-todo-log-states)))))))
  9510. (defun org-get-todo-sequence-head (kwd)
  9511. "Return the head of the TODO sequence to which KWD belongs.
  9512. If KWD is not set, check if there is a text property remembering the
  9513. right sequence."
  9514. (let (p)
  9515. (cond
  9516. ((not kwd)
  9517. (or (get-text-property (point-at-bol) 'org-todo-head)
  9518. (progn
  9519. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9520. nil (point-at-eol)))
  9521. (get-text-property p 'org-todo-head))))
  9522. ((not (member kwd org-todo-keywords-1))
  9523. (car org-todo-keywords-1))
  9524. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9525. (defun org-fast-todo-selection (&optional current-state)
  9526. "Fast TODO keyword selection with single keys.
  9527. Returns the new TODO keyword, or nil if no state change should occur.
  9528. When CURRENT-STATE is given and selection letters are not unique globally,
  9529. prefer a state in the current sequence over on in another sequence."
  9530. (let* ((fulltable org-todo-key-alist)
  9531. (head (org-get-todo-sequence-head current-state))
  9532. (done-keywords org-done-keywords) ;; needed for the faces.
  9533. (maxlen (apply 'max (mapcar
  9534. (lambda (x)
  9535. (if (stringp (car x)) (string-width (car x)) 0))
  9536. fulltable)))
  9537. (expert (equal org-use-fast-todo-selection 'expert))
  9538. (prompt "")
  9539. (fwidth (+ maxlen 3 1 3))
  9540. (ncol (/ (- (window-width) 4) fwidth))
  9541. tg cnt e c tbl subtable
  9542. groups ingroup in-current-sequence)
  9543. (save-excursion
  9544. (save-window-excursion
  9545. (if expert
  9546. (set-buffer (get-buffer-create " *Org todo*"))
  9547. (delete-other-windows)
  9548. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9549. (org-switch-to-buffer-other-window " *Org todo*"))
  9550. (erase-buffer)
  9551. (setq-local org-done-keywords done-keywords)
  9552. (setq tbl fulltable cnt 0)
  9553. (while (setq e (pop tbl))
  9554. (cond
  9555. ((equal e '(:startgroup))
  9556. (push '() groups) (setq ingroup t)
  9557. (unless (= cnt 0)
  9558. (setq cnt 0)
  9559. (insert "\n"))
  9560. (setq prompt (concat prompt "{"))
  9561. (insert "{ "))
  9562. ((equal e '(:endgroup))
  9563. (setq ingroup nil cnt 0 in-current-sequence nil)
  9564. (setq prompt (concat prompt "}"))
  9565. (insert "}\n"))
  9566. ((equal e '(:newline))
  9567. (unless (= cnt 0)
  9568. (setq cnt 0)
  9569. (insert "\n")
  9570. (setq e (car tbl))
  9571. (while (equal (car tbl) '(:newline))
  9572. (insert "\n")
  9573. (setq tbl (cdr tbl)))))
  9574. (t
  9575. (setq tg (car e) c (cdr e))
  9576. (if (equal tg head) (setq in-current-sequence t))
  9577. (when ingroup (push tg (car groups)))
  9578. (when in-current-sequence (push e subtable))
  9579. (setq tg (org-add-props tg nil 'face
  9580. (org-get-todo-face tg)))
  9581. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9582. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9583. (insert "[" c "] " tg (make-string
  9584. (- fwidth 4 (length tg)) ?\ ))
  9585. (when (and (= (setq cnt (1+ cnt)) ncol)
  9586. ;; Avoid lines with just a closing delimiter.
  9587. (not (equal (car tbl) '(:endgroup))))
  9588. (insert "\n")
  9589. (when ingroup (insert " "))
  9590. (setq cnt 0)))))
  9591. (insert "\n")
  9592. (goto-char (point-min))
  9593. (unless expert (org-fit-window-to-buffer))
  9594. (message (concat "[a-z..]:Set [SPC]:clear"
  9595. (if expert (concat "\n" prompt) "")))
  9596. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9597. (setq subtable (nreverse subtable))
  9598. (cond
  9599. ((or (= c ?\C-g)
  9600. (and (= c ?q) (not (rassoc c fulltable))))
  9601. (setq quit-flag t))
  9602. ((= c ?\ ) nil)
  9603. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9604. tg (car e))
  9605. tg)
  9606. (t (setq quit-flag t)))))))
  9607. (defun org-entry-is-todo-p ()
  9608. (member (org-get-todo-state) org-not-done-keywords))
  9609. (defun org-entry-is-done-p ()
  9610. (member (org-get-todo-state) org-done-keywords))
  9611. (defun org-get-todo-state ()
  9612. "Return the TODO keyword of the current subtree."
  9613. (save-excursion
  9614. (org-back-to-heading t)
  9615. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9616. (match-end 2)
  9617. (match-string 2))))
  9618. (defun org-at-date-range-p (&optional inactive-ok)
  9619. "Non-nil if point is inside a date range.
  9620. When optional argument INACTIVE-OK is non-nil, also consider
  9621. inactive time ranges.
  9622. When this function returns a non-nil value, match data is set
  9623. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9624. on INACTIVE-OK."
  9625. (interactive)
  9626. (save-excursion
  9627. (catch 'exit
  9628. (let ((pos (point)))
  9629. (skip-chars-backward "^[<\r\n")
  9630. (skip-chars-backward "<[")
  9631. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9632. (>= (match-end 0) pos)
  9633. (throw 'exit t))
  9634. (skip-chars-backward "^<[\r\n")
  9635. (skip-chars-backward "<[")
  9636. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9637. (>= (match-end 0) pos)
  9638. (throw 'exit t)))
  9639. nil)))
  9640. (defun org-get-repeat (&optional timestamp)
  9641. "Check if there is a time-stamp with repeater in this entry.
  9642. Return the repeater, as a string, or nil. Also return nil when
  9643. this function is called before first heading.
  9644. When optional argument TIMESTAMP is a string, extract the
  9645. repeater from there instead."
  9646. (save-match-data
  9647. (cond (timestamp
  9648. (and (string-match org-repeat-re timestamp)
  9649. (match-string-no-properties 1 timestamp)))
  9650. ((org-before-first-heading-p) nil)
  9651. (t
  9652. (save-excursion
  9653. (org-back-to-heading t)
  9654. (let ((end (org-entry-end-position)))
  9655. (catch :repeat
  9656. (while (re-search-forward org-repeat-re end t)
  9657. (when (save-match-data (org-at-timestamp-p 'agenda))
  9658. (throw :repeat (match-string-no-properties 1)))))))))))
  9659. (defvar org-last-changed-timestamp)
  9660. (defvar org-last-inserted-timestamp)
  9661. (defvar org-log-post-message)
  9662. (defvar org-log-note-purpose)
  9663. (defvar org-log-note-how nil)
  9664. (defvar org-log-note-extra)
  9665. (defun org-auto-repeat-maybe (done-word)
  9666. "Check if the current headline contains a repeated time-stamp.
  9667. If yes, set TODO state back to what it was and change the base date
  9668. of repeating deadline/scheduled time stamps to new date.
  9669. This function is run automatically after each state change to a DONE state."
  9670. (let* ((repeat (org-get-repeat))
  9671. (aa (assoc org-last-state org-todo-kwd-alist))
  9672. (interpret (nth 1 aa))
  9673. (head (nth 2 aa))
  9674. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9675. (msg "Entry repeats: ")
  9676. (org-log-done nil)
  9677. (org-todo-log-states nil)
  9678. (end (copy-marker (org-entry-end-position))))
  9679. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9680. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9681. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9682. (and (stringp org-todo-repeat-to-state)
  9683. org-todo-repeat-to-state)
  9684. (and org-todo-repeat-to-state org-last-state))))
  9685. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9686. to-state)
  9687. ((eq interpret 'type) org-last-state)
  9688. (head)
  9689. (t 'none))))
  9690. (org-back-to-heading t)
  9691. (org-add-planning-info nil nil 'closed)
  9692. ;; When `org-log-repeat' is non-nil or entry contains
  9693. ;; a clock, set LAST_REPEAT property.
  9694. (when (or org-log-repeat
  9695. (catch :clock
  9696. (save-excursion
  9697. (while (re-search-forward org-clock-line-re end t)
  9698. (when (org-at-clock-log-p) (throw :clock t))))))
  9699. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9700. (org-time-stamp-format t t))))
  9701. (when org-log-repeat
  9702. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9703. (memq 'org-add-log-note post-command-hook))
  9704. ;; We are already setup for some record.
  9705. (when (eq org-log-repeat 'note)
  9706. ;; Make sure we take a note, not only a time stamp.
  9707. (setq org-log-note-how 'note))
  9708. ;; Set up for taking a record.
  9709. (org-add-log-setup 'state
  9710. (or done-word (car org-done-keywords))
  9711. org-last-state
  9712. org-log-repeat)))
  9713. ;; Time-stamps without a repeater are usually skipped. However,
  9714. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9715. ;; longer relevant.
  9716. (save-excursion
  9717. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9718. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9719. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9720. ;; Update every time-stamp with a repeater in the entry.
  9721. (let ((planning-re (regexp-opt
  9722. (list org-scheduled-string org-deadline-string))))
  9723. (while (re-search-forward org-repeat-re end t)
  9724. (let* ((ts (match-string 0))
  9725. (type (if (not (org-at-planning-p)) "Plain:"
  9726. (save-excursion
  9727. (re-search-backward
  9728. planning-re (line-beginning-position) t)
  9729. (match-string 0)))))
  9730. (when (and (org-at-timestamp-p 'agenda)
  9731. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9732. (let ((n (string-to-number (match-string 2 ts)))
  9733. (what (match-string 3 ts)))
  9734. (when (equal what "w") (setq n (* n 7) what "d"))
  9735. (when (and (equal what "h")
  9736. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9737. ts)))
  9738. (user-error
  9739. "Cannot repeat in %d hour(s) because no hour has been set"
  9740. n))
  9741. ;; Preparation, see if we need to modify the start
  9742. ;; date for the change.
  9743. (when (match-end 1)
  9744. (let ((time (save-match-data (org-time-string-to-time ts)))
  9745. (repeater-type (match-string 1 ts)))
  9746. (cond
  9747. ((equal "." repeater-type)
  9748. ;; Shift starting date to today.
  9749. (org-timestamp-change (- (org-today) (time-to-days time))
  9750. 'day))
  9751. ((equal "+" repeater-type)
  9752. (let ((nshiftmax 10)
  9753. (nshift 0))
  9754. (while (or (= nshift 0)
  9755. (not (time-less-p (current-time) time)))
  9756. (when (= nshiftmax (cl-incf nshift))
  9757. (or (y-or-n-p
  9758. (format "%d repeater intervals were not \
  9759. enough to shift date past today. Continue? "
  9760. nshift))
  9761. (user-error "Abort")))
  9762. (org-timestamp-change n (cdr (assoc what whata)))
  9763. (org-in-regexp org-ts-regexp3)
  9764. (setq ts (match-string 1))
  9765. (setq time
  9766. (save-match-data
  9767. (org-time-string-to-time ts)))))
  9768. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9769. ;; Rematch, so that we have everything in place
  9770. ;; for the real shift.
  9771. (org-in-regexp org-ts-regexp3)
  9772. (setq ts (match-string 1))
  9773. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9774. ts)))))
  9775. (save-excursion
  9776. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9777. (setq msg
  9778. (concat msg type " " org-last-changed-timestamp " ")))))))
  9779. (run-hooks 'org-todo-repeat-hook)
  9780. (setq org-log-post-message msg)
  9781. (message msg))))
  9782. (defun org-show-todo-tree (arg)
  9783. "Make a compact tree which shows all headlines marked with TODO.
  9784. The tree will show the lines where the regexp matches, and all higher
  9785. headlines above the match.
  9786. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9787. With a numeric prefix N, construct a sparse tree for the Nth element
  9788. of `org-todo-keywords-1'."
  9789. (interactive "P")
  9790. (let ((case-fold-search nil)
  9791. (kwd-re
  9792. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9793. ((equal arg '(4))
  9794. (let ((kwd
  9795. (completing-read "Keyword (or KWD1|KWD2|...): "
  9796. (mapcar #'list org-todo-keywords-1))))
  9797. (concat "\\("
  9798. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9799. "\\)\\>")))
  9800. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9801. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9802. org-todo-keywords-1)))
  9803. (t (user-error "Invalid prefix argument: %s" arg)))))
  9804. (message "%d TODO entries found"
  9805. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9806. (defun org--deadline-or-schedule (arg type time)
  9807. "Insert DEADLINE or SCHEDULE information in current entry.
  9808. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9809. `org-schedule' for information about ARG and TIME arguments."
  9810. (let* ((deadline? (eq type 'deadline))
  9811. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9812. (log (if deadline? org-log-redeadline org-log-reschedule))
  9813. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9814. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9815. ;; Save repeater cookie from either TIME or current scheduled
  9816. ;; time stamp. We are going to insert it back at the end of
  9817. ;; the process.
  9818. (repeater (or (and (org-string-nw-p time)
  9819. ;; We use `org-repeat-re' because we need
  9820. ;; to tell the difference between a real
  9821. ;; repeater and a time delta, e.g. "+2d".
  9822. (string-match org-repeat-re time)
  9823. (match-string 1 time))
  9824. (and (org-string-nw-p old-date)
  9825. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9826. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9827. old-date)
  9828. (match-string 1 old-date)))))
  9829. (pcase arg
  9830. (`(4)
  9831. (if (not old-date)
  9832. (message (if deadline? "Entry had no deadline to remove"
  9833. "Entry was not scheduled"))
  9834. (when (and old-date log)
  9835. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9836. nil old-date log))
  9837. (org-remove-timestamp-with-keyword keyword)
  9838. (message (if deadline? "Entry no longer has a deadline."
  9839. "Entry is no longer scheduled."))))
  9840. (`(16)
  9841. (save-excursion
  9842. (org-back-to-heading t)
  9843. (let ((regexp (if deadline? org-deadline-time-regexp
  9844. org-scheduled-time-regexp)))
  9845. (if (not (re-search-forward regexp (line-end-position 2) t))
  9846. (user-error (if deadline? "No deadline information to update"
  9847. "No scheduled information to update"))
  9848. (let* ((rpl0 (match-string 1))
  9849. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9850. (msg (if deadline? "Warn starting from" "Delay until")))
  9851. (replace-match
  9852. (concat keyword
  9853. " <" rpl
  9854. (format " -%dd"
  9855. (abs (- (time-to-days
  9856. (save-match-data
  9857. (org-read-date
  9858. nil t nil msg old-date-time)))
  9859. (time-to-days old-date-time))))
  9860. ">") t t))))))
  9861. (_
  9862. (org-add-planning-info type time 'closed)
  9863. (when (and old-date
  9864. log
  9865. (not (equal old-date org-last-inserted-timestamp)))
  9866. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9867. org-last-inserted-timestamp
  9868. old-date
  9869. log))
  9870. (when repeater
  9871. (save-excursion
  9872. (org-back-to-heading t)
  9873. (when (re-search-forward
  9874. (concat keyword " " org-last-inserted-timestamp)
  9875. (line-end-position 2)
  9876. t)
  9877. (goto-char (1- (match-end 0)))
  9878. (insert " " repeater)
  9879. (setq org-last-inserted-timestamp
  9880. (concat (substring org-last-inserted-timestamp 0 -1)
  9881. " " repeater
  9882. (substring org-last-inserted-timestamp -1))))))
  9883. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9884. org-last-inserted-timestamp)))))
  9885. (defun org-deadline (arg &optional time)
  9886. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9887. With one universal prefix argument, remove any deadline from the item.
  9888. With two universal prefix arguments, prompt for a warning delay.
  9889. With argument TIME, set the deadline at the corresponding date. TIME
  9890. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9891. (interactive "P")
  9892. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9893. (org-map-entries
  9894. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9895. nil
  9896. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9897. 'region-start-level
  9898. 'region)
  9899. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9900. (org--deadline-or-schedule arg 'deadline time)))
  9901. (defun org-schedule (arg &optional time)
  9902. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9903. With one universal prefix argument, remove any scheduling date from the item.
  9904. With two universal prefix arguments, prompt for a delay cookie.
  9905. With argument TIME, scheduled at the corresponding date. TIME can
  9906. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9907. (interactive "P")
  9908. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9909. (org-map-entries
  9910. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9911. nil
  9912. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9913. 'region-start-level
  9914. 'region)
  9915. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9916. (org--deadline-or-schedule arg 'scheduled time)))
  9917. (defun org-get-scheduled-time (pom &optional inherit)
  9918. "Get the scheduled time as a time tuple, of a format suitable
  9919. for calling org-schedule with, or if there is no scheduling,
  9920. returns nil."
  9921. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9922. (when time
  9923. (apply 'encode-time (org-parse-time-string time)))))
  9924. (defun org-get-deadline-time (pom &optional inherit)
  9925. "Get the deadline as a time tuple, of a format suitable for
  9926. calling org-deadline with, or if there is no scheduling, returns
  9927. nil."
  9928. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9929. (when time
  9930. (apply 'encode-time (org-parse-time-string time)))))
  9931. (defun org-remove-timestamp-with-keyword (keyword)
  9932. "Remove all time stamps with KEYWORD in the current entry."
  9933. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9934. beg)
  9935. (save-excursion
  9936. (org-back-to-heading t)
  9937. (setq beg (point))
  9938. (outline-next-heading)
  9939. (while (re-search-backward re beg t)
  9940. (replace-match "")
  9941. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9942. (equal (char-before) ?\ ))
  9943. (backward-delete-char 1)
  9944. (when (string-match "^[ \t]*$" (buffer-substring
  9945. (point-at-bol) (point-at-eol)))
  9946. (delete-region (point-at-bol)
  9947. (min (point-max) (1+ (point-at-eol))))))))))
  9948. (defvar org-time-was-given) ; dynamically scoped parameter
  9949. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9950. (defun org-at-planning-p ()
  9951. "Non-nil when point is on a planning info line."
  9952. ;; This is as accurate and faster than `org-element-at-point' since
  9953. ;; planning info location is fixed in the section.
  9954. (org-with-wide-buffer
  9955. (beginning-of-line)
  9956. (and (looking-at-p org-planning-line-re)
  9957. (eq (point)
  9958. (ignore-errors
  9959. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9960. (org-back-to-heading t)
  9961. (org-with-limited-levels (org-back-to-heading t)))
  9962. (line-beginning-position 2))))))
  9963. (defun org-add-planning-info (what &optional time &rest remove)
  9964. "Insert new timestamp with keyword in the planning line.
  9965. WHAT indicates what kind of time stamp to add. It is a symbol
  9966. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9967. the time to use. If none is given, the user is prompted for
  9968. a date. REMOVE indicates what kind of entries to remove. An old
  9969. WHAT entry will also be removed."
  9970. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9971. (catch 'exit
  9972. (when (and (memq what '(scheduled deadline))
  9973. (or (not time)
  9974. (and (stringp time)
  9975. (string-match "^[-+]+[0-9]" time))))
  9976. ;; Try to get a default date/time from existing timestamp
  9977. (save-excursion
  9978. (org-back-to-heading t)
  9979. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9980. (when (re-search-forward (if (eq what 'scheduled)
  9981. org-scheduled-time-regexp
  9982. org-deadline-time-regexp)
  9983. end t)
  9984. (setq ts (match-string 1)
  9985. default-time (apply 'encode-time (org-parse-time-string ts))
  9986. default-input (and ts (org-get-compact-tod ts)))))))
  9987. (when what
  9988. (setq time
  9989. (if (stringp time)
  9990. ;; This is a string (relative or absolute), set
  9991. ;; proper date.
  9992. (apply #'encode-time
  9993. (org-read-date-analyze
  9994. time default-time (decode-time default-time)))
  9995. ;; If necessary, get the time from the user
  9996. (or time (org-read-date nil 'to-time nil
  9997. (cl-case what
  9998. (deadline "DEADLINE")
  9999. (scheduled "SCHEDULED")
  10000. (otherwise nil))
  10001. default-time default-input)))))
  10002. (org-with-wide-buffer
  10003. (org-back-to-heading t)
  10004. (forward-line)
  10005. (unless (bolp) (insert "\n"))
  10006. (cond ((looking-at-p org-planning-line-re)
  10007. ;; Move to current indentation.
  10008. (skip-chars-forward " \t")
  10009. ;; Check if we have to remove something.
  10010. (dolist (type (if what (cons what remove) remove))
  10011. (save-excursion
  10012. (when (re-search-forward
  10013. (cl-case type
  10014. (closed org-closed-time-regexp)
  10015. (deadline org-deadline-time-regexp)
  10016. (scheduled org-scheduled-time-regexp)
  10017. (otherwise
  10018. (error "Invalid planning type: %s" type)))
  10019. (line-end-position) t)
  10020. ;; Delete until next keyword or end of line.
  10021. (delete-region
  10022. (match-beginning 0)
  10023. (if (re-search-forward org-keyword-time-not-clock-regexp
  10024. (line-end-position)
  10025. t)
  10026. (match-beginning 0)
  10027. (line-end-position))))))
  10028. ;; If there is nothing more to add and no more keyword
  10029. ;; is left, remove the line completely.
  10030. (if (and (looking-at-p "[ \t]*$") (not what))
  10031. (delete-region (line-beginning-position)
  10032. (line-beginning-position 2))
  10033. ;; If we removed last keyword, do not leave trailing
  10034. ;; white space at the end of line.
  10035. (let ((p (point)))
  10036. (save-excursion
  10037. (end-of-line)
  10038. (unless (= (skip-chars-backward " \t" p) 0)
  10039. (delete-region (point) (line-end-position)))))))
  10040. ((not what) (throw 'exit nil)) ; Nothing to do.
  10041. (t (insert-before-markers "\n")
  10042. (backward-char 1)
  10043. (when org-adapt-indentation
  10044. (indent-to-column (1+ (org-outline-level))))))
  10045. (when what
  10046. ;; Insert planning keyword.
  10047. (insert (cl-case what
  10048. (closed org-closed-string)
  10049. (deadline org-deadline-string)
  10050. (scheduled org-scheduled-string)
  10051. (otherwise (error "Invalid planning type: %s" what)))
  10052. " ")
  10053. ;; Insert associated timestamp.
  10054. (let ((ts (org-insert-time-stamp
  10055. time
  10056. (or org-time-was-given
  10057. (and (eq what 'closed) org-log-done-with-time))
  10058. (eq what 'closed)
  10059. nil nil (list org-end-time-was-given))))
  10060. (unless (eolp) (insert " "))
  10061. ts))))))
  10062. (defvar org-log-note-marker (make-marker)
  10063. "Marker pointing at the entry where the note is to be inserted.")
  10064. (defvar org-log-note-purpose nil)
  10065. (defvar org-log-note-state nil)
  10066. (defvar org-log-note-previous-state nil)
  10067. (defvar org-log-note-extra nil)
  10068. (defvar org-log-note-window-configuration nil)
  10069. (defvar org-log-note-return-to (make-marker))
  10070. (defvar org-log-note-effective-time nil
  10071. "Remembered current time so that dynamically scoped
  10072. `org-extend-today-until' affects timestamps in state change log")
  10073. (defvar org-log-post-message nil
  10074. "Message to be displayed after a log note has been stored.
  10075. The auto-repeater uses this.")
  10076. (defun org-add-note ()
  10077. "Add a note to the current entry.
  10078. This is done in the same way as adding a state change note."
  10079. (interactive)
  10080. (org-add-log-setup 'note))
  10081. (defun org-log-beginning (&optional create)
  10082. "Return expected start of log notes in current entry.
  10083. When optional argument CREATE is non-nil, the function creates
  10084. a drawer to store notes, if necessary. Returned position ignores
  10085. narrowing."
  10086. (org-with-wide-buffer
  10087. (let ((drawer (org-log-into-drawer)))
  10088. (cond
  10089. (drawer
  10090. (org-end-of-meta-data)
  10091. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10092. (end (if (org-at-heading-p) (point)
  10093. (save-excursion (outline-next-heading) (point))))
  10094. (case-fold-search t))
  10095. (catch 'exit
  10096. ;; Try to find existing drawer.
  10097. (while (re-search-forward regexp end t)
  10098. (let ((element (org-element-at-point)))
  10099. (when (eq (org-element-type element) 'drawer)
  10100. (let ((cend (org-element-property :contents-end element)))
  10101. (when (and (not org-log-states-order-reversed) cend)
  10102. (goto-char cend)))
  10103. (throw 'exit nil))))
  10104. ;; No drawer found. Create one, if permitted.
  10105. (when create
  10106. (unless (bolp) (insert "\n"))
  10107. (let ((beg (point)))
  10108. (insert ":" drawer ":\n:END:\n")
  10109. (org-indent-region beg (point))
  10110. (org-flag-region
  10111. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10112. (end-of-line -1)))))
  10113. (t
  10114. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10115. (skip-chars-forward " \t\n")
  10116. (beginning-of-line)
  10117. (unless org-log-states-order-reversed
  10118. (org-skip-over-state-notes)
  10119. (skip-chars-backward " \t\n")
  10120. (forward-line)))))
  10121. (if (bolp) (point) (line-beginning-position 2))))
  10122. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10123. "Set up the post command hook to take a note.
  10124. If this is about to TODO state change, the new state is expected in STATE.
  10125. HOW is an indicator what kind of note should be created.
  10126. EXTRA is additional text that will be inserted into the notes buffer."
  10127. (move-marker org-log-note-marker (point))
  10128. (setq org-log-note-purpose purpose
  10129. org-log-note-state state
  10130. org-log-note-previous-state prev-state
  10131. org-log-note-how how
  10132. org-log-note-extra extra
  10133. org-log-note-effective-time (org-current-effective-time))
  10134. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10135. (defun org-skip-over-state-notes ()
  10136. "Skip past the list of State notes in an entry."
  10137. (when (ignore-errors (goto-char (org-in-item-p)))
  10138. (let* ((struct (org-list-struct))
  10139. (prevs (org-list-prevs-alist struct))
  10140. (regexp
  10141. (concat "[ \t]*- +"
  10142. (replace-regexp-in-string
  10143. " +" " +"
  10144. (org-replace-escapes
  10145. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10146. `(("%d" . ,org-ts-regexp-inactive)
  10147. ("%D" . ,org-ts-regexp)
  10148. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10149. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10150. ("%t" . ,org-ts-regexp-inactive)
  10151. ("%T" . ,org-ts-regexp)
  10152. ("%u" . ".*?")
  10153. ("%U" . ".*?")))))))
  10154. (while (looking-at-p regexp)
  10155. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10156. (org-list-get-item-end (point) struct)))))))
  10157. (defun org-add-log-note (&optional _purpose)
  10158. "Pop up a window for taking a note, and add this note later."
  10159. (remove-hook 'post-command-hook 'org-add-log-note)
  10160. (setq org-log-note-window-configuration (current-window-configuration))
  10161. (delete-other-windows)
  10162. (move-marker org-log-note-return-to (point))
  10163. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10164. (goto-char org-log-note-marker)
  10165. (org-switch-to-buffer-other-window "*Org Note*")
  10166. (erase-buffer)
  10167. (if (memq org-log-note-how '(time state))
  10168. (org-store-log-note)
  10169. (let ((org-inhibit-startup t)) (org-mode))
  10170. (insert (format "# Insert note for %s.
  10171. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10172. (cl-case org-log-note-purpose
  10173. (clock-out "stopped clock")
  10174. (done "closed todo item")
  10175. (reschedule "rescheduling")
  10176. (delschedule "no longer scheduled")
  10177. (redeadline "changing deadline")
  10178. (deldeadline "removing deadline")
  10179. (refile "refiling")
  10180. (note "this entry")
  10181. (state
  10182. (format "state change from \"%s\" to \"%s\""
  10183. (or org-log-note-previous-state "")
  10184. (or org-log-note-state "")))
  10185. (t (error "This should not happen")))))
  10186. (when org-log-note-extra (insert org-log-note-extra))
  10187. (setq-local org-finish-function 'org-store-log-note)
  10188. (run-hooks 'org-log-buffer-setup-hook)))
  10189. (defvar org-note-abort nil) ; dynamically scoped
  10190. (defun org-store-log-note ()
  10191. "Finish taking a log note, and insert it to where it belongs."
  10192. (let ((txt (prog1 (buffer-string)
  10193. (kill-buffer)))
  10194. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10195. lines)
  10196. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10197. (setq txt (replace-match "" t t txt)))
  10198. (when (string-match "\\s-+\\'" txt)
  10199. (setq txt (replace-match "" t t txt)))
  10200. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10201. (when (org-string-nw-p note)
  10202. (setq note
  10203. (org-replace-escapes
  10204. note
  10205. (list (cons "%u" (user-login-name))
  10206. (cons "%U" user-full-name)
  10207. (cons "%t" (format-time-string
  10208. (org-time-stamp-format 'long 'inactive)
  10209. org-log-note-effective-time))
  10210. (cons "%T" (format-time-string
  10211. (org-time-stamp-format 'long nil)
  10212. org-log-note-effective-time))
  10213. (cons "%d" (format-time-string
  10214. (org-time-stamp-format nil 'inactive)
  10215. org-log-note-effective-time))
  10216. (cons "%D" (format-time-string
  10217. (org-time-stamp-format nil nil)
  10218. org-log-note-effective-time))
  10219. (cons "%s" (cond
  10220. ((not org-log-note-state) "")
  10221. ((string-match-p org-ts-regexp
  10222. org-log-note-state)
  10223. (format "\"[%s]\""
  10224. (substring org-log-note-state 1 -1)))
  10225. (t (format "\"%s\"" org-log-note-state))))
  10226. (cons "%S"
  10227. (cond
  10228. ((not org-log-note-previous-state) "")
  10229. ((string-match-p org-ts-regexp
  10230. org-log-note-previous-state)
  10231. (format "\"[%s]\""
  10232. (substring
  10233. org-log-note-previous-state 1 -1)))
  10234. (t (format "\"%s\""
  10235. org-log-note-previous-state)))))))
  10236. (when lines (setq note (concat note " \\\\")))
  10237. (push note lines))
  10238. (when (and lines (not org-note-abort))
  10239. (with-current-buffer (marker-buffer org-log-note-marker)
  10240. (org-with-wide-buffer
  10241. ;; Find location for the new note.
  10242. (goto-char org-log-note-marker)
  10243. (set-marker org-log-note-marker nil)
  10244. ;; Note associated to a clock is to be located right after
  10245. ;; the clock. Do not move point.
  10246. (unless (eq org-log-note-purpose 'clock-out)
  10247. (goto-char (org-log-beginning t)))
  10248. ;; Make sure point is at the beginning of an empty line.
  10249. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10250. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10251. ;; In an existing list, add a new item at the top level.
  10252. ;; Otherwise, indent line like a regular one.
  10253. (let ((itemp (org-in-item-p)))
  10254. (if itemp
  10255. (indent-line-to
  10256. (let ((struct (save-excursion
  10257. (goto-char itemp) (org-list-struct))))
  10258. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10259. (org-indent-line)))
  10260. (insert (org-list-bullet-string "-") (pop lines))
  10261. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10262. (dolist (line lines)
  10263. (insert "\n")
  10264. (indent-line-to ind)
  10265. (insert line)))
  10266. (message "Note stored")
  10267. (org-back-to-heading t))
  10268. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10269. ;; from within `org-add-log-note' because `buffer-undo-list'
  10270. ;; is then modified outside of `org-with-remote-undo'.
  10271. (when (eq this-command 'org-agenda-todo)
  10272. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10273. ;; Don't add undo information when called from `org-agenda-todo'.
  10274. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10275. (set-window-configuration org-log-note-window-configuration)
  10276. (with-current-buffer (marker-buffer org-log-note-return-to)
  10277. (goto-char org-log-note-return-to))
  10278. (move-marker org-log-note-return-to nil)
  10279. (when org-log-post-message (message "%s" org-log-post-message))))
  10280. (defun org-remove-empty-drawer-at (pos)
  10281. "Remove an empty drawer at position POS.
  10282. POS may also be a marker."
  10283. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10284. (org-with-wide-buffer
  10285. (goto-char pos)
  10286. (let ((drawer (org-element-at-point)))
  10287. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10288. (not (org-element-property :contents-begin drawer)))
  10289. (delete-region (org-element-property :begin drawer)
  10290. (progn (goto-char (org-element-property :end drawer))
  10291. (skip-chars-backward " \r\t\n")
  10292. (forward-line)
  10293. (point))))))))
  10294. (defvar org-ts-type nil)
  10295. (defun org-sparse-tree (&optional arg type)
  10296. "Create a sparse tree, prompt for the details.
  10297. This command can create sparse trees. You first need to select the type
  10298. of match used to create the tree:
  10299. t Show all TODO entries.
  10300. T Show entries with a specific TODO keyword.
  10301. m Show entries selected by a tags/property match.
  10302. p Enter a property name and its value (both with completion on existing
  10303. names/values) and show entries with that property.
  10304. r Show entries matching a regular expression (`/' can be used as well).
  10305. b Show deadlines and scheduled items before a date.
  10306. a Show deadlines and scheduled items after a date.
  10307. d Show deadlines due within `org-deadline-warning-days'.
  10308. D Show deadlines and scheduled items between a date range."
  10309. (interactive "P")
  10310. (setq type (or type org-sparse-tree-default-date-type))
  10311. (setq org-ts-type type)
  10312. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10313. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10314. \[c]ycle through date types: %s"
  10315. (cl-case type
  10316. (all "all timestamps")
  10317. (scheduled "only scheduled")
  10318. (deadline "only deadline")
  10319. (active "only active timestamps")
  10320. (inactive "only inactive timestamps")
  10321. (closed "with a closed time-stamp")
  10322. (otherwise "scheduled/deadline")))
  10323. (let ((answer (read-char-exclusive)))
  10324. (cl-case answer
  10325. (?c
  10326. (org-sparse-tree
  10327. arg
  10328. (cadr
  10329. (memq type '(nil all scheduled deadline active inactive closed)))))
  10330. (?d (call-interactively 'org-check-deadlines))
  10331. (?b (call-interactively 'org-check-before-date))
  10332. (?a (call-interactively 'org-check-after-date))
  10333. (?D (call-interactively 'org-check-dates-range))
  10334. (?t (call-interactively 'org-show-todo-tree))
  10335. (?T (org-show-todo-tree '(4)))
  10336. (?m (call-interactively 'org-match-sparse-tree))
  10337. ((?p ?P)
  10338. (let* ((kwd (completing-read
  10339. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10340. (value (completing-read
  10341. "Value: " (mapcar #'list (org-property-values kwd)))))
  10342. (unless (string-match "\\`{.*}\\'" value)
  10343. (setq value (concat "\"" value "\"")))
  10344. (org-match-sparse-tree arg (concat kwd "=" value))))
  10345. ((?r ?R ?/) (call-interactively 'org-occur))
  10346. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10347. (defvar-local org-occur-highlights nil
  10348. "List of overlays used for occur matches.")
  10349. (defvar-local org-occur-parameters nil
  10350. "Parameters of the active org-occur calls.
  10351. This is a list, each call to org-occur pushes as cons cell,
  10352. containing the regular expression and the callback, onto the list.
  10353. The list can contain several entries if `org-occur' has been called
  10354. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10355. will only contain one set of parameters. When the highlights are
  10356. removed (for example with `C-c C-c', or with the next edit (depending
  10357. on `org-remove-highlights-with-change'), this variable is emptied
  10358. as well.")
  10359. (defun org-occur (regexp &optional keep-previous callback)
  10360. "Make a compact tree which shows all matches of REGEXP.
  10361. The tree will show the lines where the regexp matches, and any other context
  10362. defined in `org-show-context-detail', which see.
  10363. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10364. done by a previous call to `org-occur' will be kept, to allow stacking of
  10365. calls to this command.
  10366. Optional argument CALLBACK can be a function of no argument. In this case,
  10367. it is called with point at the end of the match, match data being set
  10368. accordingly. Current match is shown only if the return value is non-nil.
  10369. The function must neither move point nor alter narrowing."
  10370. (interactive "sRegexp: \nP")
  10371. (when (equal regexp "")
  10372. (user-error "Regexp cannot be empty"))
  10373. (unless keep-previous
  10374. (org-remove-occur-highlights nil nil t))
  10375. (push (cons regexp callback) org-occur-parameters)
  10376. (let ((cnt 0))
  10377. (save-excursion
  10378. (goto-char (point-min))
  10379. (when (or (not keep-previous) ; do not want to keep
  10380. (not org-occur-highlights)) ; no previous matches
  10381. ;; hide everything
  10382. (org-overview))
  10383. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10384. (isearch-no-upper-case-p regexp t)
  10385. org-occur-case-fold-search)))
  10386. (while (re-search-forward regexp nil t)
  10387. (when (or (not callback)
  10388. (save-match-data (funcall callback)))
  10389. (setq cnt (1+ cnt))
  10390. (when org-highlight-sparse-tree-matches
  10391. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10392. (org-show-context 'occur-tree)))))
  10393. (when org-remove-highlights-with-change
  10394. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10395. nil 'local))
  10396. (unless org-sparse-tree-open-archived-trees
  10397. (org-hide-archived-subtrees (point-min) (point-max)))
  10398. (run-hooks 'org-occur-hook)
  10399. (when (called-interactively-p 'interactive)
  10400. (message "%d match(es) for regexp %s" cnt regexp))
  10401. cnt))
  10402. (defun org-occur-next-match (&optional n _reset)
  10403. "Function for `next-error-function' to find sparse tree matches.
  10404. N is the number of matches to move, when negative move backwards.
  10405. This function always goes back to the starting point when no
  10406. match is found."
  10407. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10408. (search-func (if (< n 0)
  10409. 'previous-single-char-property-change
  10410. 'next-single-char-property-change))
  10411. (n (abs n))
  10412. (pos (point))
  10413. p1)
  10414. (catch 'exit
  10415. (while (setq p1 (funcall search-func (point) 'org-type))
  10416. (when (equal p1 limit)
  10417. (goto-char pos)
  10418. (user-error "No more matches"))
  10419. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10420. (setq n (1- n))
  10421. (when (= n 0)
  10422. (goto-char p1)
  10423. (throw 'exit (point))))
  10424. (goto-char p1))
  10425. (goto-char p1)
  10426. (user-error "No more matches"))))
  10427. (defun org-highlight-new-match (beg end)
  10428. "Highlight from BEG to END and mark the highlight is an occur headline."
  10429. (let ((ov (make-overlay beg end)))
  10430. (overlay-put ov 'face 'secondary-selection)
  10431. (overlay-put ov 'org-type 'org-occur)
  10432. (push ov org-occur-highlights)))
  10433. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10434. "Remove the occur highlights from the buffer.
  10435. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10436. from the `before-change-functions' in the current buffer."
  10437. (interactive)
  10438. (unless org-inhibit-highlight-removal
  10439. (mapc #'delete-overlay org-occur-highlights)
  10440. (setq org-occur-highlights nil)
  10441. (setq org-occur-parameters nil)
  10442. (unless noremove
  10443. (remove-hook 'before-change-functions
  10444. 'org-remove-occur-highlights 'local))))
  10445. ;;;; Priorities
  10446. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  10447. "Regular expression matching the priority indicator.")
  10448. (defvar org-remove-priority-next-time nil)
  10449. (defun org-priority-up ()
  10450. "Increase the priority of the current item."
  10451. (interactive)
  10452. (org-priority 'up))
  10453. (defun org-priority-down ()
  10454. "Decrease the priority of the current item."
  10455. (interactive)
  10456. (org-priority 'down))
  10457. (defun org-priority (&optional action show)
  10458. "Change the priority of an item.
  10459. When called interactively with a `\\[universal-argument]' prefix,
  10460. show the priority in the minibuffer instead of changing it.
  10461. When called programatically, ACTION can be `set', `up', `down',
  10462. or a character."
  10463. (interactive "P")
  10464. (when show
  10465. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10466. ;; passed the SHOW argument should be removed.
  10467. (warn "`org-priority' called with deprecated SHOW argument"))
  10468. (if (equal action '(4))
  10469. (org-show-priority)
  10470. (unless org-enable-priority-commands
  10471. (user-error "Priority commands are disabled"))
  10472. (setq action (or action 'set))
  10473. (let (current new news have remove)
  10474. (save-excursion
  10475. (org-back-to-heading t)
  10476. (when (looking-at org-priority-regexp)
  10477. (setq current (string-to-char (match-string 2))
  10478. have t))
  10479. (cond
  10480. ((eq action 'remove)
  10481. (setq remove t new ?\ ))
  10482. ((or (eq action 'set)
  10483. (integerp action))
  10484. (if (not (eq action 'set))
  10485. (setq new action)
  10486. (message "Priority %c-%c, SPC to remove: "
  10487. org-highest-priority org-lowest-priority)
  10488. (save-match-data
  10489. (setq new (read-char-exclusive))))
  10490. (when (and (= (upcase org-highest-priority) org-highest-priority)
  10491. (= (upcase org-lowest-priority) org-lowest-priority))
  10492. (setq new (upcase new)))
  10493. (cond ((equal new ?\s) (setq remove t))
  10494. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  10495. (user-error "Priority must be between `%c' and `%c'"
  10496. org-highest-priority org-lowest-priority))))
  10497. ((eq action 'up)
  10498. (setq new (if have
  10499. (1- current) ; normal cycling
  10500. ;; last priority was empty
  10501. (if (eq last-command this-command)
  10502. org-lowest-priority ; wrap around empty to lowest
  10503. ;; default
  10504. (if org-priority-start-cycle-with-default
  10505. org-default-priority
  10506. (1- org-default-priority))))))
  10507. ((eq action 'down)
  10508. (setq new (if have
  10509. (1+ current) ; normal cycling
  10510. ;; last priority was empty
  10511. (if (eq last-command this-command)
  10512. org-highest-priority ; wrap around empty to highest
  10513. ;; default
  10514. (if org-priority-start-cycle-with-default
  10515. org-default-priority
  10516. (1+ org-default-priority))))))
  10517. (t (user-error "Invalid action")))
  10518. (when (or (< (upcase new) org-highest-priority)
  10519. (> (upcase new) org-lowest-priority))
  10520. (if (and (memq action '(up down))
  10521. (not have) (not (eq last-command this-command)))
  10522. ;; `new' is from default priority
  10523. (error
  10524. "The default can not be set, see `org-default-priority' why")
  10525. ;; normal cycling: `new' is beyond highest/lowest priority
  10526. ;; and is wrapped around to the empty priority
  10527. (setq remove t)))
  10528. (setq news (format "%c" new))
  10529. (if have
  10530. (if remove
  10531. (replace-match "" t t nil 1)
  10532. (replace-match news t t nil 2))
  10533. (if remove
  10534. (user-error "No priority cookie found in line")
  10535. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10536. (if (match-end 2)
  10537. (progn
  10538. (goto-char (match-end 2))
  10539. (insert " [#" news "]"))
  10540. (goto-char (match-beginning 3))
  10541. (insert "[#" news "] "))))
  10542. (org-align-tags))
  10543. (if remove
  10544. (message "Priority removed")
  10545. (message "Priority of current item set to %s" news)))))
  10546. (defun org-show-priority ()
  10547. "Show the priority of the current item.
  10548. This priority is composed of the main priority given with the [#A] cookies,
  10549. and by additional input from the age of a schedules or deadline entry."
  10550. (interactive)
  10551. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10552. (org-get-at-bol 'priority)
  10553. (save-excursion
  10554. (save-match-data
  10555. (beginning-of-line)
  10556. (and (looking-at org-heading-regexp)
  10557. (org-get-priority (match-string 0))))))))
  10558. (message "Priority is %d" (if pri pri -1000))))
  10559. (defun org-get-priority (s)
  10560. "Find priority cookie and return priority."
  10561. (save-match-data
  10562. (if (functionp org-get-priority-function)
  10563. (funcall org-get-priority-function)
  10564. (if (not (string-match org-priority-regexp s))
  10565. (* 1000 (- org-lowest-priority org-default-priority))
  10566. (* 1000 (- org-lowest-priority
  10567. (string-to-char (match-string 2 s))))))))
  10568. ;;;; Tags
  10569. (defvar org-agenda-archives-mode)
  10570. (defvar org-map-continue-from nil
  10571. "Position from where mapping should continue.
  10572. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10573. (defvar org-scanner-tags nil
  10574. "The current tag list while the tags scanner is running.")
  10575. (defvar org-trust-scanner-tags nil
  10576. "Should `org-get-tags' use the tags for the scanner.
  10577. This is for internal dynamical scoping only.
  10578. When this is non-nil, the function `org-get-tags' will return the value
  10579. of `org-scanner-tags' instead of building the list by itself. This
  10580. can lead to large speed-ups when the tags scanner is used in a file with
  10581. many entries, and when the list of tags is retrieved, for example to
  10582. obtain a list of properties. Building the tags list for each entry in such
  10583. a file becomes an N^2 operation - but with this variable set, it scales
  10584. as N.")
  10585. (defvar org--matcher-tags-todo-only nil)
  10586. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10587. "Scan headline tags with inheritance and produce output ACTION.
  10588. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10589. or `agenda' to produce an entry list for an agenda view. It can also be
  10590. a Lisp form or a function that should be called at each matched headline, in
  10591. this case the return value is a list of all return values from these calls.
  10592. MATCHER is a function accepting three arguments, returning
  10593. a non-nil value whenever a given set of tags qualifies a headline
  10594. for inclusion. See `org-make-tags-matcher' for more information.
  10595. As a special case, it can also be set to t (respectively nil) in
  10596. order to match all (respectively none) headline.
  10597. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10598. included in the output.
  10599. START-LEVEL can be a string with asterisks, reducing the scope to
  10600. headlines matching this string."
  10601. (require 'org-agenda)
  10602. (let* ((re (concat "^"
  10603. (if start-level
  10604. ;; Get the correct level to match
  10605. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10606. org-outline-regexp)
  10607. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10608. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10609. (props (list 'face 'default
  10610. 'done-face 'org-agenda-done
  10611. 'undone-face 'default
  10612. 'mouse-face 'highlight
  10613. 'org-not-done-regexp org-not-done-regexp
  10614. 'org-todo-regexp org-todo-regexp
  10615. 'org-complex-heading-regexp org-complex-heading-regexp
  10616. 'help-echo
  10617. (format "mouse-2 or RET jump to Org file %S"
  10618. (abbreviate-file-name
  10619. (or (buffer-file-name (buffer-base-buffer))
  10620. (buffer-name (buffer-base-buffer)))))))
  10621. (org-map-continue-from nil)
  10622. lspos tags tags-list
  10623. (tags-alist (list (cons 0 org-file-tags)))
  10624. (llast 0) rtn rtn1 level category i txt
  10625. todo marker entry priority
  10626. ts-date ts-date-type ts-date-pair)
  10627. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10628. (setq action (list 'lambda nil action)))
  10629. (save-excursion
  10630. (goto-char (point-min))
  10631. (when (eq action 'sparse-tree)
  10632. (org-overview)
  10633. (org-remove-occur-highlights))
  10634. (while (let (case-fold-search)
  10635. (re-search-forward re nil t))
  10636. (setq org-map-continue-from nil)
  10637. (catch :skip
  10638. ;; Ignore closing parts of inline tasks.
  10639. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10640. (throw :skip t))
  10641. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10642. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10643. (goto-char (setq lspos (match-beginning 0)))
  10644. (setq level (org-reduced-level (org-outline-level))
  10645. category (org-get-category))
  10646. (when (eq action 'agenda)
  10647. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10648. ts-date (car ts-date-pair)
  10649. ts-date-type (cdr ts-date-pair)))
  10650. (setq i llast llast level)
  10651. ;; remove tag lists from same and sublevels
  10652. (while (>= i level)
  10653. (when (setq entry (assoc i tags-alist))
  10654. (setq tags-alist (delete entry tags-alist)))
  10655. (setq i (1- i)))
  10656. ;; add the next tags
  10657. (when tags
  10658. (setq tags (org-split-string tags ":")
  10659. tags-alist
  10660. (cons (cons level tags) tags-alist)))
  10661. ;; compile tags for current headline
  10662. (setq tags-list
  10663. (if org-use-tag-inheritance
  10664. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10665. tags)
  10666. org-scanner-tags tags-list)
  10667. (when org-use-tag-inheritance
  10668. (setcdr (car tags-alist)
  10669. (mapcar (lambda (x)
  10670. (setq x (copy-sequence x))
  10671. (org-add-prop-inherited x))
  10672. (cdar tags-alist))))
  10673. (when (and tags org-use-tag-inheritance
  10674. (or (not (eq t org-use-tag-inheritance))
  10675. org-tags-exclude-from-inheritance))
  10676. ;; Selective inheritance, remove uninherited ones.
  10677. (setcdr (car tags-alist)
  10678. (org-remove-uninherited-tags (cdar tags-alist))))
  10679. (when (and
  10680. ;; eval matcher only when the todo condition is OK
  10681. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10682. (if (functionp matcher)
  10683. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10684. (funcall matcher todo tags-list level))
  10685. matcher))
  10686. ;; Call the skipper, but return t if it does not
  10687. ;; skip, so that the `and' form continues evaluating.
  10688. (progn
  10689. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10690. t)
  10691. ;; Check if timestamps are deselecting this entry
  10692. (or (not todo-only)
  10693. (and (member todo org-todo-keywords-1)
  10694. (or (not org-agenda-tags-todo-honor-ignore-options)
  10695. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10696. ;; select this headline
  10697. (cond
  10698. ((eq action 'sparse-tree)
  10699. (and org-highlight-sparse-tree-matches
  10700. (org-get-heading) (match-end 0)
  10701. (org-highlight-new-match
  10702. (match-beginning 1) (match-end 1)))
  10703. (org-show-context 'tags-tree))
  10704. ((eq action 'agenda)
  10705. (setq txt (org-agenda-format-item
  10706. ""
  10707. (concat
  10708. (if (eq org-tags-match-list-sublevels 'indented)
  10709. (make-string (1- level) ?.) "")
  10710. (org-get-heading))
  10711. (make-string level ?\s)
  10712. category
  10713. tags-list)
  10714. priority (org-get-priority txt))
  10715. (goto-char lspos)
  10716. (setq marker (org-agenda-new-marker))
  10717. (org-add-props txt props
  10718. 'org-marker marker 'org-hd-marker marker 'org-category category
  10719. 'todo-state todo
  10720. 'ts-date ts-date
  10721. 'priority priority
  10722. 'type (concat "tagsmatch" ts-date-type))
  10723. (push txt rtn))
  10724. ((functionp action)
  10725. (setq org-map-continue-from nil)
  10726. (save-excursion
  10727. (setq rtn1 (funcall action))
  10728. (push rtn1 rtn)))
  10729. (t (user-error "Invalid action")))
  10730. ;; if we are to skip sublevels, jump to end of subtree
  10731. (unless org-tags-match-list-sublevels
  10732. (org-end-of-subtree t)
  10733. (backward-char 1))))
  10734. ;; Get the correct position from where to continue
  10735. (if org-map-continue-from
  10736. (goto-char org-map-continue-from)
  10737. (and (= (point) lspos) (end-of-line 1)))))
  10738. (when (and (eq action 'sparse-tree)
  10739. (not org-sparse-tree-open-archived-trees))
  10740. (org-hide-archived-subtrees (point-min) (point-max)))
  10741. (nreverse rtn)))
  10742. (defun org-remove-uninherited-tags (tags)
  10743. "Remove all tags that are not inherited from the list TAGS."
  10744. (cond
  10745. ((eq org-use-tag-inheritance t)
  10746. (if org-tags-exclude-from-inheritance
  10747. (org-delete-all org-tags-exclude-from-inheritance tags)
  10748. tags))
  10749. ((not org-use-tag-inheritance) nil)
  10750. ((stringp org-use-tag-inheritance)
  10751. (delq nil (mapcar
  10752. (lambda (x)
  10753. (if (and (string-match org-use-tag-inheritance x)
  10754. (not (member x org-tags-exclude-from-inheritance)))
  10755. x nil))
  10756. tags)))
  10757. ((listp org-use-tag-inheritance)
  10758. (delq nil (mapcar
  10759. (lambda (x)
  10760. (if (member x org-use-tag-inheritance) x nil))
  10761. tags)))))
  10762. (defun org-match-sparse-tree (&optional todo-only match)
  10763. "Create a sparse tree according to tags string MATCH.
  10764. MATCH is a string with match syntax. It can contain a selection
  10765. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10766. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10767. those. See the manual for details.
  10768. If optional argument TODO-ONLY is non-nil, only select lines that
  10769. are also TODO tasks."
  10770. (interactive "P")
  10771. (org-agenda-prepare-buffers (list (current-buffer)))
  10772. (let ((org--matcher-tags-todo-only todo-only))
  10773. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10774. org--matcher-tags-todo-only)))
  10775. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10776. (defvar org-cached-props nil)
  10777. (defun org-cached-entry-get (pom property)
  10778. (if (or (eq t org-use-property-inheritance)
  10779. (and (stringp org-use-property-inheritance)
  10780. (let ((case-fold-search t))
  10781. (string-match-p org-use-property-inheritance property)))
  10782. (and (listp org-use-property-inheritance)
  10783. (member-ignore-case property org-use-property-inheritance)))
  10784. ;; Caching is not possible, check it directly.
  10785. (org-entry-get pom property 'inherit)
  10786. ;; Get all properties, so we can do complicated checks easily.
  10787. (cdr (assoc-string property
  10788. (or org-cached-props
  10789. (setq org-cached-props (org-entry-properties pom)))
  10790. t))))
  10791. (defun org-global-tags-completion-table (&optional files)
  10792. "Return the list of all tags in all agenda buffer/files.
  10793. Optional FILES argument is a list of files which can be used
  10794. instead of the agenda files."
  10795. (save-excursion
  10796. (org-uniquify
  10797. (delq nil
  10798. (apply #'append
  10799. (mapcar
  10800. (lambda (file)
  10801. (set-buffer (find-file-noselect file))
  10802. (org--tag-add-to-alist
  10803. (org-get-buffer-tags)
  10804. (mapcar (lambda (x)
  10805. (and (stringp (car-safe x))
  10806. (list (car-safe x))))
  10807. org-current-tag-alist)))
  10808. (if (car-safe files) files
  10809. (org-agenda-files))))))))
  10810. (defun org-make-tags-matcher (match)
  10811. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10812. Returns a cons of the selection string MATCH and a function
  10813. implementing the matcher.
  10814. The matcher is to be called at an Org entry, with point on the
  10815. headline, and returns non-nil if the entry matches the selection
  10816. string MATCH. It must be called with three arguments: the TODO
  10817. keyword at the entry (or nil if none), the list of all tags at
  10818. the entry including inherited ones and the reduced level of the
  10819. headline. Additionally, the category of the entry, if any, must
  10820. be specified as the text property `org-category' on the headline.
  10821. This function sets the variable `org--matcher-tags-todo-only' to
  10822. a non-nil value if the matcher restricts matching to TODO
  10823. entries, otherwise it is not touched.
  10824. See also `org-scan-tags'."
  10825. (unless match
  10826. ;; Get a new match request, with completion against the global
  10827. ;; tags table and the local tags in current buffer.
  10828. (let ((org-last-tags-completion-table
  10829. (org--tag-add-to-alist
  10830. (org-get-buffer-tags)
  10831. (org-global-tags-completion-table))))
  10832. (setq match
  10833. (completing-read
  10834. "Match: "
  10835. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10836. (let ((match0 match)
  10837. (re (concat
  10838. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10839. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10840. "\\([<>=]\\{1,2\\}\\)"
  10841. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10842. "\\|" org-tag-re "\\)"))
  10843. (start 0)
  10844. tagsmatch todomatch tagsmatcher todomatcher)
  10845. ;; Expand group tags.
  10846. (setq match (org-tags-expand match))
  10847. ;; Check if there is a TODO part of this match, which would be the
  10848. ;; part after a "/". To make sure that this slash is not part of
  10849. ;; a property value to be matched against, we also check that
  10850. ;; there is no / after that slash. First, find the last slash.
  10851. (let ((s 0))
  10852. (while (string-match "/+" match s)
  10853. (setq start (match-beginning 0))
  10854. (setq s (match-end 0))))
  10855. (if (and (string-match "/+" match start)
  10856. (not (string-match-p "\"" match start)))
  10857. ;; Match contains also a TODO-matching request.
  10858. (progn
  10859. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10860. (setq todomatch (substring match (match-end 0)))
  10861. (when (string-prefix-p "!" todomatch)
  10862. (setq org--matcher-tags-todo-only t)
  10863. (setq todomatch (substring todomatch 1)))
  10864. (when (string-match "\\`\\s-*\\'" todomatch)
  10865. (setq todomatch nil)))
  10866. ;; Only matching tags.
  10867. (setq tagsmatch match)
  10868. (setq todomatch nil))
  10869. ;; Make the tags matcher.
  10870. (when (org-string-nw-p tagsmatch)
  10871. (let ((orlist nil)
  10872. (orterms (org-split-string tagsmatch "|"))
  10873. term)
  10874. (while (setq term (pop orterms))
  10875. (while (and (equal (substring term -1) "\\") orterms)
  10876. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10877. (while (string-match re term)
  10878. (let* ((rest (substring term (match-end 0)))
  10879. (minus (and (match-end 1)
  10880. (equal (match-string 1 term) "-")))
  10881. (tag (save-match-data
  10882. (replace-regexp-in-string
  10883. "\\\\-" "-" (match-string 2 term))))
  10884. (regexp (eq (string-to-char tag) ?{))
  10885. (levelp (match-end 4))
  10886. (propp (match-end 5))
  10887. (mm
  10888. (cond
  10889. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10890. (levelp
  10891. `(,(org-op-to-function (match-string 3 term))
  10892. level
  10893. ,(string-to-number (match-string 4 term))))
  10894. (propp
  10895. (let* ((gv (pcase (upcase (match-string 5 term))
  10896. ("CATEGORY"
  10897. '(get-text-property (point) 'org-category))
  10898. ("TODO" 'todo)
  10899. (p `(org-cached-entry-get nil ,p))))
  10900. (pv (match-string 7 term))
  10901. (regexp (eq (string-to-char pv) ?{))
  10902. (strp (eq (string-to-char pv) ?\"))
  10903. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10904. (po (org-op-to-function (match-string 6 term)
  10905. (if timep 'time strp))))
  10906. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10907. (when timep (setq pv (org-matcher-time pv)))
  10908. (cond ((and regexp (eq po '/=))
  10909. `(not (string-match ,pv (or ,gv ""))))
  10910. (regexp `(string-match ,pv (or ,gv "")))
  10911. (strp `(,po (or ,gv "") ,pv))
  10912. (t
  10913. `(,po
  10914. (string-to-number (or ,gv ""))
  10915. ,(string-to-number pv))))))
  10916. (t `(member ,tag tags-list)))))
  10917. (push (if minus `(not ,mm) mm) tagsmatcher)
  10918. (setq term rest)))
  10919. (push `(and ,@tagsmatcher) orlist)
  10920. (setq tagsmatcher nil))
  10921. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10922. ;; Make the TODO matcher.
  10923. (when (org-string-nw-p todomatch)
  10924. (let ((orlist nil))
  10925. (dolist (term (org-split-string todomatch "|"))
  10926. (while (string-match re term)
  10927. (let* ((minus (and (match-end 1)
  10928. (equal (match-string 1 term) "-")))
  10929. (kwd (match-string 2 term))
  10930. (regexp (eq (string-to-char kwd) ?{))
  10931. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10932. `(equal todo ,kwd))))
  10933. (push (if minus `(not ,mm) mm) todomatcher))
  10934. (setq term (substring term (match-end 0))))
  10935. (push (if (> (length todomatcher) 1)
  10936. (cons 'and todomatcher)
  10937. (car todomatcher))
  10938. orlist)
  10939. (setq todomatcher nil))
  10940. (setq todomatcher (cons 'or orlist))))
  10941. ;; Return the string and function of the matcher. If no
  10942. ;; tags-specific or todo-specific matcher exists, match
  10943. ;; everything.
  10944. (let ((matcher (if (and tagsmatcher todomatcher)
  10945. `(and ,tagsmatcher ,todomatcher)
  10946. (or tagsmatcher todomatcher t))))
  10947. (when org--matcher-tags-todo-only
  10948. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10949. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10950. (defun org--tags-expand-group (group tag-groups expanded)
  10951. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10952. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10953. an accumulator used in recursive calls."
  10954. (dolist (tag group)
  10955. (unless (member tag expanded)
  10956. (let ((group (assoc tag tag-groups)))
  10957. (push tag expanded)
  10958. (when group
  10959. (setq expanded
  10960. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10961. expanded)
  10962. (defun org-tags-expand (match &optional single-as-list downcased)
  10963. "Expand group tags in MATCH.
  10964. This replaces every group tag in MATCH with a regexp tag search.
  10965. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10966. will be replaced like this:
  10967. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10968. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10969. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10970. Replacing by a regexp preserves the structure of the match.
  10971. E.g., this expansion
  10972. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10973. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10974. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10975. A group tag in MATCH can contain regular expressions of its own.
  10976. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10977. will be replaced like this:
  10978. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10979. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10980. assumed to be a single group tag, and the function will return
  10981. the list of tags in this group.
  10982. When DOWNCASED is non-nil, expand downcased TAGS."
  10983. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10984. (let ((tag-groups
  10985. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10986. (if (not downcased) g
  10987. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10988. (cond
  10989. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10990. (org-group-tags
  10991. (let* ((case-fold-search t)
  10992. (tag-syntax org-mode-syntax-table)
  10993. (group-keys (mapcar #'car tag-groups))
  10994. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10995. (return-match (if downcased (downcase match) match)))
  10996. ;; Mark regexp-expressions in the match-expression so that we
  10997. ;; do not replace them later on.
  10998. (let ((s 0))
  10999. (while (string-match "{.+?}" return-match s)
  11000. (setq s (match-end 0))
  11001. (add-text-properties
  11002. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11003. ;; @ and _ are allowed as word-components in tags.
  11004. (modify-syntax-entry ?@ "w" tag-syntax)
  11005. (modify-syntax-entry ?_ "w" tag-syntax)
  11006. ;; For each tag token found in MATCH, compute a regexp and it
  11007. (with-syntax-table tag-syntax
  11008. (replace-regexp-in-string
  11009. key-regexp
  11010. (lambda (m)
  11011. (if (get-text-property (match-beginning 2) 'regexp m)
  11012. m ;regexp tag: ignore
  11013. (let* ((operator (match-string 1 m))
  11014. (tag-token (let ((tag (match-string 2 m)))
  11015. (list (if downcased (downcase tag) tag))))
  11016. regexp-tags regular-tags)
  11017. ;; Partition tags between regexp and regular tags.
  11018. ;; Remove curly bracket syntax from regexp tags.
  11019. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11020. (save-match-data
  11021. (if (string-match "{\\(.+?\\)}" tag)
  11022. (push (match-string 1 tag) regexp-tags)
  11023. (push tag regular-tags))))
  11024. ;; Replace tag token by the appropriate regexp.
  11025. ;; Regular tags need to be regexp-quoted, whereas
  11026. ;; regexp-tags are inserted as-is.
  11027. (let ((regular (regexp-opt regular-tags))
  11028. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11029. (concat operator
  11030. (cond
  11031. ((null regular-tags) (format "{%s}" regexp))
  11032. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11033. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11034. return-match
  11035. t t))))
  11036. (t match))))
  11037. (defun org-op-to-function (op &optional stringp)
  11038. "Turn an operator into the appropriate function."
  11039. (setq op
  11040. (cond
  11041. ((equal op "<" ) '(< org-string< org-time<))
  11042. ((equal op ">" ) '(> org-string> org-time>))
  11043. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11044. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11045. ((member op '("=" "==")) '(= string= org-time=))
  11046. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11047. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11048. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11049. (defvar org-tags-overlay (make-overlay 1 1))
  11050. (delete-overlay org-tags-overlay)
  11051. (defun org-add-prop-inherited (s)
  11052. (add-text-properties 0 (length s) '(inherited t) s)
  11053. s)
  11054. (defun org-toggle-tag (tag &optional onoff)
  11055. "Toggle the tag TAG for the current line.
  11056. If ONOFF is `on' or `off', don't toggle but set to this state."
  11057. (save-excursion
  11058. (org-back-to-heading t)
  11059. (let ((current
  11060. ;; Reverse the tags list so any new tag is appended to the
  11061. ;; current list of tags.
  11062. (nreverse (org-get-tags nil t)))
  11063. res)
  11064. (pcase onoff
  11065. (`off (setq current (delete tag current)))
  11066. ((or `on (guard (not (member tag current))))
  11067. (setq res t)
  11068. (cl-pushnew tag current :test #'equal))
  11069. (_ (setq current (delete tag current))))
  11070. (org-set-tags (nreverse current))
  11071. res)))
  11072. (defun org--align-tags-here (to-col)
  11073. "Align tags on the current headline to TO-COL.
  11074. Assume point is on a headline. Preserve point when aligning
  11075. tags."
  11076. (when (org-match-line org-tag-line-re)
  11077. (let* ((tags-start (match-beginning 1))
  11078. (blank-start (save-excursion
  11079. (goto-char tags-start)
  11080. (skip-chars-backward " \t")
  11081. (point)))
  11082. (new (max (if (>= to-col 0) to-col
  11083. (- (abs to-col) (string-width (match-string 1))))
  11084. ;; Introduce at least one space after the heading
  11085. ;; or the stars.
  11086. (save-excursion
  11087. (goto-char blank-start)
  11088. (1+ (current-column)))))
  11089. (current
  11090. (save-excursion (goto-char tags-start) (current-column)))
  11091. (origin (point-marker))
  11092. (column (current-column))
  11093. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11094. (when (/= new current)
  11095. (delete-region blank-start tags-start)
  11096. (goto-char blank-start)
  11097. (let ((indent-tabs-mode nil)) (indent-to new))
  11098. ;; Try to move back to original position. If point was in the
  11099. ;; blanks before the tags, ORIGIN marker is of no use because
  11100. ;; it now points to BLANK-START. Use COLUMN instead.
  11101. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11102. (defun org-set-tags-command (&optional arg)
  11103. "Set the tags for the current visible entry.
  11104. When called with `\\[universal-argument]' prefix argument ARG, \
  11105. realign all tags
  11106. in the current buffer.
  11107. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11108. unconditionally do not
  11109. offer the fast tag selection interface.
  11110. If a region is active, set tags in the region according to the
  11111. setting of `org-loop-over-headlines-in-active-region'.
  11112. This function is for interactive use only;
  11113. in Lisp code use `org-set-tags' instead."
  11114. (interactive "P")
  11115. (let ((org-use-fast-tag-selection
  11116. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11117. (cond
  11118. ((equal '(4) arg) (org-align-tags t))
  11119. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11120. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11121. (org-map-entries
  11122. #'org-set-tags-command
  11123. nil
  11124. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11125. 'region-start-level
  11126. 'region)
  11127. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11128. (t
  11129. (save-excursion
  11130. (org-back-to-heading)
  11131. (let* ((all-tags (org-get-tags))
  11132. (table (setq org-last-tags-completion-table
  11133. (org--tag-add-to-alist
  11134. (and org-complete-tags-always-offer-all-agenda-tags
  11135. (org-global-tags-completion-table
  11136. (org-agenda-files)))
  11137. (or org-current-tag-alist (org-get-buffer-tags)))))
  11138. (current-tags
  11139. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11140. all-tags))
  11141. (inherited-tags
  11142. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11143. all-tags))
  11144. (tags
  11145. (replace-regexp-in-string
  11146. ;; Ignore all forbidden characters in tags.
  11147. "[^[:alnum:]_@#%]+" ":"
  11148. (if (or (eq t org-use-fast-tag-selection)
  11149. (and org-use-fast-tag-selection
  11150. (delq nil (mapcar #'cdr table))))
  11151. (org-fast-tag-selection
  11152. current-tags
  11153. inherited-tags
  11154. table
  11155. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11156. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11157. (org-trim (completing-read
  11158. "Tags: "
  11159. #'org-tags-completion-function
  11160. nil nil (org-make-tag-string current-tags)
  11161. 'org-tags-history)))))))
  11162. (org-set-tags tags)))))))
  11163. (defun org-align-tags (&optional all)
  11164. "Align tags in current entry.
  11165. When optional argument ALL is non-nil, align all tags in the
  11166. visible part of the buffer."
  11167. (let ((get-indent-column
  11168. (lambda ()
  11169. (let ((offset (if (bound-and-true-p org-indent-mode)
  11170. (* (1- org-indent-indentation-per-level)
  11171. (1- (org-current-level)))
  11172. 0)))
  11173. (+ org-tags-column
  11174. (if (> org-tags-column 0) (- offset) offset))))))
  11175. (if (and (not all) (org-at-heading-p))
  11176. (org--align-tags-here (funcall get-indent-column))
  11177. (save-excursion
  11178. (if all
  11179. (progn
  11180. (goto-char (point-min))
  11181. (while (re-search-forward org-tag-line-re nil t)
  11182. (org--align-tags-here (funcall get-indent-column))))
  11183. (org-back-to-heading t)
  11184. (org--align-tags-here (funcall get-indent-column)))))))
  11185. (defun org-set-tags (tags)
  11186. "Set the tags of the current entry to TAGS, replacing current tags.
  11187. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11188. If TAGS is nil or the empty string, all tags are removed.
  11189. This function assumes point is on a headline."
  11190. (org-with-wide-buffer
  11191. (let ((tags (pcase tags
  11192. ((pred listp) tags)
  11193. ((pred stringp) (split-string (org-trim tags) ":" t))
  11194. (_ (error "Invalid tag specification: %S" tags))))
  11195. (old-tags (org-get-tags nil t))
  11196. (tags-change? nil))
  11197. (when (functionp org-tags-sort-function)
  11198. (setq tags (sort tags org-tags-sort-function)))
  11199. (setq tags-change? (not (equal tags old-tags)))
  11200. (when tags-change?
  11201. ;; Delete previous tags and any trailing white space.
  11202. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11203. (line-end-position)))
  11204. (skip-chars-backward " \t")
  11205. (delete-region (point) (line-end-position))
  11206. ;; Deleting white spaces may break an otherwise empty headline.
  11207. ;; Re-introduce one space in this case.
  11208. (unless (org-at-heading-p) (insert " "))
  11209. (when tags
  11210. (save-excursion (insert " " (org-make-tag-string tags)))
  11211. ;; When text is being inserted on an invisible region
  11212. ;; boundary, it can be inadvertently sucked into
  11213. ;; invisibility.
  11214. (unless (org-invisible-p (line-beginning-position))
  11215. (org-flag-region (point) (line-end-position) nil 'outline))))
  11216. ;; Align tags, if any.
  11217. (when tags (org-align-tags))
  11218. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11219. (defun org-change-tag-in-region (beg end tag off)
  11220. "Add or remove TAG for each entry in the region.
  11221. This works in the agenda, and also in an Org buffer."
  11222. (interactive
  11223. (list (region-beginning) (region-end)
  11224. (let ((org-last-tags-completion-table
  11225. (if (derived-mode-p 'org-mode)
  11226. (org--tag-add-to-alist
  11227. (org-get-buffer-tags)
  11228. (org-global-tags-completion-table))
  11229. (org-global-tags-completion-table))))
  11230. (completing-read
  11231. "Tag: " 'org-tags-completion-function nil nil nil
  11232. 'org-tags-history))
  11233. (progn
  11234. (message "[s]et or [r]emove? ")
  11235. (equal (read-char-exclusive) ?r))))
  11236. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11237. (let ((agendap (equal major-mode 'org-agenda-mode))
  11238. l1 l2 m buf pos newhead (cnt 0))
  11239. (goto-char end)
  11240. (setq l2 (1- (org-current-line)))
  11241. (goto-char beg)
  11242. (setq l1 (org-current-line))
  11243. (cl-loop for l from l1 to l2 do
  11244. (org-goto-line l)
  11245. (setq m (get-text-property (point) 'org-hd-marker))
  11246. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11247. (and agendap m))
  11248. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11249. pos (if agendap m (point)))
  11250. (with-current-buffer buf
  11251. (save-excursion
  11252. (save-restriction
  11253. (goto-char pos)
  11254. (setq cnt (1+ cnt))
  11255. (org-toggle-tag tag (if off 'off 'on))
  11256. (setq newhead (org-get-heading)))))
  11257. (and agendap (org-agenda-change-all-lines newhead m))))
  11258. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11259. (defun org-tags-completion-function (string _predicate &optional flag)
  11260. "Complete tag STRING.
  11261. FLAG specifies the type of completion operation to perform. This
  11262. function is passed as a collection function to `completing-read',
  11263. which see."
  11264. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11265. (confirm (lambda (x) (stringp (car x))))
  11266. (prefix ""))
  11267. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11268. (setq prefix (match-string 1 string))
  11269. (setq string (match-string 2 string)))
  11270. (pcase flag
  11271. (`t (all-completions string org-last-tags-completion-table confirm))
  11272. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11273. (`nil
  11274. (pcase (try-completion string org-last-tags-completion-table confirm)
  11275. ((and completion (pred stringp))
  11276. (concat prefix
  11277. completion
  11278. (if (and org-add-colon-after-tag-completion
  11279. (assoc completion org-last-tags-completion-table))
  11280. ":"
  11281. "")))
  11282. (completion completion)))
  11283. (_ nil))))
  11284. (defun org-fast-tag-insert (kwd tags face &optional end)
  11285. "Insert KWD, and the TAGS, the latter with face FACE.
  11286. Also insert END."
  11287. (insert (format "%-12s" (concat kwd ":"))
  11288. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11289. (or end "")))
  11290. (defun org-fast-tag-show-exit (flag)
  11291. (save-excursion
  11292. (org-goto-line 3)
  11293. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11294. (replace-match ""))
  11295. (when flag
  11296. (end-of-line 1)
  11297. (org-move-to-column (- (window-width) 19) t)
  11298. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11299. (defun org-set-current-tags-overlay (current prefix)
  11300. "Add an overlay to CURRENT tag with PREFIX."
  11301. (let ((s (org-make-tag-string current)))
  11302. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11303. (org-overlay-display org-tags-overlay (concat prefix s))))
  11304. (defvar org-last-tag-selection-key nil)
  11305. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11306. "Fast tag selection with single keys.
  11307. CURRENT is the current list of tags in the headline, INHERITED is the
  11308. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11309. possibly with grouping information. TODO-TABLE is a similar table with
  11310. TODO keywords, should these have keys assigned to them.
  11311. If the keys are nil, a-z are automatically assigned.
  11312. Returns the new tags string, or nil to not change the current settings."
  11313. (let* ((fulltable (append table todo-table))
  11314. (maxlen (if (null fulltable) 0
  11315. (apply #'max
  11316. (mapcar (lambda (x)
  11317. (if (stringp (car x)) (string-width (car x))
  11318. 0))
  11319. fulltable))))
  11320. (buf (current-buffer))
  11321. (expert (eq org-fast-tag-selection-single-key 'expert))
  11322. (buffer-tags nil)
  11323. (fwidth (+ maxlen 3 1 3))
  11324. (ncol (/ (- (window-width) 4) fwidth))
  11325. (i-face 'org-done)
  11326. (c-face 'org-todo)
  11327. tg cnt e c char c1 c2 ntable tbl rtn
  11328. ov-start ov-end ov-prefix
  11329. (exit-after-next org-fast-tag-selection-single-key)
  11330. (done-keywords org-done-keywords)
  11331. groups ingroup intaggroup)
  11332. (save-excursion
  11333. (beginning-of-line)
  11334. (if (looking-at org-tag-line-re)
  11335. (setq ov-start (match-beginning 1)
  11336. ov-end (match-end 1)
  11337. ov-prefix "")
  11338. (setq ov-start (1- (point-at-eol))
  11339. ov-end (1+ ov-start))
  11340. (skip-chars-forward "^\n\r")
  11341. (setq ov-prefix
  11342. (concat
  11343. (buffer-substring (1- (point)) (point))
  11344. (if (> (current-column) org-tags-column)
  11345. " "
  11346. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11347. (move-overlay org-tags-overlay ov-start ov-end)
  11348. (save-excursion
  11349. (save-window-excursion
  11350. (if expert
  11351. (set-buffer (get-buffer-create " *Org tags*"))
  11352. (delete-other-windows)
  11353. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11354. (org-switch-to-buffer-other-window " *Org tags*"))
  11355. (erase-buffer)
  11356. (setq-local org-done-keywords done-keywords)
  11357. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11358. (org-fast-tag-insert "Current" current c-face "\n\n")
  11359. (org-fast-tag-show-exit exit-after-next)
  11360. (org-set-current-tags-overlay current ov-prefix)
  11361. (setq tbl fulltable char ?a cnt 0)
  11362. (while (setq e (pop tbl))
  11363. (cond
  11364. ((eq (car e) :startgroup)
  11365. (push '() groups) (setq ingroup t)
  11366. (unless (zerop cnt)
  11367. (setq cnt 0)
  11368. (insert "\n"))
  11369. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11370. ((eq (car e) :endgroup)
  11371. (setq ingroup nil cnt 0)
  11372. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11373. ((eq (car e) :startgrouptag)
  11374. (setq intaggroup t)
  11375. (unless (zerop cnt)
  11376. (setq cnt 0)
  11377. (insert "\n"))
  11378. (insert "[ "))
  11379. ((eq (car e) :endgrouptag)
  11380. (setq intaggroup nil cnt 0)
  11381. (insert "]\n"))
  11382. ((equal e '(:newline))
  11383. (unless (zerop cnt)
  11384. (setq cnt 0)
  11385. (insert "\n")
  11386. (setq e (car tbl))
  11387. (while (equal (car tbl) '(:newline))
  11388. (insert "\n")
  11389. (setq tbl (cdr tbl)))))
  11390. ((equal e '(:grouptags)) (insert " : "))
  11391. (t
  11392. (setq tg (copy-sequence (car e)) c2 nil)
  11393. (if (cdr e)
  11394. (setq c (cdr e))
  11395. ;; automatically assign a character.
  11396. (setq c1 (string-to-char
  11397. (downcase (substring
  11398. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11399. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11400. (while (or (rassoc char ntable) (rassoc char table))
  11401. (setq char (1+ char)))
  11402. (setq c2 c1))
  11403. (setq c (or c2 char)))
  11404. (when ingroup (push tg (car groups)))
  11405. (setq tg (org-add-props tg nil 'face
  11406. (cond
  11407. ((not (assoc tg table))
  11408. (org-get-todo-face tg))
  11409. ((member tg current) c-face)
  11410. ((member tg inherited) i-face))))
  11411. (when (equal (caar tbl) :grouptags)
  11412. (org-add-props tg nil 'face 'org-tag-group))
  11413. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11414. (insert "[" c "] " tg (make-string
  11415. (- fwidth 4 (length tg)) ?\ ))
  11416. (push (cons tg c) ntable)
  11417. (when (= (cl-incf cnt) ncol)
  11418. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11419. (insert "\n")
  11420. (when (or ingroup intaggroup) (insert " ")))
  11421. (setq cnt 0)))))
  11422. (setq ntable (nreverse ntable))
  11423. (insert "\n")
  11424. (goto-char (point-min))
  11425. (unless expert (org-fit-window-to-buffer))
  11426. (setq rtn
  11427. (catch 'exit
  11428. (while t
  11429. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11430. (if (not groups) "no " "")
  11431. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11432. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11433. (setq org-last-tag-selection-key c)
  11434. (cond
  11435. ((= c ?\r) (throw 'exit t))
  11436. ((= c ?!)
  11437. (setq groups (not groups))
  11438. (goto-char (point-min))
  11439. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11440. ((= c ?\C-c)
  11441. (if (not expert)
  11442. (org-fast-tag-show-exit
  11443. (setq exit-after-next (not exit-after-next)))
  11444. (setq expert nil)
  11445. (delete-other-windows)
  11446. (set-window-buffer (split-window-vertically) " *Org tags*")
  11447. (org-switch-to-buffer-other-window " *Org tags*")
  11448. (org-fit-window-to-buffer)))
  11449. ((or (= c ?\C-g)
  11450. (and (= c ?q) (not (rassoc c ntable))))
  11451. (delete-overlay org-tags-overlay)
  11452. (setq quit-flag t))
  11453. ((= c ?\ )
  11454. (setq current nil)
  11455. (when exit-after-next (setq exit-after-next 'now)))
  11456. ((= c ?\t)
  11457. (condition-case nil
  11458. (setq tg (completing-read
  11459. "Tag: "
  11460. (or buffer-tags
  11461. (with-current-buffer buf
  11462. (setq buffer-tags
  11463. (org-get-buffer-tags))))))
  11464. (quit (setq tg "")))
  11465. (when (string-match "\\S-" tg)
  11466. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11467. (if (member tg current)
  11468. (setq current (delete tg current))
  11469. (push tg current)))
  11470. (when exit-after-next (setq exit-after-next 'now)))
  11471. ((setq e (rassoc c todo-table) tg (car e))
  11472. (with-current-buffer buf
  11473. (save-excursion (org-todo tg)))
  11474. (when exit-after-next (setq exit-after-next 'now)))
  11475. ((setq e (rassoc c ntable) tg (car e))
  11476. (if (member tg current)
  11477. (setq current (delete tg current))
  11478. (cl-loop for g in groups do
  11479. (when (member tg g)
  11480. (dolist (x g) (setq current (delete x current)))))
  11481. (push tg current))
  11482. (when exit-after-next (setq exit-after-next 'now))))
  11483. ;; Create a sorted list
  11484. (setq current
  11485. (sort current
  11486. (lambda (a b)
  11487. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11488. (when (eq exit-after-next 'now) (throw 'exit t))
  11489. (goto-char (point-min))
  11490. (beginning-of-line 2)
  11491. (delete-region (point) (point-at-eol))
  11492. (org-fast-tag-insert "Current" current c-face)
  11493. (org-set-current-tags-overlay current ov-prefix)
  11494. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11495. (while (re-search-forward tag-re nil t)
  11496. (let ((tag (match-string 1)))
  11497. (add-text-properties
  11498. (match-beginning 1) (match-end 1)
  11499. (list 'face
  11500. (cond
  11501. ((member tag current) c-face)
  11502. ((member tag inherited) i-face)
  11503. (t (get-text-property (match-beginning 1) '
  11504. face))))))))
  11505. (goto-char (point-min)))))
  11506. (delete-overlay org-tags-overlay)
  11507. (if rtn
  11508. (mapconcat 'identity current ":")
  11509. nil)))))
  11510. (defun org-make-tag-string (tags)
  11511. "Return string associated to TAGS.
  11512. TAGS is a list of strings."
  11513. (if (null tags) ""
  11514. (format ":%s:" (mapconcat #'identity tags ":"))))
  11515. (defun org--get-local-tags ()
  11516. "Return list of tags for the current headline.
  11517. Assume point is at the beginning of the headline."
  11518. (and (looking-at org-tag-line-re)
  11519. (split-string (match-string-no-properties 2) ":" t)))
  11520. (defun org-get-tags (&optional pos local)
  11521. "Get the list of tags specified in the current headline.
  11522. When argument POS is non-nil, retrieve tags for headline at POS.
  11523. According to `org-use-tag-inheritance', tags may be inherited
  11524. from parent headlines, and from the whole document, through
  11525. `org-file-tags'. In this case, the returned list of tags
  11526. contains tags in this order: file tags, tags inherited from
  11527. parent headlines, local tags.
  11528. However, when optional argument LOCAL is non-nil, only return
  11529. tags specified at the headline.
  11530. Inherited tags have the `inherited' text property."
  11531. (if (and org-trust-scanner-tags
  11532. (or (not pos) (eq pos (point)))
  11533. (not local))
  11534. org-scanner-tags
  11535. (org-with-point-at (or pos (point))
  11536. (unless (org-before-first-heading-p)
  11537. (org-back-to-heading t)
  11538. (let ((ltags (org--get-local-tags)) itags)
  11539. (if (or local (not org-use-tag-inheritance)) ltags
  11540. (while (org-up-heading-safe)
  11541. (setq itags (append (mapcar #'org-add-prop-inherited
  11542. (org--get-local-tags))
  11543. itags)))
  11544. (setq itags (append org-file-tags itags))
  11545. (delete-dups
  11546. (append (org-remove-uninherited-tags itags) ltags))))))))
  11547. (defun org-get-buffer-tags ()
  11548. "Get a table of all tags used in the buffer, for completion."
  11549. (org-with-point-at 1
  11550. (let (tags)
  11551. (while (re-search-forward org-tag-line-re nil t)
  11552. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11553. tags)))
  11554. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11555. ;;;; The mapping API
  11556. (defvar org-agenda-skip-comment-trees)
  11557. (defvar org-agenda-skip-function)
  11558. (defun org-map-entries (func &optional match scope &rest skip)
  11559. "Call FUNC at each headline selected by MATCH in SCOPE.
  11560. FUNC is a function or a lisp form. The function will be called without
  11561. arguments, with the cursor positioned at the beginning of the headline.
  11562. The return values of all calls to the function will be collected and
  11563. returned as a list.
  11564. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11565. does not need to preserve point. After evaluation, the cursor will be
  11566. moved to the end of the line (presumably of the headline of the
  11567. processed entry) and search continues from there. Under some
  11568. circumstances, this may not produce the wanted results. For example,
  11569. if you have removed (e.g. archived) the current (sub)tree it could
  11570. mean that the next entry will be skipped entirely. In such cases, you
  11571. can specify the position from where search should continue by making
  11572. FUNC set the variable `org-map-continue-from' to the desired buffer
  11573. position.
  11574. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11575. Only headlines that are matched by this query will be considered during
  11576. the iteration. When MATCH is nil or t, all headlines will be
  11577. visited by the iteration.
  11578. SCOPE determines the scope of this command. It can be any of:
  11579. nil The current buffer, respecting the restriction if any
  11580. tree The subtree started with the entry at point
  11581. region The entries within the active region, if any
  11582. region-start-level
  11583. The entries within the active region, but only those at
  11584. the same level than the first one.
  11585. file The current buffer, without restriction
  11586. file-with-archives
  11587. The current buffer, and any archives associated with it
  11588. agenda All agenda files
  11589. agenda-with-archives
  11590. All agenda files with any archive files associated with them
  11591. \(file1 file2 ...)
  11592. If this is a list, all files in the list will be scanned
  11593. The remaining args are treated as settings for the skipping facilities of
  11594. the scanner. The following items can be given here:
  11595. archive skip trees with the archive tag
  11596. comment skip trees with the COMMENT keyword
  11597. function or Emacs Lisp form:
  11598. will be used as value for `org-agenda-skip-function', so
  11599. whenever the function returns a position, FUNC will not be
  11600. called for that entry and search will continue from the
  11601. position returned
  11602. If your function needs to retrieve the tags including inherited tags
  11603. at the *current* entry, you can use the value of the variable
  11604. `org-scanner-tags' which will be much faster than getting the value
  11605. with `org-get-tags'. If your function gets properties with
  11606. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11607. to t around the call to `org-entry-properties' to get the same speedup.
  11608. Note that if your function moves around to retrieve tags and properties at
  11609. a *different* entry, you cannot use these techniques."
  11610. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11611. (not (org-region-active-p)))
  11612. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11613. (org-agenda-skip-archived-trees (memq 'archive skip))
  11614. (org-agenda-skip-comment-trees (memq 'comment skip))
  11615. (org-agenda-skip-function
  11616. (car (org-delete-all '(comment archive) skip)))
  11617. (org-tags-match-list-sublevels t)
  11618. (start-level (eq scope 'region-start-level))
  11619. matcher res
  11620. org-todo-keywords-for-agenda
  11621. org-done-keywords-for-agenda
  11622. org-todo-keyword-alist-for-agenda
  11623. org-tag-alist-for-agenda
  11624. org--matcher-tags-todo-only)
  11625. (cond
  11626. ((eq match t) (setq matcher t))
  11627. ((eq match nil) (setq matcher t))
  11628. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11629. (save-excursion
  11630. (save-restriction
  11631. (cond ((eq scope 'tree)
  11632. (org-back-to-heading t)
  11633. (org-narrow-to-subtree)
  11634. (setq scope nil))
  11635. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11636. (org-region-active-p))
  11637. ;; If needed, set start-level to a string like "2"
  11638. (when start-level
  11639. (save-excursion
  11640. (goto-char (region-beginning))
  11641. (unless (org-at-heading-p) (outline-next-heading))
  11642. (setq start-level (org-current-level))))
  11643. (narrow-to-region (region-beginning)
  11644. (save-excursion
  11645. (goto-char (region-end))
  11646. (unless (and (bolp) (org-at-heading-p))
  11647. (outline-next-heading))
  11648. (point)))
  11649. (setq scope nil)))
  11650. (if (not scope)
  11651. (progn
  11652. (org-agenda-prepare-buffers
  11653. (and buffer-file-name (list buffer-file-name)))
  11654. (setq res
  11655. (org-scan-tags
  11656. func matcher org--matcher-tags-todo-only start-level)))
  11657. ;; Get the right scope
  11658. (cond
  11659. ((and scope (listp scope) (symbolp (car scope)))
  11660. (setq scope (eval scope)))
  11661. ((eq scope 'agenda)
  11662. (setq scope (org-agenda-files t)))
  11663. ((eq scope 'agenda-with-archives)
  11664. (setq scope (org-agenda-files t))
  11665. (setq scope (org-add-archive-files scope)))
  11666. ((eq scope 'file)
  11667. (setq scope (and buffer-file-name (list buffer-file-name))))
  11668. ((eq scope 'file-with-archives)
  11669. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11670. (org-agenda-prepare-buffers scope)
  11671. (dolist (file scope)
  11672. (with-current-buffer (org-find-base-buffer-visiting file)
  11673. (org-with-wide-buffer
  11674. (goto-char (point-min))
  11675. (setq res
  11676. (append
  11677. res
  11678. (org-scan-tags
  11679. func matcher org--matcher-tags-todo-only)))))))))
  11680. res)))
  11681. ;;; Properties API
  11682. (defconst org-special-properties
  11683. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11684. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11685. "The special properties valid in Org mode.
  11686. These are properties that are not defined in the property drawer,
  11687. but in some other way.")
  11688. (defconst org-default-properties
  11689. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11690. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11691. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11692. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11693. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11694. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11695. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11696. "Some properties that are used by Org mode for various purposes.
  11697. Being in this list makes sure that they are offered for completion.")
  11698. (defun org--valid-property-p (property)
  11699. "Non nil when string PROPERTY is a valid property name."
  11700. (not
  11701. (or (equal property "")
  11702. (string-match-p "\\s-" property))))
  11703. (defun org--update-property-plist (key val props)
  11704. "Associate KEY to VAL in alist PROPS.
  11705. Modifications are made by side-effect. Return new alist."
  11706. (let* ((appending (string= (substring key -1) "+"))
  11707. (key (if appending (substring key 0 -1) key))
  11708. (old (assoc-string key props t)))
  11709. (if (not old) (cons (cons key val) props)
  11710. (setcdr old (if appending (concat (cdr old) " " val) val))
  11711. props)))
  11712. (defun org-get-property-block (&optional beg force)
  11713. "Return the (beg . end) range of the body of the property drawer.
  11714. BEG is the beginning of the current subtree, or of the part
  11715. before the first headline. If it is not given, it will be found.
  11716. If the drawer does not exist, create it if FORCE is non-nil, or
  11717. return nil."
  11718. (org-with-wide-buffer
  11719. (when beg (goto-char beg))
  11720. (unless (org-before-first-heading-p)
  11721. (let ((beg (cond (beg)
  11722. ((or (not (featurep 'org-inlinetask))
  11723. (org-inlinetask-in-task-p))
  11724. (org-back-to-heading t))
  11725. (t (org-with-limited-levels (org-back-to-heading t))))))
  11726. (forward-line)
  11727. (when (looking-at-p org-planning-line-re) (forward-line))
  11728. (cond ((looking-at org-property-drawer-re)
  11729. (forward-line)
  11730. (cons (point) (progn (goto-char (match-end 0))
  11731. (line-beginning-position))))
  11732. (force
  11733. (goto-char beg)
  11734. (org-insert-property-drawer)
  11735. (let ((pos (save-excursion (search-forward ":END:")
  11736. (line-beginning-position))))
  11737. (cons pos pos))))))))
  11738. (defun org-at-property-p ()
  11739. "Non-nil when point is inside a property drawer.
  11740. See `org-property-re' for match data, if applicable."
  11741. (save-excursion
  11742. (beginning-of-line)
  11743. (and (looking-at org-property-re)
  11744. (let ((property-drawer (save-match-data (org-get-property-block))))
  11745. (and property-drawer
  11746. (>= (point) (car property-drawer))
  11747. (< (point) (cdr property-drawer)))))))
  11748. (defun org-property-action ()
  11749. "Do an action on properties."
  11750. (interactive)
  11751. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11752. (let ((c (read-char-exclusive)))
  11753. (cl-case c
  11754. (?s (call-interactively #'org-set-property))
  11755. (?d (call-interactively #'org-delete-property))
  11756. (?D (call-interactively #'org-delete-property-globally))
  11757. (?c (call-interactively #'org-compute-property-at-point))
  11758. (otherwise (user-error "No such property action %c" c)))))
  11759. (defun org-inc-effort ()
  11760. "Increment the value of the effort property in the current entry."
  11761. (interactive)
  11762. (org-set-effort t))
  11763. (defvar org-clock-effort) ; Defined in org-clock.el.
  11764. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11765. (defun org-set-effort (&optional increment value)
  11766. "Set the effort property of the current entry.
  11767. If INCREMENT is non-nil, set the property to the next allowed
  11768. value. Otherwise, if optional argument VALUE is provided, use
  11769. it. Eventually, prompt for the new value if none of the previous
  11770. variables is set."
  11771. (interactive "P")
  11772. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11773. (current (org-entry-get nil org-effort-property))
  11774. (value
  11775. (cond
  11776. (increment
  11777. (unless allowed (user-error "Allowed effort values are not set"))
  11778. (or (cl-caadr (member (list current) allowed))
  11779. (user-error "Unknown value %S among allowed values" current)))
  11780. (value
  11781. (if (stringp value) value
  11782. (error "Invalid effort value: %S" value)))
  11783. (t
  11784. (let ((must-match
  11785. (and allowed
  11786. (not (get-text-property 0 'org-unrestricted
  11787. (caar allowed))))))
  11788. (completing-read "Effort: " allowed nil must-match))))))
  11789. (unless (equal current value)
  11790. (org-entry-put nil org-effort-property value))
  11791. (org-refresh-property '((effort . identity)
  11792. (effort-minutes . org-duration-to-minutes))
  11793. value)
  11794. (when (equal (org-get-heading t t t t)
  11795. (bound-and-true-p org-clock-current-task))
  11796. (setq org-clock-effort value)
  11797. (org-clock-update-mode-line))
  11798. (message "%s is now %s" org-effort-property value)))
  11799. (defun org-entry-properties (&optional pom which)
  11800. "Get all properties of the current entry.
  11801. When POM is a buffer position, get all properties from the entry
  11802. there instead.
  11803. This includes the TODO keyword, the tags, time strings for
  11804. deadline, scheduled, and clocking, and any additional properties
  11805. defined in the entry.
  11806. If WHICH is nil or `all', get all properties. If WHICH is
  11807. `special' or `standard', only get that subclass. If WHICH is
  11808. a string, only get that property.
  11809. Return value is an alist. Keys are properties, as upcased
  11810. strings."
  11811. (org-with-point-at pom
  11812. (when (and (derived-mode-p 'org-mode)
  11813. (ignore-errors (org-back-to-heading t)))
  11814. (catch 'exit
  11815. (let* ((beg (point))
  11816. (specific (and (stringp which) (upcase which)))
  11817. (which (cond ((not specific) which)
  11818. ((member specific org-special-properties) 'special)
  11819. (t 'standard)))
  11820. props)
  11821. ;; Get the special properties, like TODO and TAGS.
  11822. (when (memq which '(nil all special))
  11823. (when (or (not specific) (string= specific "CLOCKSUM"))
  11824. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11825. (when clocksum
  11826. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11827. props)))
  11828. (when specific (throw 'exit props)))
  11829. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11830. (let ((clocksumt (get-text-property (point)
  11831. :org-clock-minutes-today)))
  11832. (when clocksumt
  11833. (push (cons "CLOCKSUM_T"
  11834. (org-duration-from-minutes clocksumt))
  11835. props)))
  11836. (when specific (throw 'exit props)))
  11837. (when (or (not specific) (string= specific "ITEM"))
  11838. (let ((case-fold-search nil))
  11839. (when (looking-at org-complex-heading-regexp)
  11840. (push (cons "ITEM"
  11841. (let ((title (match-string-no-properties 4)))
  11842. (if (org-string-nw-p title)
  11843. (org-remove-tabs title)
  11844. "")))
  11845. props)))
  11846. (when specific (throw 'exit props)))
  11847. (when (or (not specific) (string= specific "TODO"))
  11848. (let ((case-fold-search nil))
  11849. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11850. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11851. (when specific (throw 'exit props)))
  11852. (when (or (not specific) (string= specific "PRIORITY"))
  11853. (push (cons "PRIORITY"
  11854. (if (looking-at org-priority-regexp)
  11855. (match-string-no-properties 2)
  11856. (char-to-string org-default-priority)))
  11857. props)
  11858. (when specific (throw 'exit props)))
  11859. (when (or (not specific) (string= specific "FILE"))
  11860. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11861. props)
  11862. (when specific (throw 'exit props)))
  11863. (when (or (not specific) (string= specific "TAGS"))
  11864. (let ((tags (org-get-tags nil t)))
  11865. (when tags
  11866. (push (cons "TAGS" (org-make-tag-string tags))
  11867. props)))
  11868. (when specific (throw 'exit props)))
  11869. (when (or (not specific) (string= specific "ALLTAGS"))
  11870. (let ((tags (org-get-tags)))
  11871. (when tags
  11872. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11873. props)))
  11874. (when specific (throw 'exit props)))
  11875. (when (or (not specific) (string= specific "BLOCKED"))
  11876. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11877. (when specific (throw 'exit props)))
  11878. (when (or (not specific)
  11879. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11880. (forward-line)
  11881. (when (looking-at-p org-planning-line-re)
  11882. (end-of-line)
  11883. (let ((bol (line-beginning-position))
  11884. ;; Backward compatibility: time keywords used to
  11885. ;; be configurable (before 8.3). Make sure we
  11886. ;; get the correct keyword.
  11887. (key-assoc `(("CLOSED" . ,org-closed-string)
  11888. ("DEADLINE" . ,org-deadline-string)
  11889. ("SCHEDULED" . ,org-scheduled-string))))
  11890. (dolist (pair (if specific (list (assoc specific key-assoc))
  11891. key-assoc))
  11892. (save-excursion
  11893. (when (search-backward (cdr pair) bol t)
  11894. (goto-char (match-end 0))
  11895. (skip-chars-forward " \t")
  11896. (and (looking-at org-ts-regexp-both)
  11897. (push (cons (car pair)
  11898. (match-string-no-properties 0))
  11899. props)))))))
  11900. (when specific (throw 'exit props)))
  11901. (when (or (not specific)
  11902. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11903. (let ((find-ts
  11904. (lambda (end ts)
  11905. ;; Fix next time-stamp before END. TS is the
  11906. ;; list of time-stamps found so far.
  11907. (let ((ts ts)
  11908. (regexp (cond
  11909. ((string= specific "TIMESTAMP")
  11910. org-ts-regexp)
  11911. ((string= specific "TIMESTAMP_IA")
  11912. org-ts-regexp-inactive)
  11913. ((assoc "TIMESTAMP_IA" ts)
  11914. org-ts-regexp)
  11915. ((assoc "TIMESTAMP" ts)
  11916. org-ts-regexp-inactive)
  11917. (t org-ts-regexp-both))))
  11918. (catch 'next
  11919. (while (re-search-forward regexp end t)
  11920. (backward-char)
  11921. (let ((object (org-element-context)))
  11922. ;; Accept to match timestamps in node
  11923. ;; properties, too.
  11924. (when (memq (org-element-type object)
  11925. '(node-property timestamp))
  11926. (let ((type
  11927. (org-element-property :type object)))
  11928. (cond
  11929. ((and (memq type '(active active-range))
  11930. (not (equal specific "TIMESTAMP_IA")))
  11931. (unless (assoc "TIMESTAMP" ts)
  11932. (push (cons "TIMESTAMP"
  11933. (org-element-property
  11934. :raw-value object))
  11935. ts)
  11936. (when specific (throw 'exit ts))))
  11937. ((and (memq type '(inactive inactive-range))
  11938. (not (string= specific "TIMESTAMP")))
  11939. (unless (assoc "TIMESTAMP_IA" ts)
  11940. (push (cons "TIMESTAMP_IA"
  11941. (org-element-property
  11942. :raw-value object))
  11943. ts)
  11944. (when specific (throw 'exit ts))))))
  11945. ;; Both timestamp types are found,
  11946. ;; move to next part.
  11947. (when (= (length ts) 2) (throw 'next ts)))))
  11948. ts)))))
  11949. (goto-char beg)
  11950. ;; First look for timestamps within headline.
  11951. (let ((ts (funcall find-ts (line-end-position) nil)))
  11952. (if (= (length ts) 2) (setq props (nconc ts props))
  11953. ;; Then find timestamps in the section, skipping
  11954. ;; planning line.
  11955. (let ((end (save-excursion (outline-next-heading))))
  11956. (forward-line)
  11957. (when (looking-at-p org-planning-line-re) (forward-line))
  11958. (setq props (nconc (funcall find-ts end ts) props))))))))
  11959. ;; Get the standard properties, like :PROP:.
  11960. (when (memq which '(nil all standard))
  11961. ;; If we are looking after a specific property, delegate
  11962. ;; to `org-entry-get', which is faster. However, make an
  11963. ;; exception for "CATEGORY", since it can be also set
  11964. ;; through keywords (i.e. #+CATEGORY).
  11965. (if (and specific (not (equal specific "CATEGORY")))
  11966. (let ((value (org-entry-get beg specific nil t)))
  11967. (throw 'exit (and value (list (cons specific value)))))
  11968. (let ((range (org-get-property-block beg)))
  11969. (when range
  11970. (let ((end (cdr range)) seen-base)
  11971. (goto-char (car range))
  11972. ;; Unlike to `org--update-property-plist', we
  11973. ;; handle the case where base values is found
  11974. ;; after its extension. We also forbid standard
  11975. ;; properties to be named as special properties.
  11976. (while (re-search-forward org-property-re end t)
  11977. (let* ((key (upcase (match-string-no-properties 2)))
  11978. (extendp (string-match-p "\\+\\'" key))
  11979. (key-base (if extendp (substring key 0 -1) key))
  11980. (value (match-string-no-properties 3)))
  11981. (cond
  11982. ((member-ignore-case key-base org-special-properties))
  11983. (extendp
  11984. (setq props
  11985. (org--update-property-plist key value props)))
  11986. ((member key seen-base))
  11987. (t (push key seen-base)
  11988. (let ((p (assoc-string key props t)))
  11989. (if p (setcdr p (concat value " " (cdr p)))
  11990. (push (cons key value) props))))))))))))
  11991. (unless (assoc "CATEGORY" props)
  11992. (push (cons "CATEGORY" (org-get-category beg)) props)
  11993. (when (string= specific "CATEGORY") (throw 'exit props)))
  11994. ;; Return value.
  11995. props)))))
  11996. (defun org--property-local-values (property literal-nil)
  11997. "Return value for PROPERTY in current entry.
  11998. Value is a list whose car is the base value for PROPERTY and cdr
  11999. a list of accumulated values. Return nil if neither is found in
  12000. the entry. Also return nil when PROPERTY is set to \"nil\",
  12001. unless LITERAL-NIL is non-nil."
  12002. (let ((range (org-get-property-block)))
  12003. (when range
  12004. (goto-char (car range))
  12005. (let* ((case-fold-search t)
  12006. (end (cdr range))
  12007. (value
  12008. ;; Base value.
  12009. (save-excursion
  12010. (let ((v (and (re-search-forward
  12011. (org-re-property property nil t) end t)
  12012. (match-string-no-properties 3))))
  12013. (list (if literal-nil v (org-not-nil v)))))))
  12014. ;; Find additional values.
  12015. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12016. (while (re-search-forward property+ end t)
  12017. (push (match-string-no-properties 3) value)))
  12018. ;; Return final values.
  12019. (and (not (equal value '(nil))) (nreverse value))))))
  12020. (defun org--property-global-value (property literal-nil)
  12021. "Return value for PROPERTY in current buffer.
  12022. Return value is a string. Return nil if property is not set
  12023. globally. Also return nil when PROPERTY is set to \"nil\",
  12024. unless LITERAL-NIL is non-nil."
  12025. (let ((global
  12026. (cdr (or (assoc-string property org-file-properties t)
  12027. (assoc-string property org-global-properties t)
  12028. (assoc-string property org-global-properties-fixed t)))))
  12029. (if literal-nil global (org-not-nil global))))
  12030. (defun org-entry-get (pom property &optional inherit literal-nil)
  12031. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12032. If INHERIT is non-nil and the entry does not have the property,
  12033. then also check higher levels of the hierarchy. If INHERIT is
  12034. the symbol `selective', use inheritance only if the setting in
  12035. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12036. If the property is present but empty, the return value is the
  12037. empty string. If the property is not present at all, nil is
  12038. returned. In any other case, return the value as a string.
  12039. Search is case-insensitive.
  12040. If LITERAL-NIL is set, return the string value \"nil\" as
  12041. a string, do not interpret it as the list atom nil. This is used
  12042. for inheritance when a \"nil\" value can supersede a non-nil
  12043. value higher up the hierarchy."
  12044. (org-with-point-at pom
  12045. (cond
  12046. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12047. ;; We need a special property. Use `org-entry-properties' to
  12048. ;; retrieve it, but specify the wanted property.
  12049. (cdr (assoc-string property (org-entry-properties nil property))))
  12050. ((and inherit
  12051. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12052. (org-entry-get-with-inheritance property literal-nil))
  12053. (t
  12054. (let* ((local (org--property-local-values property literal-nil))
  12055. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12056. (if literal-nil value (org-not-nil value)))))))
  12057. (defun org-property-or-variable-value (var &optional inherit)
  12058. "Check if there is a property fixing the value of VAR.
  12059. If yes, return this value. If not, return the current value of the variable."
  12060. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12061. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12062. (read prop)
  12063. (symbol-value var))))
  12064. (defun org-entry-delete (pom property)
  12065. "Delete PROPERTY from entry at point-or-marker POM.
  12066. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12067. non-nil when a property was removed."
  12068. (org-with-point-at pom
  12069. (pcase (org-get-property-block)
  12070. (`(,begin . ,origin)
  12071. (let* ((end (copy-marker origin))
  12072. (re (org-re-property
  12073. (concat (regexp-quote property) "\\+?") t t)))
  12074. (goto-char begin)
  12075. (while (re-search-forward re end t)
  12076. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12077. ;; If drawer is empty, remove it altogether.
  12078. (when (= begin end)
  12079. (delete-region (line-beginning-position 0)
  12080. (line-beginning-position 2)))
  12081. ;; Return non-nil if some property was removed.
  12082. (prog1 (/= end origin) (set-marker end nil))))
  12083. (_ nil))))
  12084. ;; Multi-values properties are properties that contain multiple values
  12085. ;; These values are assumed to be single words, separated by whitespace.
  12086. (defun org-entry-add-to-multivalued-property (pom property value)
  12087. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12088. (let* ((old (org-entry-get pom property))
  12089. (values (and old (split-string old))))
  12090. (setq value (org-entry-protect-space value))
  12091. (unless (member value values)
  12092. (setq values (append values (list value)))
  12093. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12094. (defun org-entry-remove-from-multivalued-property (pom property value)
  12095. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12096. (let* ((old (org-entry-get pom property))
  12097. (values (and old (split-string old))))
  12098. (setq value (org-entry-protect-space value))
  12099. (when (member value values)
  12100. (setq values (delete value values))
  12101. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12102. (defun org-entry-member-in-multivalued-property (pom property value)
  12103. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12104. (let* ((old (org-entry-get pom property))
  12105. (values (and old (split-string old))))
  12106. (setq value (org-entry-protect-space value))
  12107. (member value values)))
  12108. (defun org-entry-get-multivalued-property (pom property)
  12109. "Return a list of values in a multivalued property."
  12110. (let* ((value (org-entry-get pom property))
  12111. (values (and value (split-string value))))
  12112. (mapcar #'org-entry-restore-space values)))
  12113. (defun org-entry-put-multivalued-property (pom property &rest values)
  12114. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12115. VALUES should be a list of strings. Spaces will be protected."
  12116. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12117. (let* ((value (org-entry-get pom property))
  12118. (values (and value (split-string value))))
  12119. (mapcar #'org-entry-restore-space values)))
  12120. (defun org-entry-protect-space (s)
  12121. "Protect spaces and newline in string S."
  12122. (while (string-match " " s)
  12123. (setq s (replace-match "%20" t t s)))
  12124. (while (string-match "\n" s)
  12125. (setq s (replace-match "%0A" t t s)))
  12126. s)
  12127. (defun org-entry-restore-space (s)
  12128. "Restore spaces and newline in string S."
  12129. (while (string-match "%20" s)
  12130. (setq s (replace-match " " t t s)))
  12131. (while (string-match "%0A" s)
  12132. (setq s (replace-match "\n" t t s)))
  12133. s)
  12134. (defvar org-entry-property-inherited-from (make-marker)
  12135. "Marker pointing to the entry from where a property was inherited.
  12136. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12137. location of the entry where the inheritance search matched. If there was
  12138. no match, the marker will point nowhere.
  12139. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12140. is set.")
  12141. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12142. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12143. The search will stop at the first ancestor which has the property defined.
  12144. If the value found is \"nil\", return nil to show that the property
  12145. should be considered as undefined (this is the meaning of nil here).
  12146. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12147. (move-marker org-entry-property-inherited-from nil)
  12148. (org-with-wide-buffer
  12149. (let (value)
  12150. (catch 'exit
  12151. (while t
  12152. (let ((v (org--property-local-values property literal-nil)))
  12153. (when v
  12154. (setq value
  12155. (concat (mapconcat #'identity (delq nil v) " ")
  12156. (and value " ")
  12157. value)))
  12158. (cond
  12159. ((car v)
  12160. (org-back-to-heading t)
  12161. (move-marker org-entry-property-inherited-from (point))
  12162. (throw 'exit nil))
  12163. ((org-up-heading-safe))
  12164. (t
  12165. (let ((global (org--property-global-value property literal-nil)))
  12166. (cond ((not global))
  12167. (value (setq value (concat global " " value)))
  12168. (t (setq value global))))
  12169. (throw 'exit nil))))))
  12170. (if literal-nil value (org-not-nil value)))))
  12171. (defvar org-property-changed-functions nil
  12172. "Hook called when the value of a property has changed.
  12173. Each hook function should accept two arguments, the name of the property
  12174. and the new value.")
  12175. (defun org-entry-put (pom property value)
  12176. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12177. If the value is nil, it is converted to the empty string. If it
  12178. is not a string, an error is raised. Also raise an error on
  12179. invalid property names.
  12180. PROPERTY can be any regular property (see
  12181. `org-special-properties'). It can also be \"TODO\",
  12182. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12183. For the last two properties, VALUE may have any of the special
  12184. values \"earlier\" and \"later\". The function then increases or
  12185. decreases scheduled or deadline date by one day."
  12186. (cond ((null value) (setq value ""))
  12187. ((not (stringp value)) (error "Properties values should be strings"))
  12188. ((not (org--valid-property-p property))
  12189. (user-error "Invalid property name: \"%s\"" property)))
  12190. (org-with-point-at pom
  12191. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12192. (org-back-to-heading t)
  12193. (org-with-limited-levels (org-back-to-heading t)))
  12194. (let ((beg (point)))
  12195. (cond
  12196. ((equal property "TODO")
  12197. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12198. ((not (member value org-todo-keywords-1))
  12199. (user-error "\"%s\" is not a valid TODO state" value)))
  12200. (org-todo value)
  12201. (org-align-tags))
  12202. ((equal property "PRIORITY")
  12203. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12204. (org-align-tags))
  12205. ((equal property "SCHEDULED")
  12206. (forward-line)
  12207. (if (and (looking-at-p org-planning-line-re)
  12208. (re-search-forward
  12209. org-scheduled-time-regexp (line-end-position) t))
  12210. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12211. ((string= value "later") (org-timestamp-change 1 'day))
  12212. ((string= value "") (org-schedule '(4)))
  12213. (t (org-schedule nil value)))
  12214. (if (member value '("earlier" "later" ""))
  12215. (call-interactively #'org-schedule)
  12216. (org-schedule nil value))))
  12217. ((equal property "DEADLINE")
  12218. (forward-line)
  12219. (if (and (looking-at-p org-planning-line-re)
  12220. (re-search-forward
  12221. org-deadline-time-regexp (line-end-position) t))
  12222. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12223. ((string= value "later") (org-timestamp-change 1 'day))
  12224. ((string= value "") (org-deadline '(4)))
  12225. (t (org-deadline nil value)))
  12226. (if (member value '("earlier" "later" ""))
  12227. (call-interactively #'org-deadline)
  12228. (org-deadline nil value))))
  12229. ((member property org-special-properties)
  12230. (error "The %s property cannot be set with `org-entry-put'" property))
  12231. (t
  12232. (let* ((range (org-get-property-block beg 'force))
  12233. (end (cdr range))
  12234. (case-fold-search t))
  12235. (goto-char (car range))
  12236. (if (re-search-forward (org-re-property property nil t) end t)
  12237. (progn (delete-region (match-beginning 0) (match-end 0))
  12238. (goto-char (match-beginning 0)))
  12239. (goto-char end)
  12240. (insert "\n")
  12241. (backward-char))
  12242. (insert ":" property ":")
  12243. (when value (insert " " value))
  12244. (org-indent-line)))))
  12245. (run-hook-with-args 'org-property-changed-functions property value)))
  12246. (defun org-buffer-property-keys (&optional specials defaults columns)
  12247. "Get all property keys in the current buffer.
  12248. When SPECIALS is non-nil, also list the special properties that
  12249. reflect things like tags and TODO state.
  12250. When DEFAULTS is non-nil, also include properties that has
  12251. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12252. DESCRIPTION, LOCATION, and LOGGING and others.
  12253. When COLUMNS in non-nil, also include property names given in
  12254. COLUMN formats in the current buffer."
  12255. (let ((case-fold-search t)
  12256. (props (append
  12257. (and specials org-special-properties)
  12258. (and defaults (cons org-effort-property org-default-properties))
  12259. nil)))
  12260. (org-with-wide-buffer
  12261. (goto-char (point-min))
  12262. (while (re-search-forward org-property-start-re nil t)
  12263. (catch :skip
  12264. (let ((range (org-get-property-block)))
  12265. (unless range (throw :skip nil))
  12266. (goto-char (car range))
  12267. (let ((begin (car range))
  12268. (end (cdr range)))
  12269. ;; Make sure that found property block is not located
  12270. ;; before current point, as it would generate an infloop.
  12271. ;; It can happen, for example, in the following
  12272. ;; situation:
  12273. ;;
  12274. ;; * Headline
  12275. ;; :PROPERTIES:
  12276. ;; ...
  12277. ;; :END:
  12278. ;; *************** Inlinetask
  12279. ;; #+BEGIN_EXAMPLE
  12280. ;; :PROPERTIES:
  12281. ;; #+END_EXAMPLE
  12282. ;;
  12283. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12284. (while (< (point) end)
  12285. (let ((p (progn (looking-at org-property-re)
  12286. (match-string-no-properties 2))))
  12287. ;; Only add true property name, not extension symbol.
  12288. (push (if (not (string-match-p "\\+\\'" p)) p
  12289. (substring p 0 -1))
  12290. props))
  12291. (forward-line))))
  12292. (outline-next-heading)))
  12293. (when columns
  12294. (goto-char (point-min))
  12295. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12296. (let ((element (org-element-at-point)))
  12297. (when (memq (org-element-type element) '(keyword node-property))
  12298. (let ((value (org-element-property :value element))
  12299. (start 0))
  12300. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12301. \\(?:{[^}]+}\\)?"
  12302. value start)
  12303. (setq start (match-end 0))
  12304. (let ((p (match-string-no-properties 1 value)))
  12305. (unless (member-ignore-case p org-special-properties)
  12306. (push p props))))))))))
  12307. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12308. (defun org-property-values (key)
  12309. "List all non-nil values of property KEY in current buffer."
  12310. (org-with-wide-buffer
  12311. (goto-char (point-min))
  12312. (let ((case-fold-search t)
  12313. (re (org-re-property key))
  12314. values)
  12315. (while (re-search-forward re nil t)
  12316. (push (org-entry-get (point) key) values))
  12317. (delete-dups values))))
  12318. (defun org-insert-property-drawer ()
  12319. "Insert a property drawer into the current entry."
  12320. (org-with-wide-buffer
  12321. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12322. (org-back-to-heading t)
  12323. (org-with-limited-levels (org-back-to-heading t)))
  12324. (forward-line)
  12325. (when (looking-at-p org-planning-line-re) (forward-line))
  12326. (unless (looking-at-p org-property-drawer-re)
  12327. ;; Make sure we start editing a line from current entry, not from
  12328. ;; next one. It prevents extending text properties or overlays
  12329. ;; belonging to the latter.
  12330. (when (bolp) (backward-char))
  12331. (let ((begin (1+ (point)))
  12332. (inhibit-read-only t))
  12333. (insert "\n:PROPERTIES:\n:END:")
  12334. (when (eobp) (insert "\n"))
  12335. (org-indent-region begin (point))))))
  12336. (defun org-insert-drawer (&optional arg drawer)
  12337. "Insert a drawer at point.
  12338. When optional argument ARG is non-nil, insert a property drawer.
  12339. Optional argument DRAWER, when non-nil, is a string representing
  12340. drawer's name. Otherwise, the user is prompted for a name.
  12341. If a region is active, insert the drawer around that region
  12342. instead.
  12343. Point is left between drawer's boundaries."
  12344. (interactive "P")
  12345. (let* ((drawer (if arg "PROPERTIES"
  12346. (or drawer (read-from-minibuffer "Drawer: ")))))
  12347. (cond
  12348. ;; With C-u, fall back on `org-insert-property-drawer'
  12349. (arg (org-insert-property-drawer))
  12350. ;; Check validity of suggested drawer's name.
  12351. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12352. (user-error "Invalid drawer name"))
  12353. ;; With an active region, insert a drawer at point.
  12354. ((not (org-region-active-p))
  12355. (progn
  12356. (unless (bolp) (insert "\n"))
  12357. (insert (format ":%s:\n\n:END:\n" drawer))
  12358. (forward-line -2)))
  12359. ;; Otherwise, insert the drawer at point
  12360. (t
  12361. (let ((rbeg (region-beginning))
  12362. (rend (copy-marker (region-end))))
  12363. (unwind-protect
  12364. (progn
  12365. (goto-char rbeg)
  12366. (beginning-of-line)
  12367. (when (save-excursion
  12368. (re-search-forward org-outline-regexp-bol rend t))
  12369. (user-error "Drawers cannot contain headlines"))
  12370. ;; Position point at the beginning of the first
  12371. ;; non-blank line in region. Insert drawer's opening
  12372. ;; there, then indent it.
  12373. (org-skip-whitespace)
  12374. (beginning-of-line)
  12375. (insert ":" drawer ":\n")
  12376. (forward-line -1)
  12377. (indent-for-tab-command)
  12378. ;; Move point to the beginning of the first blank line
  12379. ;; after the last non-blank line in region. Insert
  12380. ;; drawer's closing, then indent it.
  12381. (goto-char rend)
  12382. (skip-chars-backward " \r\t\n")
  12383. (insert "\n:END:")
  12384. (deactivate-mark t)
  12385. (indent-for-tab-command)
  12386. (unless (eolp) (insert "\n")))
  12387. ;; Clear marker, whatever the outcome of insertion is.
  12388. (set-marker rend nil)))))))
  12389. (defvar org-property-set-functions-alist nil
  12390. "Property set function alist.
  12391. Each entry should have the following format:
  12392. (PROPERTY . READ-FUNCTION)
  12393. The read function will be called with the same argument as
  12394. `org-completing-read'.")
  12395. (defun org-set-property-function (property)
  12396. "Get the function that should be used to set PROPERTY.
  12397. This is computed according to `org-property-set-functions-alist'."
  12398. (or (cdr (assoc property org-property-set-functions-alist))
  12399. 'org-completing-read))
  12400. (defun org-read-property-value (property &optional pom)
  12401. "Read value for PROPERTY, as a string.
  12402. When optional argument POM is non-nil, completion uses additional
  12403. information, i.e., allowed or existing values at point or marker
  12404. POM."
  12405. (let* ((completion-ignore-case t)
  12406. (allowed
  12407. (or (org-property-get-allowed-values nil property 'table)
  12408. (and pom (org-property-get-allowed-values pom property 'table))))
  12409. (current (org-entry-get nil property))
  12410. (prompt (format "%s value%s: "
  12411. property
  12412. (if (org-string-nw-p current)
  12413. (format " [%s]" current)
  12414. "")))
  12415. (set-function (org-set-property-function property)))
  12416. (org-trim
  12417. (if allowed
  12418. (funcall set-function
  12419. prompt allowed nil
  12420. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12421. (let ((all (mapcar #'list
  12422. (append (org-property-values property)
  12423. (and pom
  12424. (org-with-point-at pom
  12425. (org-property-values property)))))))
  12426. (funcall set-function prompt all nil nil "" nil current))))))
  12427. (defvar org-last-set-property nil)
  12428. (defvar org-last-set-property-value nil)
  12429. (defun org-read-property-name ()
  12430. "Read a property name."
  12431. (let ((completion-ignore-case t)
  12432. (default-prop (or (and (org-at-property-p)
  12433. (match-string-no-properties 2))
  12434. org-last-set-property)))
  12435. (org-completing-read
  12436. (concat "Property"
  12437. (if default-prop (concat " [" default-prop "]") "")
  12438. ": ")
  12439. (mapcar #'list (org-buffer-property-keys nil t t))
  12440. nil nil nil nil default-prop)))
  12441. (defun org-set-property-and-value (use-last)
  12442. "Allow to set [PROPERTY]: [value] direction from prompt.
  12443. When use-default, don't even ask, just use the last
  12444. \"[PROPERTY]: [value]\" string from the history."
  12445. (interactive "P")
  12446. (let* ((completion-ignore-case t)
  12447. (pv (or (and use-last org-last-set-property-value)
  12448. (org-completing-read
  12449. "Enter a \"[Property]: [value]\" pair: "
  12450. nil nil nil nil nil
  12451. org-last-set-property-value)))
  12452. prop val)
  12453. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12454. (setq prop (match-string 1 pv)
  12455. val (match-string 2 pv))
  12456. (org-set-property prop val))))
  12457. (defun org-set-property (property value)
  12458. "In the current entry, set PROPERTY to VALUE.
  12459. When called interactively, this will prompt for a property name, offering
  12460. completion on existing and default properties. And then it will prompt
  12461. for a value, offering completion either on allowed values (via an inherited
  12462. xxx_ALL property) or on existing values in other instances of this property
  12463. in the current file.
  12464. Throw an error when trying to set a property with an invalid name."
  12465. (interactive (list nil nil))
  12466. (let ((property (or property (org-read-property-name))))
  12467. ;; `org-entry-put' also makes the following check, but this one
  12468. ;; avoids polluting `org-last-set-property' and
  12469. ;; `org-last-set-property-value' needlessly.
  12470. (unless (org--valid-property-p property)
  12471. (user-error "Invalid property name: \"%s\"" property))
  12472. (let ((value (or value (org-read-property-value property)))
  12473. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12474. (setq org-last-set-property property)
  12475. (setq org-last-set-property-value (concat property ": " value))
  12476. ;; Possibly postprocess the inserted value:
  12477. (when fn (setq value (funcall fn value)))
  12478. (unless (equal (org-entry-get nil property) value)
  12479. (org-entry-put nil property value)))))
  12480. (defun org-find-property (property &optional value)
  12481. "Find first entry in buffer that sets PROPERTY.
  12482. When optional argument VALUE is non-nil, only consider an entry
  12483. if it contains PROPERTY set to this value. If PROPERTY should be
  12484. explicitly set to nil, use string \"nil\" for VALUE.
  12485. Return position where the entry begins, or nil if there is no
  12486. such entry. If narrowing is in effect, only search the visible
  12487. part of the buffer."
  12488. (save-excursion
  12489. (goto-char (point-min))
  12490. (let ((case-fold-search t)
  12491. (re (org-re-property property nil (not value) value)))
  12492. (catch 'exit
  12493. (while (re-search-forward re nil t)
  12494. (when (if value (org-at-property-p)
  12495. (org-entry-get (point) property nil t))
  12496. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12497. (defun org-delete-property (property)
  12498. "In the current entry, delete PROPERTY."
  12499. (interactive
  12500. (let* ((completion-ignore-case t)
  12501. (cat (org-entry-get (point) "CATEGORY"))
  12502. (props0 (org-entry-properties nil 'standard))
  12503. (props (if cat props0
  12504. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12505. (prop (if (< 1 (length props))
  12506. (completing-read "Property: " props nil t)
  12507. (caar props))))
  12508. (list prop)))
  12509. (if (not property)
  12510. (message "No property to delete in this entry")
  12511. (org-entry-delete nil property)
  12512. (message "Property \"%s\" deleted" property)))
  12513. (defun org-delete-property-globally (property)
  12514. "Remove PROPERTY globally, from all entries.
  12515. This function ignores narrowing, if any."
  12516. (interactive
  12517. (let* ((completion-ignore-case t)
  12518. (prop (completing-read
  12519. "Globally remove property: "
  12520. (mapcar #'list (org-buffer-property-keys)))))
  12521. (list prop)))
  12522. (org-with-wide-buffer
  12523. (goto-char (point-min))
  12524. (let ((count 0)
  12525. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12526. (while (re-search-forward re nil t)
  12527. (when (org-entry-delete (point) property) (cl-incf count)))
  12528. (message "Property \"%s\" removed from %d entries" property count))))
  12529. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12530. (defun org-compute-property-at-point ()
  12531. "Compute the property at point.
  12532. This looks for an enclosing column format, extracts the operator and
  12533. then applies it to the property in the column format's scope."
  12534. (interactive)
  12535. (unless (org-at-property-p)
  12536. (user-error "Not at a property"))
  12537. (let ((prop (match-string-no-properties 2)))
  12538. (org-columns-get-format-and-top-level)
  12539. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12540. (user-error "No operator defined for property %s" prop))
  12541. (org-columns-compute prop)))
  12542. (defvar org-property-allowed-value-functions nil
  12543. "Hook for functions supplying allowed values for a specific property.
  12544. The functions must take a single argument, the name of the property, and
  12545. return a flat list of allowed values. If \":ETC\" is one of
  12546. the values, this means that these values are intended as defaults for
  12547. completion, but that other values should be allowed too.
  12548. The functions must return nil if they are not responsible for this
  12549. property.")
  12550. (defun org-property-get-allowed-values (pom property &optional table)
  12551. "Get allowed values for the property PROPERTY.
  12552. When TABLE is non-nil, return an alist that can directly be used for
  12553. completion."
  12554. (let (vals)
  12555. (cond
  12556. ((equal property "TODO")
  12557. (setq vals (org-with-point-at pom
  12558. (append org-todo-keywords-1 '("")))))
  12559. ((equal property "PRIORITY")
  12560. (let ((n org-lowest-priority))
  12561. (while (>= n org-highest-priority)
  12562. (push (char-to-string n) vals)
  12563. (setq n (1- n)))))
  12564. ((equal property "CATEGORY"))
  12565. ((member property org-special-properties))
  12566. ((setq vals (run-hook-with-args-until-success
  12567. 'org-property-allowed-value-functions property)))
  12568. (t
  12569. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12570. (when (and vals (string-match "\\S-" vals))
  12571. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12572. (setq vals (mapcar (lambda (x)
  12573. (cond ((stringp x) x)
  12574. ((numberp x) (number-to-string x))
  12575. ((symbolp x) (symbol-name x))
  12576. (t "???")))
  12577. vals)))))
  12578. (when (member ":ETC" vals)
  12579. (setq vals (remove ":ETC" vals))
  12580. (org-add-props (car vals) '(org-unrestricted t)))
  12581. (if table (mapcar 'list vals) vals)))
  12582. (defun org-property-previous-allowed-value (&optional _previous)
  12583. "Switch to the next allowed value for this property."
  12584. (interactive)
  12585. (org-property-next-allowed-value t))
  12586. (defun org-property-next-allowed-value (&optional previous)
  12587. "Switch to the next allowed value for this property."
  12588. (interactive)
  12589. (unless (org-at-property-p)
  12590. (user-error "Not at a property"))
  12591. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12592. (key (match-string 2))
  12593. (value (match-string 3))
  12594. (allowed (or (org-property-get-allowed-values (point) key)
  12595. (and (member value '("[ ]" "[-]" "[X]"))
  12596. '("[ ]" "[X]"))))
  12597. (heading (save-match-data (nth 4 (org-heading-components))))
  12598. nval)
  12599. (unless allowed
  12600. (user-error "Allowed values for this property have not been defined"))
  12601. (when previous (setq allowed (reverse allowed)))
  12602. (when (member value allowed)
  12603. (setq nval (car (cdr (member value allowed)))))
  12604. (setq nval (or nval (car allowed)))
  12605. (when (equal nval value)
  12606. (user-error "Only one allowed value for this property"))
  12607. (org-at-property-p)
  12608. (replace-match (concat " :" key ": " nval) t t)
  12609. (org-indent-line)
  12610. (beginning-of-line 1)
  12611. (skip-chars-forward " \t")
  12612. (when (equal prop org-effort-property)
  12613. (org-refresh-property
  12614. '((effort . identity)
  12615. (effort-minutes . org-duration-to-minutes))
  12616. nval)
  12617. (when (string= org-clock-current-task heading)
  12618. (setq org-clock-effort nval)
  12619. (org-clock-update-mode-line)))
  12620. (run-hook-with-args 'org-property-changed-functions key nval)))
  12621. (defun org-find-olp (path &optional this-buffer)
  12622. "Return a marker pointing to the entry at outline path OLP.
  12623. If anything goes wrong, throw an error.
  12624. You can wrap this call to catch the error like this:
  12625. (condition-case msg
  12626. (org-mobile-locate-entry (match-string 4))
  12627. (error (nth 1 msg)))
  12628. The return value will then be either a string with the error message,
  12629. or a marker if everything is OK.
  12630. If THIS-BUFFER is set, the outline path does not contain a file,
  12631. only headings."
  12632. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12633. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12634. (level 1)
  12635. (lmin 1)
  12636. (lmax 1)
  12637. end found flevel)
  12638. (unless buffer (error "File not found :%s" file))
  12639. (with-current-buffer buffer
  12640. (unless (derived-mode-p 'org-mode)
  12641. (error "Buffer %s needs to be in Org mode" buffer))
  12642. (org-with-wide-buffer
  12643. (goto-char (point-min))
  12644. (dolist (heading path)
  12645. (let ((re (format org-complex-heading-regexp-format
  12646. (regexp-quote heading)))
  12647. (cnt 0))
  12648. (while (re-search-forward re end t)
  12649. (setq level (- (match-end 1) (match-beginning 1)))
  12650. (when (and (>= level lmin) (<= level lmax))
  12651. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12652. (when (= cnt 0)
  12653. (error "Heading not found on level %d: %s" lmax heading))
  12654. (when (> cnt 1)
  12655. (error "Heading not unique on level %d: %s" lmax heading))
  12656. (goto-char found)
  12657. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12658. (setq end (save-excursion (org-end-of-subtree t t)))))
  12659. (when (org-at-heading-p)
  12660. (point-marker))))))
  12661. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12662. "Find node HEADING in BUFFER.
  12663. Return a marker to the heading if it was found, or nil if not.
  12664. If POS-ONLY is set, return just the position instead of a marker.
  12665. The heading text must match exact, but it may have a TODO keyword,
  12666. a priority cookie and tags in the standard locations."
  12667. (with-current-buffer (or buffer (current-buffer))
  12668. (org-with-wide-buffer
  12669. (goto-char (point-min))
  12670. (let (case-fold-search)
  12671. (when (re-search-forward
  12672. (format org-complex-heading-regexp-format
  12673. (regexp-quote heading)) nil t)
  12674. (if pos-only
  12675. (match-beginning 0)
  12676. (move-marker (make-marker) (match-beginning 0))))))))
  12677. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12678. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12679. When the target headline is found, return a marker to this location."
  12680. (let ((files (directory-files (or dir default-directory)
  12681. t "\\`[^.#].*\\.org\\'"))
  12682. visiting m buffer)
  12683. (catch 'found
  12684. (dolist (file files)
  12685. (message "trying %s" file)
  12686. (setq visiting (org-find-base-buffer-visiting file))
  12687. (setq buffer (or visiting (find-file-noselect file)))
  12688. (setq m (org-find-exact-headline-in-buffer
  12689. heading buffer))
  12690. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12691. (and m (throw 'found m))))))
  12692. (defun org-find-entry-with-id (ident)
  12693. "Locate the entry that contains the ID property with exact value IDENT.
  12694. IDENT can be a string, a symbol or a number, this function will search for
  12695. the string representation of it.
  12696. Return the position where this entry starts, or nil if there is no such entry."
  12697. (interactive "sID: ")
  12698. (let ((id (cond
  12699. ((stringp ident) ident)
  12700. ((symbolp ident) (symbol-name ident))
  12701. ((numberp ident) (number-to-string ident))
  12702. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12703. (org-with-wide-buffer (org-find-property "ID" id))))
  12704. ;;;; Timestamps
  12705. (defvar org-last-changed-timestamp nil)
  12706. (defvar org-last-inserted-timestamp nil
  12707. "The last time stamp inserted with `org-insert-time-stamp'.")
  12708. (defun org-time-stamp (arg &optional inactive)
  12709. "Prompt for a date/time and insert a time stamp.
  12710. If the user specifies a time like HH:MM or if this command is
  12711. called with at least one prefix argument, the time stamp contains
  12712. the date and the time. Otherwise, only the date is included.
  12713. All parts of a date not specified by the user are filled in from
  12714. the timestamp at point, if any, or the current date/time
  12715. otherwise.
  12716. If there is already a timestamp at the cursor, it is replaced.
  12717. With two universal prefix arguments, insert an active timestamp
  12718. with the current time without prompting the user.
  12719. When called from lisp, the timestamp is inactive if INACTIVE is
  12720. non-nil."
  12721. (interactive "P")
  12722. (let* ((ts (cond
  12723. ((org-at-date-range-p t)
  12724. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12725. ((org-at-timestamp-p 'lax) (match-string 0))))
  12726. ;; Default time is either the timestamp at point or today.
  12727. ;; When entering a range, only the range start is considered.
  12728. (default-time (and ts
  12729. (apply #'encode-time (org-parse-time-string ts))))
  12730. (default-input (and ts (org-get-compact-tod ts)))
  12731. (repeater (and ts
  12732. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12733. (match-string 0 ts)))
  12734. org-time-was-given
  12735. org-end-time-was-given
  12736. (time
  12737. (if (equal arg '(16)) (current-time)
  12738. ;; Preserve `this-command' and `last-command'.
  12739. (let ((this-command this-command)
  12740. (last-command last-command))
  12741. (org-read-date
  12742. arg 'totime nil nil default-time default-input
  12743. inactive)))))
  12744. (cond
  12745. ((and ts
  12746. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12747. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12748. (insert "--")
  12749. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12750. (ts
  12751. ;; Make sure we're on a timestamp. When in the middle of a date
  12752. ;; range, move arbitrarily to range end.
  12753. (unless (org-at-timestamp-p 'lax)
  12754. (skip-chars-forward "-")
  12755. (org-at-timestamp-p 'lax))
  12756. (replace-match "")
  12757. (setq org-last-changed-timestamp
  12758. (org-insert-time-stamp
  12759. time (or org-time-was-given arg)
  12760. inactive nil nil (list org-end-time-was-given)))
  12761. (when repeater
  12762. (backward-char)
  12763. (insert " " repeater)
  12764. (setq org-last-changed-timestamp
  12765. (concat (substring org-last-inserted-timestamp 0 -1)
  12766. " " repeater ">")))
  12767. (message "Timestamp updated"))
  12768. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12769. (t (org-insert-time-stamp
  12770. time (or org-time-was-given arg) inactive nil nil
  12771. (list org-end-time-was-given))))))
  12772. ;; FIXME: can we use this for something else, like computing time differences?
  12773. (defun org-get-compact-tod (s)
  12774. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12775. (let* ((t1 (match-string 1 s))
  12776. (h1 (string-to-number (match-string 2 s)))
  12777. (m1 (string-to-number (match-string 3 s)))
  12778. (t2 (and (match-end 4) (match-string 5 s)))
  12779. (h2 (and t2 (string-to-number (match-string 6 s))))
  12780. (m2 (and t2 (string-to-number (match-string 7 s))))
  12781. dh dm)
  12782. (if (not t2)
  12783. t1
  12784. (setq dh (- h2 h1) dm (- m2 m1))
  12785. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12786. (concat t1 "+" (number-to-string dh)
  12787. (and (/= 0 dm) (format ":%02d" dm)))))))
  12788. (defun org-time-stamp-inactive (&optional arg)
  12789. "Insert an inactive time stamp.
  12790. An inactive time stamp is enclosed in square brackets instead of angle
  12791. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12792. does not link to the calendar and cannot be changed with the S-cursor keys.
  12793. So these are more for recording a certain time/date.
  12794. If the user specifies a time like HH:MM or if this command is called with
  12795. at least one prefix argument, the time stamp contains the date and the time.
  12796. Otherwise, only the date is included.
  12797. When called with two universal prefix arguments, insert an active time stamp
  12798. with the current time without prompting the user."
  12799. (interactive "P")
  12800. (org-time-stamp arg 'inactive))
  12801. (defvar org-date-ovl (make-overlay 1 1))
  12802. (overlay-put org-date-ovl 'face 'org-date-selected)
  12803. (delete-overlay org-date-ovl)
  12804. (defvar org-ans1) ; dynamically scoped parameter
  12805. (defvar org-ans2) ; dynamically scoped parameter
  12806. (defvar org-plain-time-of-day-regexp) ; defined below
  12807. (defvar org-overriding-default-time nil) ; dynamically scoped
  12808. (defvar org-read-date-overlay nil)
  12809. (defvar org-dcst nil) ; dynamically scoped
  12810. (defvar org-read-date-history nil)
  12811. (defvar org-read-date-final-answer nil)
  12812. (defvar org-read-date-analyze-futurep nil)
  12813. (defvar org-read-date-analyze-forced-year nil)
  12814. (defvar org-read-date-inactive)
  12815. (defvar org-def)
  12816. (defvar org-defdecode)
  12817. (defvar org-with-time)
  12818. (defvar calendar-setup) ; Dynamically scoped.
  12819. (defun org-read-date (&optional with-time to-time from-string prompt
  12820. default-time default-input inactive)
  12821. "Read a date, possibly a time, and make things smooth for the user.
  12822. The prompt will suggest to enter an ISO date, but you can also enter anything
  12823. which will at least partially be understood by `parse-time-string'.
  12824. Unrecognized parts of the date will default to the current day, month, year,
  12825. hour and minute. If this command is called to replace a timestamp at point,
  12826. or to enter the second timestamp of a range, the default time is taken
  12827. from the existing stamp. Furthermore, the command prefers the future,
  12828. so if you are giving a date where the year is not given, and the day-month
  12829. combination is already past in the current year, it will assume you
  12830. mean next year. For details, see the manual. A few examples:
  12831. 3-2-5 --> 2003-02-05
  12832. feb 15 --> currentyear-02-15
  12833. 2/15 --> currentyear-02-15
  12834. sep 12 9 --> 2009-09-12
  12835. 12:45 --> today 12:45
  12836. 22 sept 0:34 --> currentyear-09-22 0:34
  12837. 12 --> currentyear-currentmonth-12
  12838. Fri --> nearest Friday after today
  12839. -Tue --> last Tuesday
  12840. etc.
  12841. Furthermore you can specify a relative date by giving, as the *first* thing
  12842. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12843. change in days weeks, months, years.
  12844. With a single plus or minus, the date is relative to today. With a double
  12845. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12846. +4d --> four days from today
  12847. +4 --> same as above
  12848. +2w --> two weeks from today
  12849. ++5 --> five days from default date
  12850. The function understands only English month and weekday abbreviations.
  12851. While prompting, a calendar is popped up - you can also select the
  12852. date with the mouse (button 1). The calendar shows a period of three
  12853. months. To scroll it to other months, use the keys `>' and `<'.
  12854. If you don't like the calendar, turn it off with
  12855. (setq org-read-date-popup-calendar nil)
  12856. With optional argument TO-TIME, the date will immediately be converted
  12857. to an internal time.
  12858. With an optional argument WITH-TIME, the prompt will suggest to
  12859. also insert a time. Note that when WITH-TIME is not set, you can
  12860. still enter a time, and this function will inform the calling routine
  12861. about this change. The calling routine may then choose to change the
  12862. format used to insert the time stamp into the buffer to include the time.
  12863. With optional argument FROM-STRING, read from this string instead from
  12864. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12865. the time/date that is used for everything that is not specified by the
  12866. user."
  12867. (require 'parse-time)
  12868. (let* ((org-with-time with-time)
  12869. (org-time-stamp-rounding-minutes
  12870. (if (equal org-with-time '(16))
  12871. '(0 0)
  12872. org-time-stamp-rounding-minutes))
  12873. (org-dcst org-display-custom-times)
  12874. (ct (org-current-time))
  12875. (org-def (or org-overriding-default-time default-time ct))
  12876. (org-defdecode (decode-time org-def))
  12877. (cur-frame (selected-frame))
  12878. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12879. (calendar-setup
  12880. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12881. (calendar-move-hook nil)
  12882. (calendar-view-diary-initially-flag nil)
  12883. (calendar-view-holidays-initially-flag nil)
  12884. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12885. ;; Rationalize `org-def' and `org-defdecode', if required.
  12886. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12887. (setf (nth 2 org-defdecode) -1)
  12888. (setf (nth 1 org-defdecode) 59)
  12889. (setq org-def (apply #'encode-time org-defdecode))
  12890. (setq org-defdecode (decode-time org-def)))
  12891. (let* ((timestr (format-time-string
  12892. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12893. org-def))
  12894. (prompt (concat (if prompt (concat prompt " ") "")
  12895. (format "Date+time [%s]: " timestr))))
  12896. (cond
  12897. (from-string (setq ans from-string))
  12898. (org-read-date-popup-calendar
  12899. (save-excursion
  12900. (save-window-excursion
  12901. (calendar)
  12902. (when (eq calendar-setup 'calendar-only)
  12903. (setq cal-frame
  12904. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12905. (select-frame cal-frame))
  12906. (org-eval-in-calendar '(setq cursor-type nil) t)
  12907. (unwind-protect
  12908. (progn
  12909. (calendar-forward-day (- (time-to-days org-def)
  12910. (calendar-absolute-from-gregorian
  12911. (calendar-current-date))))
  12912. (org-eval-in-calendar nil t)
  12913. (let* ((old-map (current-local-map))
  12914. (map (copy-keymap calendar-mode-map))
  12915. (minibuffer-local-map
  12916. (copy-keymap org-read-date-minibuffer-local-map)))
  12917. (org-defkey map (kbd "RET") 'org-calendar-select)
  12918. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12919. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12920. (unwind-protect
  12921. (progn
  12922. (use-local-map map)
  12923. (setq org-read-date-inactive inactive)
  12924. (add-hook 'post-command-hook 'org-read-date-display)
  12925. (setq org-ans0
  12926. (read-string prompt
  12927. default-input
  12928. 'org-read-date-history
  12929. nil))
  12930. ;; org-ans0: from prompt
  12931. ;; org-ans1: from mouse click
  12932. ;; org-ans2: from calendar motion
  12933. (setq ans
  12934. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12935. (remove-hook 'post-command-hook 'org-read-date-display)
  12936. (use-local-map old-map)
  12937. (when org-read-date-overlay
  12938. (delete-overlay org-read-date-overlay)
  12939. (setq org-read-date-overlay nil)))))
  12940. (bury-buffer "*Calendar*")
  12941. (when cal-frame
  12942. (delete-frame cal-frame)
  12943. (select-frame-set-input-focus cur-frame))))))
  12944. (t ; Naked prompt only
  12945. (unwind-protect
  12946. (setq ans (read-string prompt default-input
  12947. 'org-read-date-history timestr))
  12948. (when org-read-date-overlay
  12949. (delete-overlay org-read-date-overlay)
  12950. (setq org-read-date-overlay nil))))))
  12951. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12952. (when org-read-date-analyze-forced-year
  12953. (message "Year was forced into %s"
  12954. (if org-read-date-force-compatible-dates
  12955. "compatible range (1970-2037)"
  12956. "range representable on this machine"))
  12957. (ding))
  12958. ;; One round trip to get rid of 34th of August and stuff like that....
  12959. (setq final (decode-time (apply 'encode-time final)))
  12960. (setq org-read-date-final-answer ans)
  12961. (if to-time
  12962. (apply 'encode-time final)
  12963. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12964. (format "%04d-%02d-%02d %02d:%02d"
  12965. (nth 5 final) (nth 4 final) (nth 3 final)
  12966. (nth 2 final) (nth 1 final))
  12967. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12968. (defun org-read-date-display ()
  12969. "Display the current date prompt interpretation in the minibuffer."
  12970. (when org-read-date-display-live
  12971. (when org-read-date-overlay
  12972. (delete-overlay org-read-date-overlay))
  12973. (when (minibufferp (current-buffer))
  12974. (save-excursion
  12975. (end-of-line 1)
  12976. (while (not (equal (buffer-substring
  12977. (max (point-min) (- (point) 4)) (point))
  12978. " "))
  12979. (insert " ")))
  12980. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12981. " " (or org-ans1 org-ans2)))
  12982. (org-end-time-was-given nil)
  12983. (f (org-read-date-analyze ans org-def org-defdecode))
  12984. (fmts (if org-dcst
  12985. org-time-stamp-custom-formats
  12986. org-time-stamp-formats))
  12987. (fmt (if (or org-with-time
  12988. (and (boundp 'org-time-was-given) org-time-was-given))
  12989. (cdr fmts)
  12990. (car fmts)))
  12991. (txt (format-time-string fmt (apply 'encode-time f)))
  12992. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12993. (txt (concat "=> " txt)))
  12994. (when (and org-end-time-was-given
  12995. (string-match org-plain-time-of-day-regexp txt))
  12996. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12997. org-end-time-was-given
  12998. (substring txt (match-end 0)))))
  12999. (when org-read-date-analyze-futurep
  13000. (setq txt (concat txt " (=>F)")))
  13001. (setq org-read-date-overlay
  13002. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13003. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13004. (defun org-read-date-analyze (ans def defdecode)
  13005. "Analyze the combined answer of the date prompt."
  13006. ;; FIXME: cleanup and comment
  13007. (let ((org-def def)
  13008. (org-defdecode defdecode)
  13009. (nowdecode (decode-time))
  13010. delta deltan deltaw deltadef year month day
  13011. hour minute second wday pm h2 m2 tl wday1
  13012. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13013. (setq org-read-date-analyze-futurep nil
  13014. org-read-date-analyze-forced-year nil)
  13015. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13016. (setq ans "+0"))
  13017. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13018. (setq ans (replace-match "" t t ans)
  13019. deltan (car delta)
  13020. deltaw (nth 1 delta)
  13021. deltadef (nth 2 delta)))
  13022. ;; Check if there is an iso week date in there. If yes, store the
  13023. ;; info and postpone interpreting it until the rest of the parsing
  13024. ;; is done.
  13025. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13026. (setq iso-year (when (match-end 1)
  13027. (org-small-year-to-year
  13028. (string-to-number (match-string 1 ans))))
  13029. iso-weekday (when (match-end 3)
  13030. (string-to-number (match-string 3 ans)))
  13031. iso-week (string-to-number (match-string 2 ans)))
  13032. (setq ans (replace-match "" t t ans)))
  13033. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13034. (when (string-match
  13035. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13036. (setq year (if (match-end 2)
  13037. (string-to-number (match-string 2 ans))
  13038. (progn (setq kill-year t)
  13039. (string-to-number (format-time-string "%Y"))))
  13040. month (string-to-number (match-string 3 ans))
  13041. day (string-to-number (match-string 4 ans)))
  13042. (setq year (org-small-year-to-year year))
  13043. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13044. t nil ans)))
  13045. ;; Help matching dotted european dates
  13046. (when (string-match
  13047. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13048. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13049. (setq kill-year t)
  13050. (string-to-number (format-time-string "%Y")))
  13051. day (string-to-number (match-string 1 ans))
  13052. month (string-to-number (match-string 2 ans))
  13053. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13054. t nil ans)))
  13055. ;; Help matching american dates, like 5/30 or 5/30/7
  13056. (when (string-match
  13057. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13058. (setq year (if (match-end 4)
  13059. (string-to-number (match-string 4 ans))
  13060. (progn (setq kill-year t)
  13061. (string-to-number (format-time-string "%Y"))))
  13062. month (string-to-number (match-string 1 ans))
  13063. day (string-to-number (match-string 2 ans)))
  13064. (setq year (org-small-year-to-year year))
  13065. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13066. t nil ans)))
  13067. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13068. ;; If there is a time with am/pm, and *no* time without it, we convert
  13069. ;; so that matching will be successful.
  13070. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13071. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13072. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13073. (setq hour (string-to-number (match-string 1 ans))
  13074. minute (if (match-end 3)
  13075. (string-to-number (match-string 3 ans))
  13076. 0)
  13077. pm (equal ?p
  13078. (string-to-char (downcase (match-string 4 ans)))))
  13079. (if (and (= hour 12) (not pm))
  13080. (setq hour 0)
  13081. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13082. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13083. t t ans))))
  13084. ;; Check if a time range is given as a duration
  13085. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13086. (setq hour (string-to-number (match-string 1 ans))
  13087. h2 (+ hour (string-to-number (match-string 3 ans)))
  13088. minute (string-to-number (match-string 2 ans))
  13089. m2 (+ minute (if (match-end 5) (string-to-number
  13090. (match-string 5 ans))0)))
  13091. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13092. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13093. t t ans)))
  13094. ;; Check if there is a time range
  13095. (when (boundp 'org-end-time-was-given)
  13096. (setq org-time-was-given nil)
  13097. (when (and (string-match org-plain-time-of-day-regexp ans)
  13098. (match-end 8))
  13099. (setq org-end-time-was-given (match-string 8 ans))
  13100. (setq ans (concat (substring ans 0 (match-beginning 7))
  13101. (substring ans (match-end 7))))))
  13102. (setq tl (parse-time-string ans)
  13103. day (or (nth 3 tl) (nth 3 org-defdecode))
  13104. month
  13105. (cond ((nth 4 tl))
  13106. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13107. ;; Day was specified. Make sure DAY+MONTH
  13108. ;; combination happens in the future.
  13109. ((nth 3 tl)
  13110. (setq futurep t)
  13111. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13112. (nth 4 nowdecode)))
  13113. (t (nth 4 org-defdecode)))
  13114. year
  13115. (cond ((and (not kill-year) (nth 5 tl)))
  13116. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13117. ;; Month was guessed in the future and is at least
  13118. ;; equal to NOWDECODE's. Fix year accordingly.
  13119. (futurep
  13120. (if (or (> month (nth 4 nowdecode))
  13121. (>= day (nth 3 nowdecode)))
  13122. (nth 5 nowdecode)
  13123. (1+ (nth 5 nowdecode))))
  13124. ;; Month was specified. Make sure MONTH+YEAR
  13125. ;; combination happens in the future.
  13126. ((nth 4 tl)
  13127. (setq futurep t)
  13128. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13129. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13130. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13131. (t (nth 5 nowdecode))))
  13132. (t (nth 5 org-defdecode)))
  13133. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13134. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13135. second (or (nth 0 tl) 0)
  13136. wday (nth 6 tl))
  13137. (when (and (eq org-read-date-prefer-future 'time)
  13138. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13139. (equal day (nth 3 nowdecode))
  13140. (equal month (nth 4 nowdecode))
  13141. (equal year (nth 5 nowdecode))
  13142. (nth 2 tl)
  13143. (or (< (nth 2 tl) (nth 2 nowdecode))
  13144. (and (= (nth 2 tl) (nth 2 nowdecode))
  13145. (nth 1 tl)
  13146. (< (nth 1 tl) (nth 1 nowdecode)))))
  13147. (setq day (1+ day)
  13148. futurep t))
  13149. ;; Special date definitions below
  13150. (cond
  13151. (iso-week
  13152. ;; There was an iso week
  13153. (require 'cal-iso)
  13154. (setq futurep nil)
  13155. (setq year (or iso-year year)
  13156. day (or iso-weekday wday 1)
  13157. wday nil ; to make sure that the trigger below does not match
  13158. iso-date (calendar-gregorian-from-absolute
  13159. (calendar-iso-to-absolute
  13160. (list iso-week day year))))
  13161. ; FIXME: Should we also push ISO weeks into the future?
  13162. ; (when (and org-read-date-prefer-future
  13163. ; (not iso-year)
  13164. ; (< (calendar-absolute-from-gregorian iso-date)
  13165. ; (time-to-days nil)))
  13166. ; (setq year (1+ year)
  13167. ; iso-date (calendar-gregorian-from-absolute
  13168. ; (calendar-iso-to-absolute
  13169. ; (list iso-week day year)))))
  13170. (setq month (car iso-date)
  13171. year (nth 2 iso-date)
  13172. day (nth 1 iso-date)))
  13173. (deltan
  13174. (setq futurep nil)
  13175. (unless deltadef
  13176. (let ((now (decode-time)))
  13177. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13178. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13179. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13180. ((equal deltaw "m") (setq month (+ month deltan)))
  13181. ((equal deltaw "y") (setq year (+ year deltan)))))
  13182. ((and wday (not (nth 3 tl)))
  13183. ;; Weekday was given, but no day, so pick that day in the week
  13184. ;; on or after the derived date.
  13185. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13186. (unless (equal wday wday1)
  13187. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13188. (when (and (boundp 'org-time-was-given)
  13189. (nth 2 tl))
  13190. (setq org-time-was-given t))
  13191. (when (< year 100) (setq year (+ 2000 year)))
  13192. ;; Check of the date is representable
  13193. (if org-read-date-force-compatible-dates
  13194. (progn
  13195. (when (< year 1970)
  13196. (setq year 1970 org-read-date-analyze-forced-year t))
  13197. (when (> year 2037)
  13198. (setq year 2037 org-read-date-analyze-forced-year t)))
  13199. (condition-case nil
  13200. (ignore (encode-time second minute hour day month year))
  13201. (error
  13202. (setq year (nth 5 org-defdecode))
  13203. (setq org-read-date-analyze-forced-year t))))
  13204. (setq org-read-date-analyze-futurep futurep)
  13205. (list second minute hour day month year)))
  13206. (defvar parse-time-weekdays)
  13207. (defun org-read-date-get-relative (s today default)
  13208. "Check string S for special relative date string.
  13209. TODAY and DEFAULT are internal times, for today and for a default.
  13210. Return shift list (N what def-flag)
  13211. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13212. N is the number of WHATs to shift.
  13213. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13214. the DEFAULT date rather than TODAY."
  13215. (require 'parse-time)
  13216. (when (and
  13217. (string-match
  13218. (concat
  13219. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13220. "\\([0-9]+\\)?"
  13221. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13222. "\\([ \t]\\|$\\)") s)
  13223. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13224. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13225. (string-to-char (substring (match-string 1 s) -1))
  13226. ?+))
  13227. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13228. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13229. (what (if (match-end 3) (match-string 3 s) "d"))
  13230. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13231. (date (if rel default today))
  13232. (wday (nth 6 (decode-time date)))
  13233. delta)
  13234. (if wday1
  13235. (progn
  13236. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13237. (when (= delta 0) (setq delta 7))
  13238. (when (= dir ?-)
  13239. (setq delta (- delta 7))
  13240. (when (= delta 0) (setq delta -7)))
  13241. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13242. (list delta "d" rel))
  13243. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13244. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13245. "Turn a user-specified date into the internal representation.
  13246. The internal representation needed by the calendar is (month day year).
  13247. This is a wrapper to handle the brain-dead convention in calendar that
  13248. user function argument order change dependent on argument order."
  13249. (pcase calendar-date-style
  13250. (`american (list arg1 arg2 arg3))
  13251. (`european (list arg2 arg1 arg3))
  13252. (`iso (list arg2 arg3 arg1))))
  13253. (defun org-eval-in-calendar (form &optional keepdate)
  13254. "Eval FORM in the calendar window and return to current window.
  13255. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13256. (let ((sf (selected-frame))
  13257. (sw (selected-window)))
  13258. (select-window (get-buffer-window "*Calendar*" t))
  13259. (eval form)
  13260. (when (and (not keepdate) (calendar-cursor-to-date))
  13261. (let* ((date (calendar-cursor-to-date))
  13262. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13263. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13264. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13265. (select-window sw)
  13266. (select-frame-set-input-focus sf)))
  13267. (defun org-calendar-select ()
  13268. "Return to `org-read-date' with the date currently selected.
  13269. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13270. (interactive)
  13271. (when (calendar-cursor-to-date)
  13272. (let* ((date (calendar-cursor-to-date))
  13273. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13274. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13275. (when (active-minibuffer-window) (exit-minibuffer))))
  13276. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13277. "Insert a date stamp for the date given by the internal TIME.
  13278. See `format-time-string' for the format of TIME.
  13279. WITH-HM means use the stamp format that includes the time of the day.
  13280. INACTIVE means use square brackets instead of angular ones, so that the
  13281. stamp will not contribute to the agenda.
  13282. PRE and POST are optional strings to be inserted before and after the
  13283. stamp.
  13284. The command returns the inserted time stamp."
  13285. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13286. stamp)
  13287. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13288. (insert-before-markers (or pre ""))
  13289. (when (listp extra)
  13290. (setq extra (car extra))
  13291. (if (and (stringp extra)
  13292. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13293. (setq extra (format "-%02d:%02d"
  13294. (string-to-number (match-string 1 extra))
  13295. (string-to-number (match-string 2 extra))))
  13296. (setq extra nil)))
  13297. (when extra
  13298. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13299. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13300. (insert-before-markers (or post ""))
  13301. (setq org-last-inserted-timestamp stamp)))
  13302. (defun org-toggle-time-stamp-overlays ()
  13303. "Toggle the use of custom time stamp formats."
  13304. (interactive)
  13305. (setq org-display-custom-times (not org-display-custom-times))
  13306. (unless org-display-custom-times
  13307. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13308. (while (setq p (next-single-property-change p 'display))
  13309. (when (and (get-text-property p 'display)
  13310. (eq (get-text-property p 'face) 'org-date))
  13311. (remove-text-properties
  13312. p (setq p (next-single-property-change p 'display))
  13313. '(display t))))
  13314. (set-buffer-modified-p bmp)))
  13315. (org-restart-font-lock)
  13316. (setq org-table-may-need-update t)
  13317. (if org-display-custom-times
  13318. (message "Time stamps are overlaid with custom format")
  13319. (message "Time stamp overlays removed")))
  13320. (defun org-display-custom-time (beg end)
  13321. "Overlay modified time stamp format over timestamp between BEG and END."
  13322. (let* ((ts (buffer-substring beg end))
  13323. t1 with-hm tf time str (off 0))
  13324. (save-match-data
  13325. (setq t1 (org-parse-time-string ts t))
  13326. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13327. (setq off (- (match-end 0) (match-beginning 0)))))
  13328. (setq end (- end off))
  13329. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13330. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13331. time (org-fix-decoded-time t1)
  13332. str (org-add-props
  13333. (format-time-string
  13334. (substring tf 1 -1) (apply 'encode-time time))
  13335. nil 'mouse-face 'highlight))
  13336. (put-text-property beg end 'display str)))
  13337. (defun org-fix-decoded-time (time)
  13338. "Set 0 instead of nil for the first 6 elements of time.
  13339. Don't touch the rest."
  13340. (let ((n 0))
  13341. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13342. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13343. "Difference between TIMESTAMP-STRING and now in days.
  13344. If SECONDS is non-nil, return the difference in seconds."
  13345. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13346. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13347. (funcall fdiff nil))))
  13348. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13349. "Is the time in TIMESTAMP-STRING close to the current date?"
  13350. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13351. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13352. (not (org-entry-is-done-p))))
  13353. (defun org-get-wdays (ts &optional delay zero-delay)
  13354. "Get the deadline lead time appropriate for timestring TS.
  13355. When DELAY is non-nil, get the delay time for scheduled items
  13356. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13357. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13358. don't try to find the delay cookie in the scheduled timestamp."
  13359. (let ((tv (if delay org-scheduled-delay-days
  13360. org-deadline-warning-days)))
  13361. (cond
  13362. ((or (and delay (< tv 0))
  13363. (and delay zero-delay (<= tv 0))
  13364. (and (not delay) (<= tv 0)))
  13365. ;; Enforce this value no matter what
  13366. (- tv))
  13367. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13368. ;; lead time is specified.
  13369. (floor (* (string-to-number (match-string 1 ts))
  13370. (cdr (assoc (match-string 2 ts)
  13371. '(("d" . 1) ("w" . 7)
  13372. ("m" . 30.4) ("y" . 365.25)
  13373. ("h" . 0.041667)))))))
  13374. ;; go for the default.
  13375. (t tv))))
  13376. (defun org-calendar-select-mouse (ev)
  13377. "Return to `org-read-date' with the date currently selected.
  13378. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13379. (interactive "e")
  13380. (mouse-set-point ev)
  13381. (when (calendar-cursor-to-date)
  13382. (let* ((date (calendar-cursor-to-date))
  13383. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13384. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13385. (when (active-minibuffer-window) (exit-minibuffer))))
  13386. (defun org-check-deadlines (ndays)
  13387. "Check if there are any deadlines due or past due.
  13388. A deadline is considered due if it happens within `org-deadline-warning-days'
  13389. days from today's date. If the deadline appears in an entry marked DONE,
  13390. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13391. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13392. are shown."
  13393. (interactive "P")
  13394. (let* ((org-warn-days
  13395. (cond
  13396. ((equal ndays '(4)) 100000)
  13397. (ndays (prefix-numeric-value ndays))
  13398. (t (abs org-deadline-warning-days))))
  13399. (case-fold-search nil)
  13400. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13401. (callback
  13402. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13403. (message "%d deadlines past-due or due within %d days"
  13404. (org-occur regexp nil callback)
  13405. org-warn-days)))
  13406. (defsubst org-re-timestamp (type)
  13407. "Return a regexp for timestamp TYPE.
  13408. Allowed values for TYPE are:
  13409. all: all timestamps
  13410. active: only active timestamps (<...>)
  13411. inactive: only inactive timestamps ([...])
  13412. scheduled: only scheduled timestamps
  13413. deadline: only deadline timestamps
  13414. closed: only closed time-stamps
  13415. When TYPE is nil, fall back on returning a regexp that matches
  13416. both scheduled and deadline timestamps."
  13417. (cl-case type
  13418. (all org-ts-regexp-both)
  13419. (active org-ts-regexp)
  13420. (inactive org-ts-regexp-inactive)
  13421. (scheduled org-scheduled-time-regexp)
  13422. (deadline org-deadline-time-regexp)
  13423. (closed org-closed-time-regexp)
  13424. (otherwise
  13425. (concat "\\<"
  13426. (regexp-opt (list org-deadline-string org-scheduled-string))
  13427. " *<\\([^>]+\\)>"))))
  13428. (defun org-check-before-date (d)
  13429. "Check if there are deadlines or scheduled entries before date D."
  13430. (interactive (list (org-read-date)))
  13431. (let* ((case-fold-search nil)
  13432. (regexp (org-re-timestamp org-ts-type))
  13433. (ts-type org-ts-type)
  13434. (callback
  13435. (lambda ()
  13436. (let ((match (match-string 1)))
  13437. (and (if (memq ts-type '(active inactive all))
  13438. (eq (org-element-type (save-excursion
  13439. (backward-char)
  13440. (org-element-context)))
  13441. 'timestamp)
  13442. (org-at-planning-p))
  13443. (time-less-p
  13444. (org-time-string-to-time match)
  13445. (org-time-string-to-time d)))))))
  13446. (message "%d entries before %s"
  13447. (org-occur regexp nil callback)
  13448. d)))
  13449. (defun org-check-after-date (d)
  13450. "Check if there are deadlines or scheduled entries after date D."
  13451. (interactive (list (org-read-date)))
  13452. (let* ((case-fold-search nil)
  13453. (regexp (org-re-timestamp org-ts-type))
  13454. (ts-type org-ts-type)
  13455. (callback
  13456. (lambda ()
  13457. (let ((match (match-string 1)))
  13458. (and (if (memq ts-type '(active inactive all))
  13459. (eq (org-element-type (save-excursion
  13460. (backward-char)
  13461. (org-element-context)))
  13462. 'timestamp)
  13463. (org-at-planning-p))
  13464. (not (time-less-p
  13465. (org-time-string-to-time match)
  13466. (org-time-string-to-time d))))))))
  13467. (message "%d entries after %s"
  13468. (org-occur regexp nil callback)
  13469. d)))
  13470. (defun org-check-dates-range (start-date end-date)
  13471. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13472. (interactive (list (org-read-date nil nil nil "Range starts")
  13473. (org-read-date nil nil nil "Range end")))
  13474. (let ((case-fold-search nil)
  13475. (regexp (org-re-timestamp org-ts-type))
  13476. (callback
  13477. (let ((type org-ts-type))
  13478. (lambda ()
  13479. (let ((match (match-string 1)))
  13480. (and
  13481. (if (memq type '(active inactive all))
  13482. (eq (org-element-type (save-excursion
  13483. (backward-char)
  13484. (org-element-context)))
  13485. 'timestamp)
  13486. (org-at-planning-p))
  13487. (not (time-less-p
  13488. (org-time-string-to-time match)
  13489. (org-time-string-to-time start-date)))
  13490. (time-less-p
  13491. (org-time-string-to-time match)
  13492. (org-time-string-to-time end-date))))))))
  13493. (message "%d entries between %s and %s"
  13494. (org-occur regexp nil callback) start-date end-date)))
  13495. (defun org-evaluate-time-range (&optional to-buffer)
  13496. "Evaluate a time range by computing the difference between start and end.
  13497. Normally the result is just printed in the echo area, but with prefix arg
  13498. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13499. If the time range is actually in a table, the result is inserted into the
  13500. next column.
  13501. For time difference computation, a year is assumed to be exactly 365
  13502. days in order to avoid rounding problems."
  13503. (interactive "P")
  13504. (or
  13505. (org-clock-update-time-maybe)
  13506. (save-excursion
  13507. (unless (org-at-date-range-p t)
  13508. (goto-char (point-at-bol))
  13509. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13510. (unless (org-at-date-range-p t)
  13511. (user-error "Not at a time-stamp range, and none found in current line")))
  13512. (let* ((ts1 (match-string 1))
  13513. (ts2 (match-string 2))
  13514. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13515. (match-end (match-end 0))
  13516. (time1 (org-time-string-to-time ts1))
  13517. (time2 (org-time-string-to-time ts2))
  13518. (diff (abs (float-time (time-subtract time2 time1))))
  13519. (negative (time-less-p time2 time1))
  13520. ;; (ys (floor (* 365 24 60 60)))
  13521. (ds (* 24 60 60))
  13522. (hs (* 60 60))
  13523. (fy "%dy %dd %02d:%02d")
  13524. (fy1 "%dy %dd")
  13525. (fd "%dd %02d:%02d")
  13526. (fd1 "%dd")
  13527. (fh "%02d:%02d")
  13528. y d h m align)
  13529. (if havetime
  13530. (setq ; y (floor diff ys) diff (mod diff ys)
  13531. y 0
  13532. d (floor diff ds) diff (mod diff ds)
  13533. h (floor diff hs) diff (mod diff hs)
  13534. m (floor diff 60))
  13535. (setq ; y (floor diff ys) diff (mod diff ys)
  13536. y 0
  13537. d (round diff ds)
  13538. h 0 m 0))
  13539. (if (not to-buffer)
  13540. (message "%s" (org-make-tdiff-string y d h m))
  13541. (if (org-at-table-p)
  13542. (progn
  13543. (goto-char match-end)
  13544. (setq align t)
  13545. (and (looking-at " *|") (goto-char (match-end 0))))
  13546. (goto-char match-end))
  13547. (when (looking-at
  13548. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13549. (replace-match ""))
  13550. (when negative (insert " -"))
  13551. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13552. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13553. (insert " " (format fh h m))))
  13554. (when align (org-table-align))
  13555. (message "Time difference inserted")))))
  13556. (defun org-make-tdiff-string (y d h m)
  13557. (let ((fmt "")
  13558. (l nil))
  13559. (when (> y 0)
  13560. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13561. (push y l))
  13562. (when (> d 0)
  13563. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13564. (push d l))
  13565. (when (> h 0)
  13566. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13567. (push h l))
  13568. (when (> m 0)
  13569. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13570. (push m l))
  13571. (apply 'format fmt (nreverse l))))
  13572. (defun org-time-string-to-time (s)
  13573. "Convert timestamp string S into internal time."
  13574. (apply #'encode-time (org-parse-time-string s)))
  13575. (defun org-time-string-to-seconds (s)
  13576. "Convert a timestamp string S into a number of seconds."
  13577. (float-time (org-time-string-to-time s)))
  13578. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13579. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13580. "Convert time stamp S to an absolute day number.
  13581. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13582. stamp, get the closest date to DAYNR. If PREFER is
  13583. `past' (respectively `future') return a date past (respectively
  13584. after) or equal to DAYNR.
  13585. POS is the location of time stamp S, as a buffer position in
  13586. BUFFER.
  13587. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13588. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13589. signaled."
  13590. (cond
  13591. ((string-match "\\`%%\\((.*)\\)" s)
  13592. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13593. ;; only able to match individual dates. If it fails, raise an
  13594. ;; error.
  13595. (if (and daynr
  13596. (org-diary-sexp-entry
  13597. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13598. daynr
  13599. (signal 'org-diary-sexp-no-match (list s))))
  13600. (daynr (org-closest-date s daynr prefer))
  13601. (t (time-to-days
  13602. (condition-case errdata
  13603. (apply #'encode-time (org-parse-time-string s))
  13604. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13605. s
  13606. (if (not (and buffer pos)) ""
  13607. (format-message " at %d in buffer `%s'" pos buffer))
  13608. (cdr errdata))))))))
  13609. (defun org-days-to-iso-week (days)
  13610. "Return the iso week number."
  13611. (require 'cal-iso)
  13612. (car (calendar-iso-from-absolute days)))
  13613. (defun org-small-year-to-year (year)
  13614. "Convert 2-digit years into 4-digit years.
  13615. YEAR is expanded into one of the 30 next years, if possible, or
  13616. into a past one. Any year larger than 99 is returned unchanged."
  13617. (if (>= year 100) year
  13618. (let* ((current (string-to-number (format-time-string "%Y")))
  13619. (century (/ current 100))
  13620. (offset (- year (% current 100))))
  13621. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13622. ((> offset -70) (+ (* century 100) year))
  13623. (t (+ (* (1+ century) 100) year))))))
  13624. (defun org-time-from-absolute (d)
  13625. "Return the time corresponding to date D.
  13626. D may be an absolute day number, or a calendar-type list (month day year)."
  13627. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13628. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13629. (defvar org-agenda-current-date)
  13630. (defun org-calendar-holiday ()
  13631. "List of holidays, for Diary display in Org mode."
  13632. (require 'holidays)
  13633. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13634. (and hl (mapconcat #'identity hl "; "))))
  13635. (defun org-diary-sexp-entry (sexp entry d)
  13636. "Process a SEXP diary ENTRY for date D."
  13637. (require 'diary-lib)
  13638. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13639. ;; dynamically.
  13640. (let* ((sexp `(let ((entry ,entry)
  13641. (date ',d))
  13642. ,(car (read-from-string sexp))))
  13643. (result (if calendar-debug-sexp (eval sexp)
  13644. (condition-case nil
  13645. (eval sexp)
  13646. (error
  13647. (beep)
  13648. (message "Bad sexp at line %d in %s: %s"
  13649. (org-current-line)
  13650. (buffer-file-name) sexp)
  13651. (sleep-for 2))))))
  13652. (cond ((stringp result) (split-string result "; "))
  13653. ((and (consp result)
  13654. (not (consp (cdr result)))
  13655. (stringp (cdr result))) (cdr result))
  13656. ((and (consp result)
  13657. (stringp (car result))) result)
  13658. (result entry))))
  13659. (defun org-diary-to-ical-string (frombuf)
  13660. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13661. This uses the icalendar.el library."
  13662. (let* ((tmpdir temporary-file-directory)
  13663. (tmpfile (make-temp-name
  13664. (expand-file-name "orgics" tmpdir)))
  13665. buf rtn b e)
  13666. (with-current-buffer frombuf
  13667. (icalendar-export-region (point-min) (point-max) tmpfile)
  13668. (setq buf (find-buffer-visiting tmpfile))
  13669. (set-buffer buf)
  13670. (goto-char (point-min))
  13671. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13672. (setq b (match-beginning 0)))
  13673. (goto-char (point-max))
  13674. (when (re-search-backward "^END:VEVENT" nil t)
  13675. (setq e (match-end 0)))
  13676. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13677. (kill-buffer buf)
  13678. (delete-file tmpfile)
  13679. rtn))
  13680. (defun org-closest-date (start current prefer)
  13681. "Return closest date to CURRENT starting from START.
  13682. CURRENT and START are both time stamps.
  13683. When PREFER is `past', return a date that is either CURRENT or
  13684. past. When PREFER is `future', return a date that is either
  13685. CURRENT or future.
  13686. Only time stamps with a repeater are modified. Any other time
  13687. stamp stay unchanged. In any case, return value is an absolute
  13688. day number."
  13689. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13690. ;; No repeater. Do not shift time stamp.
  13691. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  13692. (let ((value (string-to-number (match-string 1 start)))
  13693. (type (match-string 2 start)))
  13694. (if (= 0 value)
  13695. ;; Repeater with a 0-value is considered as void.
  13696. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  13697. (let* ((base (org-date-to-gregorian start))
  13698. (target (org-date-to-gregorian current))
  13699. (sday (calendar-absolute-from-gregorian base))
  13700. (cday (calendar-absolute-from-gregorian target))
  13701. n1 n2)
  13702. ;; If START is already past CURRENT, just return START.
  13703. (if (<= cday sday) sday
  13704. ;; Compute closest date before (N1) and closest date past
  13705. ;; (N2) CURRENT.
  13706. (pcase type
  13707. ("h"
  13708. (let ((missing-hours
  13709. (mod (+ (- (* 24 (- cday sday))
  13710. (nth 2 (org-parse-time-string start)))
  13711. org-extend-today-until)
  13712. value)))
  13713. (setf n1 (if (= missing-hours 0) cday
  13714. (- cday (1+ (/ missing-hours 24)))))
  13715. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13716. ((or "d" "w")
  13717. (let ((value (if (equal type "w") (* 7 value) value)))
  13718. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13719. (setf n2 (+ n1 value))))
  13720. ("m"
  13721. (let* ((add-months
  13722. (lambda (d n)
  13723. ;; Add N months to gregorian date D, i.e.,
  13724. ;; a list (MONTH DAY YEAR). Return a valid
  13725. ;; gregorian date.
  13726. (let ((m (+ (nth 0 d) n)))
  13727. (list (mod m 12)
  13728. (nth 1 d)
  13729. (+ (/ m 12) (nth 2 d))))))
  13730. (months ; Complete months to TARGET.
  13731. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13732. (- (nth 0 target) (nth 0 base))
  13733. ;; If START's day is greater than
  13734. ;; TARGET's, remove incomplete month.
  13735. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13736. value)
  13737. value))
  13738. (before (funcall add-months base months)))
  13739. (setf n1 (calendar-absolute-from-gregorian before))
  13740. (setf n2
  13741. (calendar-absolute-from-gregorian
  13742. (funcall add-months before value)))))
  13743. (_
  13744. (let* ((d (nth 1 base))
  13745. (m (nth 0 base))
  13746. (y (nth 2 base))
  13747. (years ; Complete years to TARGET.
  13748. (* (/ (- (nth 2 target)
  13749. y
  13750. ;; If START's month and day are
  13751. ;; greater than TARGET's, remove
  13752. ;; incomplete year.
  13753. (if (or (> (nth 0 target) m)
  13754. (and (= (nth 0 target) m)
  13755. (> (nth 1 target) d)))
  13756. 0
  13757. 1))
  13758. value)
  13759. value))
  13760. (before (list m d (+ y years))))
  13761. (setf n1 (calendar-absolute-from-gregorian before))
  13762. (setf n2 (calendar-absolute-from-gregorian
  13763. (list m d (+ (nth 2 before) value)))))))
  13764. ;; Handle PREFER parameter, if any.
  13765. (cond
  13766. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13767. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13768. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13769. (defun org-date-to-gregorian (d)
  13770. "Turn any specification of date D into a Gregorian date for the calendar."
  13771. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13772. ((and (listp d) (= (length d) 3)) d)
  13773. ((stringp d)
  13774. (let ((d (org-parse-time-string d)))
  13775. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13776. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13777. (defun org-timestamp-up (&optional arg)
  13778. "Increase the date item at the cursor by one.
  13779. If the cursor is on the year, change the year. If it is on the month,
  13780. the day or the time, change that. If the cursor is on the enclosing
  13781. bracket, change the timestamp type.
  13782. With prefix ARG, change by that many units."
  13783. (interactive "p")
  13784. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13785. (defun org-timestamp-down (&optional arg)
  13786. "Decrease the date item at the cursor by one.
  13787. If the cursor is on the year, change the year. If it is on the month,
  13788. the day or the time, change that. If the cursor is on the enclosing
  13789. bracket, change the timestamp type.
  13790. With prefix ARG, change by that many units."
  13791. (interactive "p")
  13792. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13793. (defun org-timestamp-up-day (&optional arg)
  13794. "Increase the date in the time stamp by one day.
  13795. With prefix ARG, change that many days."
  13796. (interactive "p")
  13797. (if (and (not (org-at-timestamp-p 'lax))
  13798. (org-at-heading-p))
  13799. (org-todo 'up)
  13800. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13801. (defun org-timestamp-down-day (&optional arg)
  13802. "Decrease the date in the time stamp by one day.
  13803. With prefix ARG, change that many days."
  13804. (interactive "p")
  13805. (if (and (not (org-at-timestamp-p 'lax))
  13806. (org-at-heading-p))
  13807. (org-todo 'down)
  13808. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13809. (defun org-at-timestamp-p (&optional extended)
  13810. "Non-nil if point is inside a timestamp.
  13811. By default, the function only consider syntactically valid active
  13812. timestamps. However, the caller may have a broader definition
  13813. for timestamps. As a consequence, optional argument EXTENDED can
  13814. be set to the following values
  13815. `inactive'
  13816. Include also syntactically valid inactive timestamps.
  13817. `agenda'
  13818. Include timestamps allowed in Agenda, i.e., those in
  13819. properties drawers, planning lines and clock lines.
  13820. `lax'
  13821. Ignore context. The function matches any part of the
  13822. document looking like a timestamp. This includes comments,
  13823. example blocks...
  13824. For backward-compatibility with Org 9.0, every other non-nil
  13825. value is equivalent to `inactive'.
  13826. When at a timestamp, return the position of the point as a symbol
  13827. among `bracket', `after', `year', `month', `hour', `minute',
  13828. `day' or a number of character from the last know part of the
  13829. time stamp.
  13830. When matching, the match groups are the following:
  13831. group 1: year
  13832. group 2: month
  13833. group 3: day number
  13834. group 4: day name
  13835. group 5: hours, if any
  13836. group 6: minutes, if any"
  13837. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13838. (pos (point))
  13839. (match?
  13840. (let ((boundaries (org-in-regexp regexp)))
  13841. (save-match-data
  13842. (cond ((null boundaries) nil)
  13843. ((eq extended 'lax) t)
  13844. (t
  13845. (or (and (eq extended 'agenda)
  13846. (or (org-at-planning-p)
  13847. (org-at-property-p)
  13848. (and (bound-and-true-p
  13849. org-agenda-include-inactive-timestamps)
  13850. (org-at-clock-log-p))))
  13851. (eq 'timestamp
  13852. (save-excursion
  13853. (when (= pos (cdr boundaries)) (forward-char -1))
  13854. (org-element-type (org-element-context)))))))))))
  13855. (cond
  13856. ((not match?) nil)
  13857. ((= pos (match-beginning 0)) 'bracket)
  13858. ;; Distinguish location right before the closing bracket from
  13859. ;; right after it.
  13860. ((= pos (1- (match-end 0))) 'bracket)
  13861. ((= pos (match-end 0)) 'after)
  13862. ((org-pos-in-match-range pos 2) 'year)
  13863. ((org-pos-in-match-range pos 3) 'month)
  13864. ((org-pos-in-match-range pos 7) 'hour)
  13865. ((org-pos-in-match-range pos 8) 'minute)
  13866. ((or (org-pos-in-match-range pos 4)
  13867. (org-pos-in-match-range pos 5)) 'day)
  13868. ((and (> pos (or (match-end 8) (match-end 5)))
  13869. (< pos (match-end 0)))
  13870. (- pos (or (match-end 8) (match-end 5))))
  13871. (t 'day))))
  13872. (defun org-toggle-timestamp-type ()
  13873. "Toggle the type (<active> or [inactive]) of a time stamp."
  13874. (interactive)
  13875. (when (org-at-timestamp-p 'lax)
  13876. (let ((beg (match-beginning 0)) (end (match-end 0))
  13877. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13878. (save-excursion
  13879. (goto-char beg)
  13880. (while (re-search-forward "[][<>]" end t)
  13881. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13882. t t)))
  13883. (message "Timestamp is now %sactive"
  13884. (if (equal (char-after beg) ?<) "" "in")))))
  13885. (defun org-at-clock-log-p ()
  13886. "Non-nil if point is on a clock log line."
  13887. (and (org-match-line org-clock-line-re)
  13888. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13889. (defvar org-clock-history) ; defined in org-clock.el
  13890. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13891. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13892. "Change the date in the time stamp at point.
  13893. The date is changed by N times WHAT. WHAT can be `day', `month',
  13894. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13895. position in the timestamp determines what is changed.
  13896. When optional argument UPDOWN is non-nil, minutes are rounded
  13897. according to `org-time-stamp-rounding-minutes'.
  13898. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13899. \"--2d\"."
  13900. (let ((origin (point))
  13901. (timestamp? (org-at-timestamp-p 'lax))
  13902. origin-cat
  13903. with-hm inactive
  13904. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13905. extra rem
  13906. ts time time0 fixnext clrgx)
  13907. (unless timestamp? (user-error "Not at a timestamp"))
  13908. (if (and (not what) (eq timestamp? 'bracket))
  13909. (org-toggle-timestamp-type)
  13910. ;; Point isn't on brackets. Remember the part of the time-stamp
  13911. ;; the point was in. Indeed, size of time-stamps may change,
  13912. ;; but point must be kept in the same category nonetheless.
  13913. (setq origin-cat timestamp?)
  13914. (when (and (not what) (not (eq timestamp? 'day))
  13915. org-display-custom-times
  13916. (get-text-property (point) 'display)
  13917. (not (get-text-property (1- (point)) 'display)))
  13918. (setq timestamp? 'day))
  13919. (setq timestamp? (or what timestamp?)
  13920. inactive (= (char-after (match-beginning 0)) ?\[)
  13921. ts (match-string 0))
  13922. (replace-match "")
  13923. (when (string-match
  13924. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13925. ts)
  13926. (setq extra (match-string 1 ts))
  13927. (when suppress-tmp-delay
  13928. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13929. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13930. (setq with-hm t))
  13931. (setq time0 (org-parse-time-string ts))
  13932. (when (and updown
  13933. (eq timestamp? 'minute)
  13934. (not current-prefix-arg))
  13935. ;; This looks like s-up and s-down. Change by one rounding step.
  13936. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13937. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13938. (setcar (cdr time0) (+ (nth 1 time0)
  13939. (if (> n 0) (- rem) (- dm rem))))))
  13940. (setq time
  13941. (apply #'encode-time
  13942. (or (car time0) 0)
  13943. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13944. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13945. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13946. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13947. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13948. (nthcdr 6 time0)))
  13949. (when (and (memq timestamp? '(hour minute))
  13950. extra
  13951. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13952. (setq extra (org-modify-ts-extra
  13953. extra
  13954. (if (eq timestamp? 'hour) 2 5)
  13955. n dm)))
  13956. (when (integerp timestamp?)
  13957. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13958. (when (eq what 'calendar)
  13959. (let ((cal-date (org-get-date-from-calendar)))
  13960. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13961. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13962. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13963. (setcar time0 (or (car time0) 0))
  13964. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13965. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13966. (setq time (apply 'encode-time time0))))
  13967. ;; Insert the new time-stamp, and ensure point stays in the same
  13968. ;; category as before (i.e. not after the last position in that
  13969. ;; category).
  13970. (let ((pos (point)))
  13971. ;; Stay before inserted string. `save-excursion' is of no use.
  13972. (setq org-last-changed-timestamp
  13973. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13974. (goto-char pos))
  13975. (save-match-data
  13976. (looking-at org-ts-regexp3)
  13977. (goto-char
  13978. (pcase origin-cat
  13979. ;; `day' category ends before `hour' if any, or at the end
  13980. ;; of the day name.
  13981. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13982. (`hour (min (match-end 7) origin))
  13983. (`minute (min (1- (match-end 8)) origin))
  13984. ((pred integerp) (min (1- (match-end 0)) origin))
  13985. ;; Point was right after the time-stamp. However, the
  13986. ;; time-stamp length might have changed, so refer to
  13987. ;; (match-end 0) instead.
  13988. (`after (match-end 0))
  13989. ;; `year' and `month' have both fixed size: point couldn't
  13990. ;; have moved into another part.
  13991. (_ origin))))
  13992. ;; Update clock if on a CLOCK line.
  13993. (org-clock-update-time-maybe)
  13994. ;; Maybe adjust the closest clock in `org-clock-history'
  13995. (when org-clock-adjust-closest
  13996. (if (not (and (org-at-clock-log-p)
  13997. (< 1 (length (delq nil (mapcar 'marker-position
  13998. org-clock-history))))))
  13999. (message "No clock to adjust")
  14000. (cond ((save-excursion ; fix previous clock?
  14001. (re-search-backward org-ts-regexp0 nil t)
  14002. (looking-back (concat org-clock-string " \\[")
  14003. (line-beginning-position)))
  14004. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14005. ((save-excursion ; fix next clock?
  14006. (re-search-backward org-ts-regexp0 nil t)
  14007. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14008. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14009. (save-window-excursion
  14010. ;; Find closest clock to point, adjust the previous/next one in history
  14011. (let* ((p (save-excursion (org-back-to-heading t)))
  14012. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14013. (clfixnth
  14014. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14015. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14016. (if (not clfixpos)
  14017. (message "No clock to adjust")
  14018. (save-excursion
  14019. (org-goto-marker-or-bmk clfixpos)
  14020. (org-show-subtree)
  14021. (when (re-search-forward clrgx nil t)
  14022. (goto-char (match-beginning 1))
  14023. (let (org-clock-adjust-closest)
  14024. (org-timestamp-change n timestamp? updown))
  14025. (message "Clock adjusted in %s for heading: %s"
  14026. (file-name-nondirectory (buffer-file-name))
  14027. (org-get-heading t t)))))))))
  14028. ;; Try to recenter the calendar window, if any.
  14029. (when (and org-calendar-follow-timestamp-change
  14030. (get-buffer-window "*Calendar*" t)
  14031. (memq timestamp? '(day month year)))
  14032. (org-recenter-calendar (time-to-days time))))))
  14033. (defun org-modify-ts-extra (s pos n dm)
  14034. "Change the different parts of the lead-time and repeat fields in timestamp."
  14035. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14036. ng h m new rem)
  14037. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14038. (cond
  14039. ((or (org-pos-in-match-range pos 2)
  14040. (org-pos-in-match-range pos 3))
  14041. (setq m (string-to-number (match-string 3 s))
  14042. h (string-to-number (match-string 2 s)))
  14043. (if (org-pos-in-match-range pos 2)
  14044. (setq h (+ h n))
  14045. (setq n (* dm (with-no-warnings (cl-signum n))))
  14046. (unless (= 0 (setq rem (% m dm)))
  14047. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14048. (setq m (+ m n)))
  14049. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14050. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14051. (setq h (mod h 24))
  14052. (setq ng 1 new (format "-%02d:%02d" h m)))
  14053. ((org-pos-in-match-range pos 6)
  14054. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14055. ((org-pos-in-match-range pos 5)
  14056. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14057. ((org-pos-in-match-range pos 9)
  14058. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14059. ((org-pos-in-match-range pos 8)
  14060. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14061. (when ng
  14062. (setq s (concat
  14063. (substring s 0 (match-beginning ng))
  14064. new
  14065. (substring s (match-end ng))))))
  14066. s))
  14067. (defun org-recenter-calendar (d)
  14068. "If the calendar is visible, recenter it to date D."
  14069. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14070. (when cwin
  14071. (let ((calendar-move-hook nil))
  14072. (with-selected-window cwin
  14073. (calendar-goto-date
  14074. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14075. (defun org-goto-calendar (&optional arg)
  14076. "Go to the Emacs calendar at the current date.
  14077. If there is a time stamp in the current line, go to that date.
  14078. A prefix ARG can be used to force the current date."
  14079. (interactive "P")
  14080. (let ((calendar-move-hook nil)
  14081. (calendar-view-holidays-initially-flag nil)
  14082. (calendar-view-diary-initially-flag nil)
  14083. diff)
  14084. (when (or (org-at-timestamp-p 'lax)
  14085. (org-match-line (concat ".*" org-ts-regexp)))
  14086. (let ((d1 (time-to-days nil))
  14087. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14088. (setq diff (- d2 d1))))
  14089. (calendar)
  14090. (calendar-goto-today)
  14091. (when (and diff (not arg)) (calendar-forward-day diff))))
  14092. (defun org-get-date-from-calendar ()
  14093. "Return a list (month day year) of date at point in calendar."
  14094. (with-current-buffer "*Calendar*"
  14095. (save-match-data
  14096. (calendar-cursor-to-date))))
  14097. (defun org-date-from-calendar ()
  14098. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14099. If there is already a time stamp at the cursor position, update it."
  14100. (interactive)
  14101. (if (org-at-timestamp-p 'lax)
  14102. (org-timestamp-change 0 'calendar)
  14103. (let ((cal-date (org-get-date-from-calendar)))
  14104. (org-insert-time-stamp
  14105. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14106. (defcustom org-image-actual-width t
  14107. "When non-nil, use the actual width of images when inlining them.
  14108. When set to a number, use imagemagick (when available) to set the
  14109. image's width to this value.
  14110. When set to a number in a list, try to get the width from any
  14111. #+ATTR.* keyword if it matches a width specification like
  14112. #+ATTR_HTML: :width 300px
  14113. and fall back on that number if none is found.
  14114. When set to nil, try to get the width from an #+ATTR.* keyword
  14115. and fall back on the original width if none is found.
  14116. When set to any other non-nil value, always use the image width.
  14117. This requires Emacs >= 24.1, built with imagemagick support."
  14118. :group 'org-appearance
  14119. :version "24.4"
  14120. :package-version '(Org . "8.0")
  14121. :type '(choice
  14122. (const :tag "Use the image width" t)
  14123. (integer :tag "Use a number of pixels")
  14124. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14125. (const :tag "Use #+ATTR* or don't resize" nil)))
  14126. (defcustom org-agenda-inhibit-startup nil
  14127. "Inhibit startup when preparing agenda buffers.
  14128. When this variable is t, the initialization of the Org agenda
  14129. buffers is inhibited: e.g. the visibility state is not set, the
  14130. tables are not re-aligned, etc."
  14131. :type 'boolean
  14132. :version "24.3"
  14133. :group 'org-agenda)
  14134. (defcustom org-agenda-ignore-properties nil
  14135. "Avoid updating text properties when building the agenda.
  14136. Properties are used to prepare buffers for effort estimates,
  14137. appointments, statistics and subtree-local categories.
  14138. If you don't use these in the agenda, you can add them to this
  14139. list and agenda building will be a bit faster.
  14140. The value is a list, with zero or more of the symbols `effort', `appt',
  14141. `stats' or `category'."
  14142. :type '(set :greedy t
  14143. (const effort)
  14144. (const appt)
  14145. (const stats)
  14146. (const category))
  14147. :version "26.1"
  14148. :package-version '(Org . "8.3")
  14149. :group 'org-agenda)
  14150. ;;;; Files
  14151. (defun org-save-all-org-buffers ()
  14152. "Save all Org buffers without user confirmation."
  14153. (interactive)
  14154. (message "Saving all Org buffers...")
  14155. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14156. (when (featurep 'org-id) (org-id-locations-save))
  14157. (message "Saving all Org buffers... done"))
  14158. (defun org-revert-all-org-buffers ()
  14159. "Revert all Org buffers.
  14160. Prompt for confirmation when there are unsaved changes.
  14161. Be sure you know what you are doing before letting this function
  14162. overwrite your changes.
  14163. This function is useful in a setup where one tracks Org files
  14164. with a version control system, to revert on one machine after pulling
  14165. changes from another. I believe the procedure must be like this:
  14166. 1. M-x org-save-all-org-buffers
  14167. 2. Pull changes from the other machine, resolve conflicts
  14168. 3. M-x org-revert-all-org-buffers"
  14169. (interactive)
  14170. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14171. (user-error "Abort"))
  14172. (save-excursion
  14173. (save-window-excursion
  14174. (dolist (b (buffer-list))
  14175. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14176. (with-current-buffer b buffer-file-name))
  14177. (pop-to-buffer-same-window b)
  14178. (revert-buffer t 'no-confirm)))
  14179. (when (and (featurep 'org-id) org-id-track-globally)
  14180. (org-id-locations-load)))))
  14181. ;;;; Agenda files
  14182. ;;;###autoload
  14183. (defun org-switchb (&optional arg)
  14184. "Switch between Org buffers.
  14185. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14186. With `\\[universal-argument] \\[universal-argument]' \
  14187. prefix, restrict available buffers to agenda files."
  14188. (interactive "P")
  14189. (let ((blist (org-buffer-list
  14190. (cond ((equal arg '(4)) 'files)
  14191. ((equal arg '(16)) 'agenda)))))
  14192. (pop-to-buffer-same-window
  14193. (completing-read "Org buffer: "
  14194. (mapcar #'list (mapcar #'buffer-name blist))
  14195. nil t))))
  14196. (defun org-buffer-list (&optional predicate exclude-tmp)
  14197. "Return a list of Org buffers.
  14198. PREDICATE can be `export', `files' or `agenda'.
  14199. export restrict the list to Export buffers.
  14200. files restrict the list to buffers visiting Org files.
  14201. agenda restrict the list to buffers visiting agenda files.
  14202. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14203. (let* ((bfn nil)
  14204. (agenda-files (and (eq predicate 'agenda)
  14205. (mapcar 'file-truename (org-agenda-files t))))
  14206. (filter
  14207. (cond
  14208. ((eq predicate 'files)
  14209. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14210. ((eq predicate 'export)
  14211. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14212. ((eq predicate 'agenda)
  14213. (lambda (b)
  14214. (with-current-buffer b
  14215. (and (derived-mode-p 'org-mode)
  14216. (setq bfn (buffer-file-name b))
  14217. (member (file-truename bfn) agenda-files)))))
  14218. (t (lambda (b) (with-current-buffer b
  14219. (or (derived-mode-p 'org-mode)
  14220. (string-match "\\*Org .*Export"
  14221. (buffer-name b)))))))))
  14222. (delq nil
  14223. (mapcar
  14224. (lambda(b)
  14225. (if (and (funcall filter b)
  14226. (or (not exclude-tmp)
  14227. (not (string-match "tmp" (buffer-name b)))))
  14228. b
  14229. nil))
  14230. (buffer-list)))))
  14231. (defun org-agenda-files (&optional unrestricted archives)
  14232. "Get the list of agenda files.
  14233. Optional UNRESTRICTED means return the full list even if a restriction
  14234. is currently in place.
  14235. When ARCHIVES is t, include all archive files that are really being
  14236. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14237. `org-agenda-archives-mode' is t."
  14238. (let ((files
  14239. (cond
  14240. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14241. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14242. ((listp org-agenda-files) org-agenda-files)
  14243. (t (error "Invalid value of `org-agenda-files'")))))
  14244. (setq files (apply 'append
  14245. (mapcar (lambda (f)
  14246. (if (file-directory-p f)
  14247. (directory-files
  14248. f t org-agenda-file-regexp)
  14249. (list f)))
  14250. files)))
  14251. (when org-agenda-skip-unavailable-files
  14252. (setq files (delq nil
  14253. (mapcar (function
  14254. (lambda (file)
  14255. (and (file-readable-p file) file)))
  14256. files))))
  14257. (when (or (eq archives t)
  14258. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14259. (setq files (org-add-archive-files files)))
  14260. files))
  14261. (defun org-agenda-file-p (&optional file)
  14262. "Return non-nil, if FILE is an agenda file.
  14263. If FILE is omitted, use the file associated with the current
  14264. buffer."
  14265. (let ((fname (or file (buffer-file-name))))
  14266. (and fname
  14267. (member (file-truename fname)
  14268. (mapcar #'file-truename (org-agenda-files t))))))
  14269. (defun org-edit-agenda-file-list ()
  14270. "Edit the list of agenda files.
  14271. Depending on setup, this either uses customize to edit the variable
  14272. `org-agenda-files', or it visits the file that is holding the list. In the
  14273. latter case, the buffer is set up in a way that saving it automatically kills
  14274. the buffer and restores the previous window configuration."
  14275. (interactive)
  14276. (if (stringp org-agenda-files)
  14277. (let ((cw (current-window-configuration)))
  14278. (find-file org-agenda-files)
  14279. (setq-local org-window-configuration cw)
  14280. (add-hook 'after-save-hook
  14281. (lambda ()
  14282. (set-window-configuration
  14283. (prog1 org-window-configuration
  14284. (kill-buffer (current-buffer))))
  14285. (org-install-agenda-files-menu)
  14286. (message "New agenda file list installed"))
  14287. nil 'local)
  14288. (message "%s" (substitute-command-keys
  14289. "Edit list and finish with \\[save-buffer]")))
  14290. (customize-variable 'org-agenda-files)))
  14291. (defun org-store-new-agenda-file-list (list)
  14292. "Set new value for the agenda file list and save it correctly."
  14293. (if (stringp org-agenda-files)
  14294. (let ((fe (org-read-agenda-file-list t)) b u)
  14295. (while (setq b (find-buffer-visiting org-agenda-files))
  14296. (kill-buffer b))
  14297. (with-temp-file org-agenda-files
  14298. (insert
  14299. (mapconcat
  14300. (lambda (f) ;; Keep un-expanded entries.
  14301. (if (setq u (assoc f fe))
  14302. (cdr u)
  14303. f))
  14304. list "\n")
  14305. "\n")))
  14306. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14307. (org-insert-mode-line-in-empty-file nil))
  14308. (setq org-agenda-files list)
  14309. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14310. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14311. "Read the list of agenda files from a file.
  14312. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14313. filenames, used by `org-store-new-agenda-file-list' to write back
  14314. un-expanded file names."
  14315. (when (file-directory-p org-agenda-files)
  14316. (error "`org-agenda-files' cannot be a single directory"))
  14317. (when (stringp org-agenda-files)
  14318. (with-temp-buffer
  14319. (insert-file-contents org-agenda-files)
  14320. (mapcar
  14321. (lambda (f)
  14322. (let ((e (expand-file-name (substitute-in-file-name f)
  14323. org-directory)))
  14324. (if pair-with-expansion
  14325. (cons e f)
  14326. e)))
  14327. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14328. ;;;###autoload
  14329. (defun org-cycle-agenda-files ()
  14330. "Cycle through the files in `org-agenda-files'.
  14331. If the current buffer visits an agenda file, find the next one in the list.
  14332. If the current buffer does not, find the first agenda file."
  14333. (interactive)
  14334. (let* ((fs (or (org-agenda-files t)
  14335. (user-error "No agenda files")))
  14336. (files (copy-sequence fs))
  14337. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14338. file)
  14339. (when tcf
  14340. (while (and (setq file (pop files))
  14341. (not (equal (file-truename file) tcf)))))
  14342. (find-file (car (or files fs)))
  14343. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14344. (defun org-agenda-file-to-front (&optional to-end)
  14345. "Move/add the current file to the top of the agenda file list.
  14346. If the file is not present in the list, it is added to the front. If it is
  14347. present, it is moved there. With optional argument TO-END, add/move to the
  14348. end of the list."
  14349. (interactive "P")
  14350. (let ((org-agenda-skip-unavailable-files nil)
  14351. (file-alist (mapcar (lambda (x)
  14352. (cons (file-truename x) x))
  14353. (org-agenda-files t)))
  14354. (ctf (file-truename
  14355. (or buffer-file-name
  14356. (user-error "Please save the current buffer to a file"))))
  14357. x had)
  14358. (setq x (assoc ctf file-alist) had x)
  14359. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14360. (if to-end
  14361. (setq file-alist (append (delq x file-alist) (list x)))
  14362. (setq file-alist (cons x (delq x file-alist))))
  14363. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14364. (org-install-agenda-files-menu)
  14365. (message "File %s to %s of agenda file list"
  14366. (if had "moved" "added") (if to-end "end" "front"))))
  14367. (defun org-remove-file (&optional file)
  14368. "Remove current file from the list of files in variable `org-agenda-files'.
  14369. These are the files which are being checked for agenda entries.
  14370. Optional argument FILE means use this file instead of the current."
  14371. (interactive)
  14372. (let* ((org-agenda-skip-unavailable-files nil)
  14373. (file (or file buffer-file-name
  14374. (user-error "Current buffer does not visit a file")))
  14375. (true-file (file-truename file))
  14376. (afile (abbreviate-file-name file))
  14377. (files (delq nil (mapcar
  14378. (lambda (x)
  14379. (unless (equal true-file
  14380. (file-truename x))
  14381. x))
  14382. (org-agenda-files t)))))
  14383. (if (not (= (length files) (length (org-agenda-files t))))
  14384. (progn
  14385. (org-store-new-agenda-file-list files)
  14386. (org-install-agenda-files-menu)
  14387. (message "Removed from Org Agenda list: %s" afile))
  14388. (message "File was not in list: %s (not removed)" afile))))
  14389. (defun org-file-menu-entry (file)
  14390. (vector file (list 'find-file file) t))
  14391. (defun org-check-agenda-file (file)
  14392. "Make sure FILE exists. If not, ask user what to do."
  14393. (unless (file-exists-p file)
  14394. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14395. (abbreviate-file-name file))
  14396. (let ((r (downcase (read-char-exclusive))))
  14397. (cond
  14398. ((equal r ?r)
  14399. (org-remove-file file)
  14400. (throw 'nextfile t))
  14401. (t (user-error "Abort"))))))
  14402. (defun org-get-agenda-file-buffer (file)
  14403. "Get an agenda buffer visiting FILE.
  14404. If the buffer needs to be created, add it to the list of buffers
  14405. which might be released later."
  14406. (let ((buf (org-find-base-buffer-visiting file)))
  14407. (if buf
  14408. buf ; just return it
  14409. ;; Make a new buffer and remember it
  14410. (setq buf (find-file-noselect file))
  14411. (when buf (push buf org-agenda-new-buffers))
  14412. buf)))
  14413. (defun org-release-buffers (blist)
  14414. "Release all buffers in list, asking the user for confirmation when needed.
  14415. When a buffer is unmodified, it is just killed. When modified, it is saved
  14416. \(if the user agrees) and then killed."
  14417. (let (file)
  14418. (dolist (buf blist)
  14419. (setq file (buffer-file-name buf))
  14420. (when (and (buffer-modified-p buf)
  14421. file
  14422. (y-or-n-p (format "Save file %s? " file)))
  14423. (with-current-buffer buf (save-buffer)))
  14424. (kill-buffer buf))))
  14425. (defun org-agenda-prepare-buffers (files)
  14426. "Create buffers for all agenda files, protect archived trees and comments."
  14427. (interactive)
  14428. (let ((pa '(:org-archived t))
  14429. (pc '(:org-comment t))
  14430. (pall '(:org-archived t :org-comment t))
  14431. (inhibit-read-only t)
  14432. (org-inhibit-startup org-agenda-inhibit-startup)
  14433. (rea (org-make-tag-string (list org-archive-tag)))
  14434. re pos)
  14435. (setq org-tag-alist-for-agenda nil
  14436. org-tag-groups-alist-for-agenda nil)
  14437. (save-excursion
  14438. (save-restriction
  14439. (dolist (file files)
  14440. (catch 'nextfile
  14441. (if (bufferp file)
  14442. (set-buffer file)
  14443. (org-check-agenda-file file)
  14444. (set-buffer (org-get-agenda-file-buffer file)))
  14445. (widen)
  14446. (org-set-regexps-and-options 'tags-only)
  14447. (setq pos (point))
  14448. (or (memq 'category org-agenda-ignore-properties)
  14449. (org-refresh-category-properties))
  14450. (or (memq 'stats org-agenda-ignore-properties)
  14451. (org-refresh-stats-properties))
  14452. (or (memq 'effort org-agenda-ignore-properties)
  14453. (org-refresh-effort-properties))
  14454. (or (memq 'appt org-agenda-ignore-properties)
  14455. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14456. (setq org-todo-keywords-for-agenda
  14457. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14458. (setq org-done-keywords-for-agenda
  14459. (append org-done-keywords-for-agenda org-done-keywords))
  14460. (setq org-todo-keyword-alist-for-agenda
  14461. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14462. (setq org-tag-alist-for-agenda
  14463. (org--tag-add-to-alist
  14464. org-tag-alist-for-agenda
  14465. org-current-tag-alist))
  14466. ;; Merge current file's tag groups into global
  14467. ;; `org-tag-groups-alist-for-agenda'.
  14468. (when org-group-tags
  14469. (dolist (alist org-tag-groups-alist)
  14470. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14471. (if old
  14472. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14473. (push alist org-tag-groups-alist-for-agenda)))))
  14474. (with-silent-modifications
  14475. (save-excursion
  14476. (remove-text-properties (point-min) (point-max) pall)
  14477. (when org-agenda-skip-archived-trees
  14478. (goto-char (point-min))
  14479. (while (re-search-forward rea nil t)
  14480. (when (org-at-heading-p t)
  14481. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14482. (goto-char (point-min))
  14483. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14484. (while (re-search-forward re nil t)
  14485. (when (save-match-data (org-in-commented-heading-p t))
  14486. (add-text-properties
  14487. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14488. (goto-char pos)))))
  14489. (setq org-todo-keywords-for-agenda
  14490. (org-uniquify org-todo-keywords-for-agenda))
  14491. (setq org-todo-keyword-alist-for-agenda
  14492. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14493. ;;;; CDLaTeX minor mode
  14494. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14495. "Keymap for the minor `org-cdlatex-mode'.")
  14496. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14497. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14498. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14499. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14500. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14501. (defvar org-cdlatex-texmathp-advice-is-done nil
  14502. "Flag remembering if we have applied the advice to texmathp already.")
  14503. (define-minor-mode org-cdlatex-mode
  14504. "Toggle the minor `org-cdlatex-mode'.
  14505. This mode supports entering LaTeX environment and math in LaTeX fragments
  14506. in Org mode.
  14507. \\{org-cdlatex-mode-map}"
  14508. nil " OCDL" nil
  14509. (when org-cdlatex-mode
  14510. (require 'cdlatex)
  14511. (run-hooks 'cdlatex-mode-hook)
  14512. (cdlatex-compute-tables))
  14513. (unless org-cdlatex-texmathp-advice-is-done
  14514. (setq org-cdlatex-texmathp-advice-is-done t)
  14515. (defadvice texmathp (around org-math-always-on activate)
  14516. "Always return t in Org buffers.
  14517. This is because we want to insert math symbols without dollars even outside
  14518. the LaTeX math segments. If Org mode thinks that point is actually inside
  14519. an embedded LaTeX fragment, let `texmathp' do its job.
  14520. `\\[org-cdlatex-mode-map]'"
  14521. (interactive)
  14522. (let (p)
  14523. (cond
  14524. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14525. ((eq this-command 'cdlatex-math-symbol)
  14526. (setq ad-return-value t
  14527. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14528. (t
  14529. (let ((p (org-inside-LaTeX-fragment-p)))
  14530. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14531. (setq ad-return-value t
  14532. texmathp-why '("Org mode embedded math" . 0))
  14533. (when p ad-do-it)))))))))
  14534. (defun turn-on-org-cdlatex ()
  14535. "Unconditionally turn on `org-cdlatex-mode'."
  14536. (org-cdlatex-mode 1))
  14537. (defun org-try-cdlatex-tab ()
  14538. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14539. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14540. - inside a LaTeX fragment, or
  14541. - after the first word in a line, where an abbreviation expansion could
  14542. insert a LaTeX environment."
  14543. (when org-cdlatex-mode
  14544. (cond
  14545. ;; Before any word on the line: No expansion possible.
  14546. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14547. ;; Just after first word on the line: Expand it. Make sure it
  14548. ;; cannot happen on headlines, though.
  14549. ((save-excursion
  14550. (skip-chars-backward "a-zA-Z0-9*")
  14551. (skip-chars-backward " \t")
  14552. (and (bolp) (not (org-at-heading-p))))
  14553. (cdlatex-tab) t)
  14554. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14555. (defun org-cdlatex-underscore-caret (&optional _arg)
  14556. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14557. Revert to the normal definition outside of these fragments."
  14558. (interactive "P")
  14559. (if (org-inside-LaTeX-fragment-p)
  14560. (call-interactively 'cdlatex-sub-superscript)
  14561. (let (org-cdlatex-mode)
  14562. (call-interactively (key-binding (vector last-input-event))))))
  14563. (defun org-cdlatex-math-modify (&optional _arg)
  14564. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14565. Revert to the normal definition outside of these fragments."
  14566. (interactive "P")
  14567. (if (org-inside-LaTeX-fragment-p)
  14568. (call-interactively 'cdlatex-math-modify)
  14569. (let (org-cdlatex-mode)
  14570. (call-interactively (key-binding (vector last-input-event))))))
  14571. (defun org-cdlatex-environment-indent (&optional environment item)
  14572. "Execute `cdlatex-environment' and indent the inserted environment.
  14573. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14574. The inserted environment is indented to current indentation
  14575. unless point is at the beginning of the line, in which the
  14576. environment remains unintended."
  14577. (interactive)
  14578. ;; cdlatex-environment always return nil. Therefore, capture output
  14579. ;; first and determine if an environment was selected.
  14580. (let* ((beg (point-marker))
  14581. (end (copy-marker (point) t))
  14582. (inserted (progn
  14583. (ignore-errors (cdlatex-environment environment item))
  14584. (< beg end)))
  14585. ;; Figure out how many lines to move forward after the
  14586. ;; environment has been inserted.
  14587. (lines (when inserted
  14588. (save-excursion
  14589. (- (cl-loop while (< beg (point))
  14590. with x = 0
  14591. do (forward-line -1)
  14592. (cl-incf x)
  14593. finally return x)
  14594. (if (progn (goto-char beg)
  14595. (and (progn (skip-chars-forward " \t") (eolp))
  14596. (progn (skip-chars-backward " \t") (bolp))))
  14597. 1 0)))))
  14598. (env (org-trim (delete-and-extract-region beg end))))
  14599. (when inserted
  14600. ;; Get indentation of next line unless at column 0.
  14601. (let ((ind (if (bolp) 0
  14602. (save-excursion
  14603. (org-return-indent)
  14604. (prog1 (current-indentation)
  14605. (when (progn (skip-chars-forward " \t") (eolp))
  14606. (delete-region beg (point)))))))
  14607. (bol (progn (skip-chars-backward " \t") (bolp))))
  14608. ;; Insert a newline before environment unless at column zero
  14609. ;; to "escape" the current line. Insert a newline if
  14610. ;; something is one the same line as \end{ENVIRONMENT}.
  14611. (insert
  14612. (concat (unless bol "\n") env
  14613. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14614. (unless (zerop ind)
  14615. (save-excursion
  14616. (goto-char beg)
  14617. (while (< (point) end)
  14618. (unless (eolp) (indent-line-to ind))
  14619. (forward-line))))
  14620. (goto-char beg)
  14621. (forward-line lines)
  14622. (indent-line-to ind)))
  14623. (set-marker beg nil)
  14624. (set-marker end nil)))
  14625. ;;;; LaTeX fragments
  14626. (defun org-inside-LaTeX-fragment-p ()
  14627. "Test if point is inside a LaTeX fragment.
  14628. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14629. sequence appearing also before point.
  14630. Even though the matchers for math are configurable, this function assumes
  14631. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14632. delimiters are skipped when they have been removed by customization.
  14633. The return value is nil, or a cons cell with the delimiter and the
  14634. position of this delimiter.
  14635. This function does a reasonably good job, but can locally be fooled by
  14636. for example currency specifications. For example it will assume being in
  14637. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14638. fragments that are properly closed, but during editing, we have to live
  14639. with the uncertainty caused by missing closing delimiters. This function
  14640. looks only before point, not after."
  14641. (catch 'exit
  14642. (let ((pos (point))
  14643. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14644. (lim (save-excursion (org-backward-paragraph) (point)))
  14645. dd-on str (start 0) m re)
  14646. (goto-char pos)
  14647. (when dodollar
  14648. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14649. re (nth 1 (assoc "$" org-latex-regexps)))
  14650. (while (string-match re str start)
  14651. (cond
  14652. ((= (match-end 0) (length str))
  14653. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14654. ((= (match-end 0) (- (length str) 5))
  14655. (throw 'exit nil))
  14656. (t (setq start (match-end 0))))))
  14657. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14658. (goto-char pos)
  14659. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14660. (and (match-beginning 2) (throw 'exit nil))
  14661. ;; count $$
  14662. (while (re-search-backward "\\$\\$" lim t)
  14663. (setq dd-on (not dd-on)))
  14664. (goto-char pos)
  14665. (when dd-on (cons "$$" m))))))
  14666. (defun org-inside-latex-macro-p ()
  14667. "Is point inside a LaTeX macro or its arguments?"
  14668. (save-match-data
  14669. (org-in-regexp
  14670. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14671. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14672. "Build an overlay between BEG and END using IMAGE file.
  14673. Argument IMAGETYPE is the extension of the displayed image,
  14674. as a string. It defaults to \"png\"."
  14675. (let ((ov (make-overlay beg end))
  14676. (imagetype (or (intern imagetype) 'png)))
  14677. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14678. (overlay-put ov 'evaporate t)
  14679. (overlay-put ov
  14680. 'modification-hooks
  14681. (list (lambda (o _flag _beg _end &optional _l)
  14682. (delete-overlay o))))
  14683. (overlay-put ov
  14684. 'display
  14685. (list 'image :type imagetype :file image :ascent 'center))))
  14686. (defun org-clear-latex-preview (&optional beg end)
  14687. "Remove all overlays with LaTeX fragment images in current buffer.
  14688. When optional arguments BEG and END are non-nil, remove all
  14689. overlays between them instead. Return a non-nil value when some
  14690. overlays were removed, nil otherwise."
  14691. (let ((overlays
  14692. (cl-remove-if-not
  14693. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14694. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14695. (mapc #'delete-overlay overlays)
  14696. overlays))
  14697. (defun org--latex-preview-region (beg end)
  14698. "Preview LaTeX fragments between BEG and END.
  14699. BEG and END are buffer positions."
  14700. (let ((file (buffer-file-name (buffer-base-buffer))))
  14701. (save-excursion
  14702. (org-format-latex
  14703. (concat org-preview-latex-image-directory "org-ltximg")
  14704. beg end
  14705. ;; Emacs cannot overlay images from remote hosts. Create it in
  14706. ;; `temporary-file-directory' instead.
  14707. (if (or (not file) (file-remote-p file))
  14708. temporary-file-directory
  14709. default-directory)
  14710. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14711. (defun org-latex-preview (&optional arg)
  14712. "Toggle preview of the LaTeX fragment at point.
  14713. If the cursor is on a LaTeX fragment, create the image and
  14714. overlay it over the source code, if there is none. Remove it
  14715. otherwise. If there is no fragment at point, display images for
  14716. all fragments in the current section.
  14717. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14718. for all fragments
  14719. in the current section.
  14720. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14721. argument ARG, display image for all
  14722. fragments in the buffer.
  14723. With a `\\[universal-argument] \\[universal-argument] \
  14724. \\[universal-argument]' prefix argument ARG, clear image for all
  14725. fragments in the buffer."
  14726. (interactive "P")
  14727. (cond
  14728. ((not (display-graphic-p)) nil)
  14729. ;; Clear whole buffer.
  14730. ((equal arg '(64))
  14731. (org-clear-latex-preview (point-min) (point-max))
  14732. (message "LaTeX previews removed from buffer"))
  14733. ;; Preview whole buffer.
  14734. ((equal arg '(16))
  14735. (message "Creating LaTeX previews in buffer...")
  14736. (org--latex-preview-region (point-min) (point-max))
  14737. (message "Creating LaTeX previews in buffer... done."))
  14738. ;; Clear current section.
  14739. ((equal arg '(4))
  14740. (org-clear-latex-preview
  14741. (if (org-before-first-heading-p) (point-min)
  14742. (save-excursion
  14743. (org-with-limited-levels (org-back-to-heading t) (point))))
  14744. (org-with-limited-levels (org-entry-end-position))))
  14745. ;; Toggle preview on LaTeX code at point.
  14746. ((let ((datum (org-element-context)))
  14747. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14748. (let ((beg (org-element-property :begin datum))
  14749. (end (org-element-property :end datum)))
  14750. (if (org-clear-latex-preview beg end)
  14751. (message "LaTeX preview removed")
  14752. (message "Creating LaTeX preview...")
  14753. (org--latex-preview-region beg end)
  14754. (message "Creating LaTeX preview... done."))
  14755. t))))
  14756. ;; Preview current section.
  14757. (t
  14758. (let ((beg (if (org-before-first-heading-p) (point-min)
  14759. (save-excursion
  14760. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14761. (end (org-with-limited-levels (org-entry-end-position))))
  14762. (message "Creating LaTeX previews in section...")
  14763. (org--latex-preview-region beg end)
  14764. (message "Creating LaTeX previews in section... done.")))))
  14765. (defun org-format-latex
  14766. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14767. "Replace LaTeX fragments with links to an image.
  14768. The function takes care of creating the replacement image.
  14769. Only consider fragments between BEG and END when those are
  14770. provided.
  14771. When optional argument OVERLAYS is non-nil, display the image on
  14772. top of the fragment instead of replacing it.
  14773. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14774. Some of the options can be changed using the variable
  14775. `org-format-latex-options', which see."
  14776. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14777. (unless (eq processing-type 'verbatim)
  14778. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14779. (cnt 0)
  14780. checkdir-flag)
  14781. (goto-char (or beg (point-min)))
  14782. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14783. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14784. (overlay-recenter (or end (point-max))))
  14785. (while (re-search-forward math-regexp end t)
  14786. (unless (and overlays
  14787. (eq (get-char-property (point) 'org-overlay-type)
  14788. 'org-latex-overlay))
  14789. (let* ((context (org-element-context))
  14790. (type (org-element-type context)))
  14791. (when (memq type '(latex-environment latex-fragment))
  14792. (let ((block-type (eq type 'latex-environment))
  14793. (value (org-element-property :value context))
  14794. (beg (org-element-property :begin context))
  14795. (end (save-excursion
  14796. (goto-char (org-element-property :end context))
  14797. (skip-chars-backward " \r\t\n")
  14798. (point))))
  14799. (cond
  14800. ((eq processing-type 'mathjax)
  14801. ;; Prepare for MathJax processing.
  14802. (if (not (string-match "\\`\\$\\$?" value))
  14803. (goto-char end)
  14804. (delete-region beg end)
  14805. (if (string= (match-string 0 value) "$$")
  14806. (insert "\\[" (substring value 2 -2) "\\]")
  14807. (insert "\\(" (substring value 1 -1) "\\)"))))
  14808. ((assq processing-type org-preview-latex-process-alist)
  14809. ;; Process to an image.
  14810. (cl-incf cnt)
  14811. (goto-char beg)
  14812. (let* ((processing-info
  14813. (cdr (assq processing-type org-preview-latex-process-alist)))
  14814. (face (face-at-point))
  14815. ;; Get the colors from the face at point.
  14816. (fg
  14817. (let ((color (plist-get org-format-latex-options
  14818. :foreground)))
  14819. (if (and forbuffer (eq color 'auto))
  14820. (face-attribute face :foreground nil 'default)
  14821. color)))
  14822. (bg
  14823. (let ((color (plist-get org-format-latex-options
  14824. :background)))
  14825. (if (and forbuffer (eq color 'auto))
  14826. (face-attribute face :background nil 'default)
  14827. color)))
  14828. (hash (sha1 (prin1-to-string
  14829. (list org-format-latex-header
  14830. org-latex-default-packages-alist
  14831. org-latex-packages-alist
  14832. org-format-latex-options
  14833. forbuffer value fg bg))))
  14834. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14835. (absprefix (expand-file-name prefix dir))
  14836. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14837. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14838. (sep (and block-type "\n\n"))
  14839. (link (concat sep "[[file:" linkfile "]]" sep))
  14840. (options
  14841. (org-combine-plists
  14842. org-format-latex-options
  14843. `(:foreground ,fg :background ,bg))))
  14844. (when msg (message msg cnt))
  14845. (unless checkdir-flag ; Ensure the directory exists.
  14846. (setq checkdir-flag t)
  14847. (let ((todir (file-name-directory absprefix)))
  14848. (unless (file-directory-p todir)
  14849. (make-directory todir t))))
  14850. (unless (file-exists-p movefile)
  14851. (org-create-formula-image
  14852. value movefile options forbuffer processing-type))
  14853. (if overlays
  14854. (progn
  14855. (dolist (o (overlays-in beg end))
  14856. (when (eq (overlay-get o 'org-overlay-type)
  14857. 'org-latex-overlay)
  14858. (delete-overlay o)))
  14859. (org--make-preview-overlay beg end movefile imagetype)
  14860. (goto-char end))
  14861. (delete-region beg end)
  14862. (insert
  14863. (org-add-props link
  14864. (list 'org-latex-src
  14865. (replace-regexp-in-string "\"" "" value)
  14866. 'org-latex-src-embed-type
  14867. (if block-type 'paragraph 'character)))))))
  14868. ((eq processing-type 'mathml)
  14869. ;; Process to MathML.
  14870. (unless (org-format-latex-mathml-available-p)
  14871. (user-error "LaTeX to MathML converter not configured"))
  14872. (cl-incf cnt)
  14873. (when msg (message msg cnt))
  14874. (goto-char beg)
  14875. (delete-region beg end)
  14876. (insert (org-format-latex-as-mathml
  14877. value block-type prefix dir)))
  14878. (t
  14879. (error "Unknown conversion process %s for LaTeX fragments"
  14880. processing-type)))))))))))
  14881. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14882. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14883. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14884. sucessful, return the portion between \"<math...> </math>\"
  14885. elements otherwise return nil. When MATHML-FILE is specified,
  14886. write the results in to that file. When invoked as an
  14887. interactive command, prompt for LATEX-FRAG, with initial value
  14888. set to the current active region and echo the results for user
  14889. inspection."
  14890. (interactive (list (let ((frag (when (org-region-active-p)
  14891. (buffer-substring-no-properties
  14892. (region-beginning) (region-end)))))
  14893. (read-string "LaTeX Fragment: " frag nil frag))))
  14894. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14895. (let* ((tmp-in-file
  14896. (let ((file (file-relative-name
  14897. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14898. (write-region latex-frag nil file)
  14899. file))
  14900. (tmp-out-file (file-relative-name
  14901. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14902. (cmd (format-spec
  14903. org-latex-to-mathml-convert-command
  14904. `((?j . ,(and org-latex-to-mathml-jar-file
  14905. (shell-quote-argument
  14906. (expand-file-name
  14907. org-latex-to-mathml-jar-file))))
  14908. (?I . ,(shell-quote-argument tmp-in-file))
  14909. (?i . ,latex-frag)
  14910. (?o . ,(shell-quote-argument tmp-out-file)))))
  14911. mathml shell-command-output)
  14912. (when (called-interactively-p 'any)
  14913. (unless (org-format-latex-mathml-available-p)
  14914. (user-error "LaTeX to MathML converter not configured")))
  14915. (message "Running %s" cmd)
  14916. (setq shell-command-output (shell-command-to-string cmd))
  14917. (setq mathml
  14918. (when (file-readable-p tmp-out-file)
  14919. (with-current-buffer (find-file-noselect tmp-out-file t)
  14920. (goto-char (point-min))
  14921. (when (re-search-forward
  14922. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14923. (regexp-quote
  14924. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14925. nil t)
  14926. (prog1 (match-string 0) (kill-buffer))))))
  14927. (cond
  14928. (mathml
  14929. (setq mathml
  14930. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14931. (when mathml-file
  14932. (write-region mathml nil mathml-file))
  14933. (when (called-interactively-p 'any)
  14934. (message mathml)))
  14935. ((message "LaTeX to MathML conversion failed")
  14936. (message shell-command-output)))
  14937. (delete-file tmp-in-file)
  14938. (when (file-exists-p tmp-out-file)
  14939. (delete-file tmp-out-file))
  14940. mathml))
  14941. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14942. prefix &optional dir)
  14943. "Use `org-create-math-formula' but check local cache first."
  14944. (let* ((absprefix (expand-file-name prefix dir))
  14945. (print-length nil) (print-level nil)
  14946. (formula-id (concat
  14947. "formula-"
  14948. (sha1
  14949. (prin1-to-string
  14950. (list latex-frag
  14951. org-latex-to-mathml-convert-command)))))
  14952. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14953. (formula-cache-dir (file-name-directory formula-cache)))
  14954. (unless (file-directory-p formula-cache-dir)
  14955. (make-directory formula-cache-dir t))
  14956. (unless (file-exists-p formula-cache)
  14957. (org-create-math-formula latex-frag formula-cache))
  14958. (if (file-exists-p formula-cache)
  14959. ;; Successful conversion. Return the link to MathML file.
  14960. (org-add-props
  14961. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14962. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14963. 'org-latex-src-embed-type (if latex-frag-type
  14964. 'paragraph 'character)))
  14965. ;; Failed conversion. Return the LaTeX fragment verbatim
  14966. latex-frag)))
  14967. (defun org--get-display-dpi ()
  14968. "Get the DPI of the display.
  14969. The function assumes that the display has the same pixel width in
  14970. the horizontal and vertical directions."
  14971. (if (display-graphic-p)
  14972. (round (/ (display-pixel-height)
  14973. (/ (display-mm-height) 25.4)))
  14974. (error "Attempt to calculate the dpi of a non-graphic display")))
  14975. (defun org-create-formula-image
  14976. (string tofile options buffer &optional processing-type)
  14977. "Create an image from LaTeX source using external processes.
  14978. The LaTeX STRING is saved to a temporary LaTeX file, then
  14979. converted to an image file by process PROCESSING-TYPE defined in
  14980. `org-preview-latex-process-alist'. A nil value defaults to
  14981. `org-preview-latex-default-process'.
  14982. The generated image file is eventually moved to TOFILE.
  14983. The OPTIONS argument controls the size, foreground color and
  14984. background color of the generated image.
  14985. When BUFFER non-nil, this function is used for LaTeX previewing.
  14986. Otherwise, it is used to deal with LaTeX snippets showed in
  14987. a HTML file."
  14988. (let* ((processing-type (or processing-type
  14989. org-preview-latex-default-process))
  14990. (processing-info
  14991. (cdr (assq processing-type org-preview-latex-process-alist)))
  14992. (programs (plist-get processing-info :programs))
  14993. (error-message (or (plist-get processing-info :message) ""))
  14994. (image-input-type (plist-get processing-info :image-input-type))
  14995. (image-output-type (plist-get processing-info :image-output-type))
  14996. (post-clean (or (plist-get processing-info :post-clean)
  14997. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14998. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14999. (latex-header
  15000. (or (plist-get processing-info :latex-header)
  15001. (org-latex-make-preamble
  15002. (org-export-get-environment (org-export-get-backend 'latex))
  15003. org-format-latex-header
  15004. 'snippet)))
  15005. (latex-compiler (plist-get processing-info :latex-compiler))
  15006. (image-converter (plist-get processing-info :image-converter))
  15007. (tmpdir temporary-file-directory)
  15008. (texfilebase (make-temp-name
  15009. (expand-file-name "orgtex" tmpdir)))
  15010. (texfile (concat texfilebase ".tex"))
  15011. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15012. '(1.0 . 1.0)))
  15013. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15014. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15015. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15016. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15017. "Black"))
  15018. (bg (or (plist-get options (if buffer :background :html-background))
  15019. "Transparent"))
  15020. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15021. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15022. (dolist (program programs)
  15023. (org-check-external-command program error-message))
  15024. (if (eq fg 'default)
  15025. (setq fg (org-latex-color :foreground))
  15026. (setq fg (org-latex-color-format fg)))
  15027. (if (eq bg 'default)
  15028. (setq bg (org-latex-color :background))
  15029. (setq bg (org-latex-color-format
  15030. (if (string= bg "Transparent") "white" bg))))
  15031. (with-temp-file texfile
  15032. (insert latex-header)
  15033. (insert "\n\\begin{document}\n"
  15034. "\\definecolor{fg}{rgb}{" fg "}\n"
  15035. "\\definecolor{bg}{rgb}{" bg "}\n"
  15036. "\n\\pagecolor{bg}\n"
  15037. "\n{\\color{fg}\n"
  15038. string
  15039. "\n}\n"
  15040. "\n\\end{document}\n"))
  15041. (let* ((err-msg (format "Please adjust `%s' part of \
  15042. `org-preview-latex-process-alist'."
  15043. processing-type))
  15044. (image-input-file
  15045. (org-compile-file
  15046. texfile latex-compiler image-input-type err-msg log-buf))
  15047. (image-output-file
  15048. (org-compile-file
  15049. image-input-file image-converter image-output-type err-msg log-buf
  15050. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15051. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15052. (copy-file image-output-file tofile 'replace)
  15053. (dolist (e post-clean)
  15054. (when (file-exists-p (concat texfilebase e))
  15055. (delete-file (concat texfilebase e))))
  15056. image-output-file)))
  15057. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15058. "Fill a LaTeX header template TPL.
  15059. In the template, the following place holders will be recognized:
  15060. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15061. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15062. [PACKAGES] \\usepackage statements for PKG
  15063. [NO-PACKAGES] do not include PKG
  15064. [EXTRA] the string EXTRA
  15065. [NO-EXTRA] do not include EXTRA
  15066. For backward compatibility, if both the positive and the negative place
  15067. holder is missing, the positive one (without the \"NO-\") will be
  15068. assumed to be present at the end of the template.
  15069. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15070. EXTRA is a string.
  15071. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15072. (let (rpl (end ""))
  15073. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15074. (setq rpl (if (or (match-end 1) (not def-pkg))
  15075. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15076. tpl (replace-match rpl t t tpl))
  15077. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15078. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15079. (setq rpl (if (or (match-end 1) (not pkg))
  15080. "" (org-latex-packages-to-string pkg snippets-p t))
  15081. tpl (replace-match rpl t t tpl))
  15082. (when pkg (setq end
  15083. (concat end "\n"
  15084. (org-latex-packages-to-string pkg snippets-p)))))
  15085. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15086. (setq rpl (if (or (match-end 1) (not extra))
  15087. "" (concat extra "\n"))
  15088. tpl (replace-match rpl t t tpl))
  15089. (when (and extra (string-match "\\S-" extra))
  15090. (setq end (concat end "\n" extra))))
  15091. (if (string-match "\\S-" end)
  15092. (concat tpl "\n" end)
  15093. tpl)))
  15094. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15095. "Turn an alist of packages into a string with the \\usepackage macros."
  15096. (setq pkg (mapconcat (lambda(p)
  15097. (cond
  15098. ((stringp p) p)
  15099. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15100. (format "%% Package %s omitted" (cadr p)))
  15101. ((equal "" (car p))
  15102. (format "\\usepackage{%s}" (cadr p)))
  15103. (t
  15104. (format "\\usepackage[%s]{%s}"
  15105. (car p) (cadr p)))))
  15106. pkg
  15107. "\n"))
  15108. (if newline (concat pkg "\n") pkg))
  15109. (defun org-dvipng-color (attr)
  15110. "Return a RGB color specification for dvipng."
  15111. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15112. (defun org-dvipng-color-format (color-name)
  15113. "Convert COLOR-NAME to a RGB color value for dvipng."
  15114. (apply #'format "rgb %s %s %s"
  15115. (mapcar 'org-normalize-color
  15116. (color-values color-name))))
  15117. (defun org-latex-color (attr)
  15118. "Return a RGB color for the LaTeX color package."
  15119. (org-latex-color-format (face-attribute 'default attr nil)))
  15120. (defun org-latex-color-format (color-name)
  15121. "Convert COLOR-NAME to a RGB color value."
  15122. (apply #'format "%s,%s,%s"
  15123. (mapcar 'org-normalize-color
  15124. (color-values color-name))))
  15125. (defun org-normalize-color (value)
  15126. "Return string to be used as color value for an RGB component."
  15127. (format "%g" (/ value 65535.0)))
  15128. ;; Image display
  15129. (defvar-local org-inline-image-overlays nil)
  15130. (defun org-toggle-inline-images (&optional include-linked)
  15131. "Toggle the display of inline images.
  15132. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15133. (interactive "P")
  15134. (if org-inline-image-overlays
  15135. (progn
  15136. (org-remove-inline-images)
  15137. (when (called-interactively-p 'interactive)
  15138. (message "Inline image display turned off")))
  15139. (org-display-inline-images include-linked)
  15140. (when (called-interactively-p 'interactive)
  15141. (message (if org-inline-image-overlays
  15142. (format "%d images displayed inline"
  15143. (length org-inline-image-overlays))
  15144. "No images to display inline")))))
  15145. (defun org-redisplay-inline-images ()
  15146. "Refresh the display of inline images."
  15147. (interactive)
  15148. (if (not org-inline-image-overlays)
  15149. (org-toggle-inline-images)
  15150. (org-toggle-inline-images)
  15151. (org-toggle-inline-images)))
  15152. ;; For without-x builds.
  15153. (declare-function image-refresh "image" (spec &optional frame))
  15154. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15155. "Display inline images.
  15156. An inline image is a link which follows either of these
  15157. conventions:
  15158. 1. Its path is a file with an extension matching return value
  15159. from `image-file-name-regexp' and it has no contents.
  15160. 2. Its description consists in a single link of the previous
  15161. type. In this case, that link must be a well-formed plain
  15162. or angle link, i.e., it must have an explicit \"file\" type.
  15163. When optional argument INCLUDE-LINKED is non-nil, also links with
  15164. a text description part will be inlined. This can be nice for
  15165. a quick look at those images, but it does not reflect what
  15166. exported files will look like.
  15167. When optional argument REFRESH is non-nil, refresh existing
  15168. images between BEG and END. This will create new image displays
  15169. only if necessary. BEG and END default to the buffer
  15170. boundaries."
  15171. (interactive "P")
  15172. (when (display-graphic-p)
  15173. (unless refresh
  15174. (org-remove-inline-images)
  15175. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15176. (org-with-point-at (or beg 1)
  15177. (let* ((case-fold-search t)
  15178. (file-extension-re (image-file-name-regexp))
  15179. (link-abbrevs (mapcar #'car
  15180. (append org-link-abbrev-alist-local
  15181. org-link-abbrev-alist)))
  15182. ;; Check absolute, relative file names and explicit
  15183. ;; "file:" links. Also check link abbreviations since
  15184. ;; some might expand to "file" links.
  15185. (file-types-re
  15186. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15187. (if (not link-abbrevs) ""
  15188. (concat "\\|" (regexp-opt link-abbrevs))))))
  15189. (while (re-search-forward file-types-re end t)
  15190. (let* ((link (org-element-lineage
  15191. (save-match-data (org-element-context))
  15192. '(link) t))
  15193. (linktype (org-element-property :type link))
  15194. (inner-start (match-beginning 1))
  15195. (path
  15196. (cond
  15197. ;; No link at point; no inline image.
  15198. ((not link) nil)
  15199. ;; File link without a description. Also handle
  15200. ;; INCLUDE-LINKED here since it should have
  15201. ;; precedence over the next case. I.e., if link
  15202. ;; contains filenames in both the path and the
  15203. ;; description, prioritize the path only when
  15204. ;; INCLUDE-LINKED is non-nil.
  15205. ((or (not (org-element-property :contents-begin link))
  15206. include-linked)
  15207. (and (or (equal "file" linktype)
  15208. (equal "attachment" linktype))
  15209. (org-element-property :path link)))
  15210. ;; Link with a description. Check if description
  15211. ;; is a filename. Even if Org doesn't have syntax
  15212. ;; for those -- clickable image -- constructs, fake
  15213. ;; them, as in `org-export-insert-image-links'.
  15214. ((not inner-start) nil)
  15215. (t
  15216. (org-with-point-at inner-start
  15217. (and (looking-at
  15218. (if (char-equal ?< (char-after inner-start))
  15219. org-link-angle-re
  15220. org-link-plain-re))
  15221. ;; File name must fill the whole
  15222. ;; description.
  15223. (= (org-element-property :contents-end link)
  15224. (match-end 0))
  15225. (match-string 2)))))))
  15226. (when (and path (string-match-p file-extension-re path))
  15227. (let ((file (if (equal "attachment" linktype)
  15228. (progn
  15229. (require 'org-attach)
  15230. (org-attach-expand path))
  15231. (expand-file-name path))))
  15232. (when (file-exists-p file)
  15233. (let ((width
  15234. ;; Apply `org-image-actual-width' specifications.
  15235. (cond
  15236. ((not (image-type-available-p 'imagemagick)) nil)
  15237. ((eq org-image-actual-width t) nil)
  15238. ((listp org-image-actual-width)
  15239. (or
  15240. ;; First try to find a width among
  15241. ;; attributes associated to the paragraph
  15242. ;; containing link.
  15243. (pcase (org-element-lineage link '(paragraph))
  15244. (`nil nil)
  15245. (p
  15246. (let* ((case-fold-search t)
  15247. (end (org-element-property :post-affiliated p))
  15248. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15249. (when (org-with-point-at
  15250. (org-element-property :begin p)
  15251. (re-search-forward re end t))
  15252. (string-to-number (match-string 1))))))
  15253. ;; Otherwise, fall-back to provided number.
  15254. (car org-image-actual-width)))
  15255. ((numberp org-image-actual-width)
  15256. org-image-actual-width)))
  15257. (old (get-char-property-and-overlay
  15258. (org-element-property :begin link)
  15259. 'org-image-overlay)))
  15260. (if (and (car-safe old) refresh)
  15261. (image-refresh (overlay-get (cdr old) 'display))
  15262. (let ((image (create-image file
  15263. (and width 'imagemagick)
  15264. nil
  15265. :width width)))
  15266. (when image
  15267. (let ((ov (make-overlay
  15268. (org-element-property :begin link)
  15269. (progn
  15270. (goto-char
  15271. (org-element-property :end link))
  15272. (skip-chars-backward " \t")
  15273. (point)))))
  15274. (overlay-put ov 'display image)
  15275. (overlay-put ov 'face 'default)
  15276. (overlay-put ov 'org-image-overlay t)
  15277. (overlay-put
  15278. ov 'modification-hooks
  15279. (list 'org-display-inline-remove-overlay))
  15280. (push ov org-inline-image-overlays)))))))))))))))
  15281. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15282. "Remove inline-display overlay if a corresponding region is modified."
  15283. (let ((inhibit-modification-hooks t))
  15284. (when (and ov after)
  15285. (delete ov org-inline-image-overlays)
  15286. (delete-overlay ov))))
  15287. (defun org-remove-inline-images ()
  15288. "Remove inline display of images."
  15289. (interactive)
  15290. (mapc #'delete-overlay org-inline-image-overlays)
  15291. (setq org-inline-image-overlays nil))
  15292. (defvar org-self-insert-command-undo-counter 0)
  15293. (defvar org-speed-command nil)
  15294. (defun org-self-insert-command (N)
  15295. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15296. If the cursor is in a table looking at whitespace, the whitespace is
  15297. overwritten, and the table is not marked as requiring realignment."
  15298. (interactive "p")
  15299. (org-check-before-invisible-edit 'insert)
  15300. (cond
  15301. ((and org-use-speed-commands
  15302. (let ((kv (this-command-keys-vector)))
  15303. (setq org-speed-command
  15304. (run-hook-with-args-until-success
  15305. 'org-speed-command-hook
  15306. (make-string 1 (aref kv (1- (length kv))))))))
  15307. (cond
  15308. ((commandp org-speed-command)
  15309. (setq this-command org-speed-command)
  15310. (call-interactively org-speed-command))
  15311. ((functionp org-speed-command)
  15312. (funcall org-speed-command))
  15313. ((and org-speed-command (listp org-speed-command))
  15314. (eval org-speed-command))
  15315. (t (let (org-use-speed-commands)
  15316. (call-interactively 'org-self-insert-command)))))
  15317. ((and
  15318. (= N 1)
  15319. (not (org-region-active-p))
  15320. (org-at-table-p)
  15321. (progn
  15322. ;; Check if we blank the field, and if that triggers align.
  15323. (and (featurep 'org-table)
  15324. org-table-auto-blank-field
  15325. (memq last-command
  15326. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15327. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15328. ;; Got extra space, this field does not determine
  15329. ;; column width.
  15330. (let (org-table-may-need-update) (org-table-blank-field))
  15331. ;; No extra space, this field may determine column
  15332. ;; width.
  15333. (org-table-blank-field)))
  15334. t)
  15335. (looking-at "[^|\n]* |"))
  15336. ;; There is room for insertion without re-aligning the table.
  15337. (self-insert-command N)
  15338. (org-table-with-shrunk-field
  15339. (save-excursion
  15340. (skip-chars-forward "^|")
  15341. ;; Do not delete last space, which is
  15342. ;; `org-table-separator-space', but the regular space before
  15343. ;; it.
  15344. (delete-region (- (point) 2) (1- (point))))))
  15345. (t
  15346. (setq org-table-may-need-update t)
  15347. (self-insert-command N)
  15348. (org-fix-tags-on-the-fly)
  15349. (when org-self-insert-cluster-for-undo
  15350. (if (not (eq last-command 'org-self-insert-command))
  15351. (setq org-self-insert-command-undo-counter 1)
  15352. (if (>= org-self-insert-command-undo-counter 20)
  15353. (setq org-self-insert-command-undo-counter 1)
  15354. (and (> org-self-insert-command-undo-counter 0)
  15355. buffer-undo-list (listp buffer-undo-list)
  15356. (not (cadr buffer-undo-list)) ; remove nil entry
  15357. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15358. (setq org-self-insert-command-undo-counter
  15359. (1+ org-self-insert-command-undo-counter))))))))
  15360. (defun org-check-before-invisible-edit (kind)
  15361. "Check is editing if kind KIND would be dangerous with invisible text around.
  15362. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15363. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15364. (when (and org-catch-invisible-edits
  15365. (or (not (boundp 'visible-mode)) (not visible-mode))
  15366. (or (get-char-property (point) 'invisible)
  15367. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15368. ;; OK, we need to take a closer look. Do not consider
  15369. ;; invisibility obtained through text properties (e.g., link
  15370. ;; fontification), as it cannot be toggled.
  15371. (let* ((invisible-at-point
  15372. (pcase (get-char-property-and-overlay (point) 'invisible)
  15373. (`(,_ . ,(and (pred overlayp) o)) o)))
  15374. ;; Assume that point cannot land in the middle of an
  15375. ;; overlay, or between two overlays.
  15376. (invisible-before-point
  15377. (and (not invisible-at-point)
  15378. (not (bobp))
  15379. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15380. (`(,_ . ,(and (pred overlayp) o)) o))))
  15381. (border-and-ok-direction
  15382. (or
  15383. ;; Check if we are acting predictably before invisible
  15384. ;; text.
  15385. (and invisible-at-point
  15386. (memq kind '(insert delete-backward)))
  15387. ;; Check if we are acting predictably after invisible text
  15388. ;; This works not well, and I have turned it off. It seems
  15389. ;; better to always show and stop after invisible text.
  15390. ;; (and (not invisible-at-point) invisible-before-point
  15391. ;; (memq kind '(insert delete)))
  15392. )))
  15393. (when (or invisible-at-point invisible-before-point)
  15394. (when (eq org-catch-invisible-edits 'error)
  15395. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15396. (if (and org-custom-properties-overlays
  15397. (y-or-n-p "Display invisible properties in this buffer? "))
  15398. (org-toggle-custom-properties-visibility)
  15399. ;; Make the area visible
  15400. (save-excursion
  15401. (when invisible-before-point
  15402. (goto-char
  15403. (previous-single-char-property-change (point) 'invisible)))
  15404. ;; Remove whatever overlay is currently making yet-to-be
  15405. ;; edited text invisible. Also remove nested invisibility
  15406. ;; related overlays.
  15407. (delete-overlay (or invisible-at-point invisible-before-point))
  15408. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15409. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15410. (`(,_ . ,(and (pred overlayp) o))
  15411. (delete-overlay o)
  15412. t)))))
  15413. (cond
  15414. ((eq org-catch-invisible-edits 'show)
  15415. ;; That's it, we do the edit after showing
  15416. (message
  15417. "Unfolding invisible region around point before editing")
  15418. (sit-for 1))
  15419. ((and (eq org-catch-invisible-edits 'smart)
  15420. border-and-ok-direction)
  15421. (message "Unfolding invisible region around point before editing"))
  15422. (t
  15423. ;; Don't do the edit, make the user repeat it in full visibility
  15424. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15425. (defun org-fix-tags-on-the-fly ()
  15426. "Align tags in headline at point.
  15427. Unlike `org-align-tags', this function does nothing if point is
  15428. either not currently on a tagged headline or on a tag."
  15429. (when (and (org-match-line org-tag-line-re)
  15430. (< (point) (match-beginning 1)))
  15431. (org-align-tags)))
  15432. (defun org-delete-backward-char (N)
  15433. "Like `delete-backward-char', insert whitespace at field end in tables.
  15434. When deleting backwards, in tables this function will insert whitespace in
  15435. front of the next \"|\" separator, to keep the table aligned. The table will
  15436. still be marked for re-alignment if the field did fill the entire column,
  15437. because, in this case the deletion might narrow the column."
  15438. (interactive "p")
  15439. (save-match-data
  15440. (org-check-before-invisible-edit 'delete-backward)
  15441. (if (and (= N 1)
  15442. (not overwrite-mode)
  15443. (not (org-region-active-p))
  15444. (not (eq (char-before) ?|))
  15445. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15446. (looking-at-p ".*?|")
  15447. (org-at-table-p))
  15448. (progn (forward-char -1) (org-delete-char 1))
  15449. (backward-delete-char N)
  15450. (org-fix-tags-on-the-fly))))
  15451. (defun org-delete-char (N)
  15452. "Like `delete-char', but insert whitespace at field end in tables.
  15453. When deleting characters, in tables this function will insert whitespace in
  15454. front of the next \"|\" separator, to keep the table aligned. The table will
  15455. still be marked for re-alignment if the field did fill the entire column,
  15456. because, in this case the deletion might narrow the column."
  15457. (interactive "p")
  15458. (save-match-data
  15459. (org-check-before-invisible-edit 'delete)
  15460. (cond
  15461. ((or (/= N 1)
  15462. (eq (char-after) ?|)
  15463. (save-excursion (skip-chars-backward " \t") (bolp))
  15464. (not (org-at-table-p)))
  15465. (delete-char N)
  15466. (org-fix-tags-on-the-fly))
  15467. ((looking-at ".\\(.*?\\)|")
  15468. (let* ((update? org-table-may-need-update)
  15469. (noalign (looking-at-p ".*? |")))
  15470. (delete-char 1)
  15471. (org-table-with-shrunk-field
  15472. (save-excursion
  15473. ;; Last space is `org-table-separator-space', so insert
  15474. ;; a regular one before it instead.
  15475. (goto-char (- (match-end 0) 2))
  15476. (insert " ")))
  15477. ;; If there were two spaces at the end, this field does not
  15478. ;; determine the width of the column.
  15479. (when noalign (setq org-table-may-need-update update?))))
  15480. (t
  15481. (delete-char N)))))
  15482. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15483. (put 'org-self-insert-command 'delete-selection
  15484. (lambda ()
  15485. (not (run-hook-with-args-until-success
  15486. 'self-insert-uses-region-functions))))
  15487. (put 'orgtbl-self-insert-command 'delete-selection
  15488. (lambda ()
  15489. (not (run-hook-with-args-until-success
  15490. 'self-insert-uses-region-functions))))
  15491. (put 'org-delete-char 'delete-selection 'supersede)
  15492. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15493. (put 'org-yank 'delete-selection 'yank)
  15494. ;; Make `flyspell-mode' delay after some commands
  15495. (put 'org-self-insert-command 'flyspell-delayed t)
  15496. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15497. (put 'org-delete-char 'flyspell-delayed t)
  15498. (put 'org-delete-backward-char 'flyspell-delayed t)
  15499. ;; Make pabbrev-mode expand after Org mode commands
  15500. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15501. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15502. (defun org-transpose-words ()
  15503. "Transpose words for Org.
  15504. This uses the `org-mode-transpose-word-syntax-table' syntax
  15505. table, which interprets characters in `org-emphasis-alist' as
  15506. word constituents."
  15507. (interactive)
  15508. (with-syntax-table org-mode-transpose-word-syntax-table
  15509. (call-interactively 'transpose-words)))
  15510. (defvar org-ctrl-c-ctrl-c-hook nil
  15511. "Hook for functions attaching themselves to `C-c C-c'.
  15512. This can be used to add additional functionality to the C-c C-c
  15513. key which executes context-dependent commands. This hook is run
  15514. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15515. run after the last test.
  15516. Each function will be called with no arguments. The function
  15517. must check if the context is appropriate for it to act. If yes,
  15518. it should do its thing and then return a non-nil value. If the
  15519. context is wrong, just do nothing and return nil.")
  15520. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15521. "Hook for functions attaching themselves to `C-c C-c'.
  15522. This can be used to add additional functionality to the C-c C-c
  15523. key which executes context-dependent commands. This hook is run
  15524. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15525. before the first test.
  15526. Each function will be called with no arguments. The function
  15527. must check if the context is appropriate for it to act. If yes,
  15528. it should do its thing and then return a non-nil value. If the
  15529. context is wrong, just do nothing and return nil.")
  15530. (defvar org-tab-first-hook nil
  15531. "Hook for functions to attach themselves to TAB.
  15532. See `org-ctrl-c-ctrl-c-hook' for more information.
  15533. This hook runs as the first action when TAB is pressed, even before
  15534. `org-cycle' messes around with the `outline-regexp' to cater for
  15535. inline tasks and plain list item folding.
  15536. If any function in this hook returns t, any other actions that
  15537. would have been caused by TAB (such as table field motion or visibility
  15538. cycling) will not occur.")
  15539. (defvar org-tab-after-check-for-table-hook nil
  15540. "Hook for functions to attach themselves to TAB.
  15541. See `org-ctrl-c-ctrl-c-hook' for more information.
  15542. This hook runs after it has been established that the cursor is not in a
  15543. table, but before checking if the cursor is in a headline or if global cycling
  15544. should be done.
  15545. If any function in this hook returns t, not other actions like visibility
  15546. cycling will be done.")
  15547. (defvar org-tab-after-check-for-cycling-hook nil
  15548. "Hook for functions to attach themselves to TAB.
  15549. See `org-ctrl-c-ctrl-c-hook' for more information.
  15550. This hook runs after it has been established that not table field motion and
  15551. not visibility should be done because of current context. This is probably
  15552. the place where a package like yasnippets can hook in.")
  15553. (defvar org-tab-before-tab-emulation-hook nil
  15554. "Hook for functions to attach themselves to TAB.
  15555. See `org-ctrl-c-ctrl-c-hook' for more information.
  15556. This hook runs after every other options for TAB have been exhausted, but
  15557. before indentation and \t insertion takes place.")
  15558. (defvar org-metaleft-hook nil
  15559. "Hook for functions attaching themselves to `M-left'.
  15560. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15561. (defvar org-metaright-hook nil
  15562. "Hook for functions attaching themselves to `M-right'.
  15563. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15564. (defvar org-metaup-hook nil
  15565. "Hook for functions attaching themselves to `M-up'.
  15566. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15567. (defvar org-metadown-hook nil
  15568. "Hook for functions attaching themselves to `M-down'.
  15569. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15570. (defvar org-shiftmetaleft-hook nil
  15571. "Hook for functions attaching themselves to `M-S-left'.
  15572. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15573. (defvar org-shiftmetaright-hook nil
  15574. "Hook for functions attaching themselves to `M-S-right'.
  15575. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15576. (defvar org-shiftmetaup-hook nil
  15577. "Hook for functions attaching themselves to `M-S-up'.
  15578. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15579. (defvar org-shiftmetadown-hook nil
  15580. "Hook for functions attaching themselves to `M-S-down'.
  15581. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15582. (defvar org-metareturn-hook nil
  15583. "Hook for functions attaching themselves to `M-RET'.
  15584. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15585. (defvar org-shiftup-hook nil
  15586. "Hook for functions attaching themselves to `S-up'.
  15587. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15588. (defvar org-shiftup-final-hook nil
  15589. "Hook for functions attaching themselves to `S-up'.
  15590. This one runs after all other options except shift-select have been excluded.
  15591. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15592. (defvar org-shiftdown-hook nil
  15593. "Hook for functions attaching themselves to `S-down'.
  15594. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15595. (defvar org-shiftdown-final-hook nil
  15596. "Hook for functions attaching themselves to `S-down'.
  15597. This one runs after all other options except shift-select have been excluded.
  15598. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15599. (defvar org-shiftleft-hook nil
  15600. "Hook for functions attaching themselves to `S-left'.
  15601. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15602. (defvar org-shiftleft-final-hook nil
  15603. "Hook for functions attaching themselves to `S-left'.
  15604. This one runs after all other options except shift-select have been excluded.
  15605. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15606. (defvar org-shiftright-hook nil
  15607. "Hook for functions attaching themselves to `S-right'.
  15608. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15609. (defvar org-shiftright-final-hook nil
  15610. "Hook for functions attaching themselves to `S-right'.
  15611. This one runs after all other options except shift-select have been excluded.
  15612. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15613. (defun org-modifier-cursor-error ()
  15614. "Throw an error, a modified cursor command was applied in wrong context."
  15615. (user-error "This command is active in special context like tables, headlines or items"))
  15616. (defun org-shiftselect-error ()
  15617. "Throw an error because Shift-Cursor command was applied in wrong context."
  15618. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15619. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15620. (user-error "This command works only in special context like headlines or timestamps")))
  15621. (defun org-call-for-shift-select (cmd)
  15622. (let ((this-command-keys-shift-translated t))
  15623. (call-interactively cmd)))
  15624. (defun org-shifttab (&optional arg)
  15625. "Global visibility cycling or move to previous table field.
  15626. Call `org-table-previous-field' within a table.
  15627. When ARG is nil, cycle globally through visibility states.
  15628. When ARG is a numeric prefix, show contents of this level."
  15629. (interactive "P")
  15630. (cond
  15631. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15632. ((integerp arg)
  15633. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15634. (message "Content view to level: %d" arg)
  15635. (org-content (prefix-numeric-value arg2))
  15636. (org-cycle-show-empty-lines t)
  15637. (setq org-cycle-global-status 'overview)))
  15638. (t (call-interactively 'org-global-cycle))))
  15639. (defun org-shiftmetaleft ()
  15640. "Promote subtree or delete table column.
  15641. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15642. `org-table-delete-column', depending on context. See the
  15643. individual commands for more information."
  15644. (interactive)
  15645. (cond
  15646. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15647. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15648. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15649. ((if (not (org-region-active-p)) (org-at-item-p)
  15650. (save-excursion (goto-char (region-beginning))
  15651. (org-at-item-p)))
  15652. (call-interactively 'org-outdent-item-tree))
  15653. (t (org-modifier-cursor-error))))
  15654. (defun org-shiftmetaright ()
  15655. "Demote subtree or insert table column.
  15656. Calls `org-demote-subtree', `org-indent-item-tree', or
  15657. `org-table-insert-column', depending on context. See the
  15658. individual commands for more information."
  15659. (interactive)
  15660. (cond
  15661. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15662. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15663. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15664. ((if (not (org-region-active-p)) (org-at-item-p)
  15665. (save-excursion (goto-char (region-beginning))
  15666. (org-at-item-p)))
  15667. (call-interactively 'org-indent-item-tree))
  15668. (t (org-modifier-cursor-error))))
  15669. (defun org-shiftmetaup (&optional _arg)
  15670. "Drag the line at point up.
  15671. In a table, kill the current row.
  15672. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15673. but also adjust the previous clocked item in the clock history.
  15674. Everywhere else, drag the line at point up."
  15675. (interactive "P")
  15676. (cond
  15677. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15678. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15679. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15680. (call-interactively 'org-timestamp-up)))
  15681. (t (call-interactively 'org-drag-line-backward))))
  15682. (defun org-shiftmetadown (&optional _arg)
  15683. "Drag the line at point down.
  15684. In a table, insert an empty row at the current line.
  15685. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15686. but also adjust the previous clocked item in the clock history.
  15687. Everywhere else, drag the line at point down."
  15688. (interactive "P")
  15689. (cond
  15690. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15691. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15692. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15693. (call-interactively 'org-timestamp-down)))
  15694. (t (call-interactively 'org-drag-line-forward))))
  15695. (defsubst org-hidden-tree-error ()
  15696. (user-error
  15697. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15698. (defun org-metaleft (&optional _arg)
  15699. "Promote heading, list item at point or move table column left.
  15700. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15701. depending on context. With no specific context, calls the Emacs
  15702. default `backward-word'. See the individual commands for more
  15703. information.
  15704. This function runs the hook `org-metaleft-hook' as a first step,
  15705. and returns at first non-nil value."
  15706. (interactive "P")
  15707. (cond
  15708. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15709. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15710. ((org-with-limited-levels
  15711. (or (org-at-heading-p)
  15712. (and (org-region-active-p)
  15713. (save-excursion
  15714. (goto-char (region-beginning))
  15715. (org-at-heading-p)))))
  15716. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15717. (call-interactively 'org-do-promote))
  15718. ;; At an inline task.
  15719. ((org-at-heading-p)
  15720. (call-interactively 'org-inlinetask-promote))
  15721. ((or (org-at-item-p)
  15722. (and (org-region-active-p)
  15723. (save-excursion
  15724. (goto-char (region-beginning))
  15725. (org-at-item-p))))
  15726. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15727. (call-interactively 'org-outdent-item))
  15728. (t (call-interactively 'backward-word))))
  15729. (defun org-metaright (&optional _arg)
  15730. "Demote heading, list item at point or move table column right.
  15731. In front of a drawer or a block keyword, indent it correctly.
  15732. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15733. `org-indent-drawer' or `org-indent-block' depending on context.
  15734. With no specific context, calls the Emacs default `forward-word'.
  15735. See the individual commands for more information.
  15736. This function runs the hook `org-metaright-hook' as a first step,
  15737. and returns at first non-nil value."
  15738. (interactive "P")
  15739. (cond
  15740. ((run-hook-with-args-until-success 'org-metaright-hook))
  15741. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15742. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15743. ((org-at-block-p) (call-interactively 'org-indent-block))
  15744. ((org-with-limited-levels
  15745. (or (org-at-heading-p)
  15746. (and (org-region-active-p)
  15747. (save-excursion
  15748. (goto-char (region-beginning))
  15749. (org-at-heading-p)))))
  15750. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15751. (call-interactively 'org-do-demote))
  15752. ;; At an inline task.
  15753. ((org-at-heading-p)
  15754. (call-interactively 'org-inlinetask-demote))
  15755. ((or (org-at-item-p)
  15756. (and (org-region-active-p)
  15757. (save-excursion
  15758. (goto-char (region-beginning))
  15759. (org-at-item-p))))
  15760. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15761. (call-interactively 'org-indent-item))
  15762. (t (call-interactively 'forward-word))))
  15763. (defun org-check-for-hidden (what)
  15764. "Check if there are hidden headlines/items in the current visual line.
  15765. WHAT can be either `headlines' or `items'. If the current line is
  15766. an outline or item heading and it has a folded subtree below it,
  15767. this function returns t, nil otherwise."
  15768. (let ((re (cond
  15769. ((eq what 'headlines) org-outline-regexp-bol)
  15770. ((eq what 'items) (org-item-beginning-re))
  15771. (t (error "This should not happen"))))
  15772. beg end)
  15773. (save-excursion
  15774. (catch 'exit
  15775. (unless (org-region-active-p)
  15776. (setq beg (point-at-bol))
  15777. (beginning-of-line 2)
  15778. (while (and (not (eobp)) ;; this is like `next-line'
  15779. (get-char-property (1- (point)) 'invisible))
  15780. (beginning-of-line 2))
  15781. (setq end (point))
  15782. (goto-char beg)
  15783. (goto-char (point-at-eol))
  15784. (setq end (max end (point)))
  15785. (while (re-search-forward re end t)
  15786. (when (get-char-property (match-beginning 0) 'invisible)
  15787. (throw 'exit t))))
  15788. nil))))
  15789. (defun org-metaup (&optional _arg)
  15790. "Move subtree up or move table row up.
  15791. Calls `org-move-subtree-up' or `org-table-move-row' or
  15792. `org-move-item-up', depending on context. See the individual commands
  15793. for more information."
  15794. (interactive "P")
  15795. (cond
  15796. ((run-hook-with-args-until-success 'org-metaup-hook))
  15797. ((org-region-active-p)
  15798. (let* ((a (save-excursion
  15799. (goto-char (min (region-beginning) (region-end)))
  15800. (line-beginning-position)))
  15801. (b (save-excursion
  15802. (goto-char (max (region-beginning) (region-end)))
  15803. (if (bolp) (1- (point)) (line-end-position))))
  15804. (c (save-excursion
  15805. (goto-char a)
  15806. (move-beginning-of-line 0)
  15807. (point)))
  15808. (d (save-excursion
  15809. (goto-char a)
  15810. (move-end-of-line 0)
  15811. (point))))
  15812. (transpose-regions a b c d)
  15813. (goto-char c)))
  15814. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15815. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15816. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15817. (t (org-drag-element-backward))))
  15818. (defun org-metadown (&optional _arg)
  15819. "Move subtree down or move table row down.
  15820. Calls `org-move-subtree-down' or `org-table-move-row' or
  15821. `org-move-item-down', depending on context. See the individual
  15822. commands for more information."
  15823. (interactive "P")
  15824. (cond
  15825. ((run-hook-with-args-until-success 'org-metadown-hook))
  15826. ((org-region-active-p)
  15827. (let* ((a (save-excursion
  15828. (goto-char (min (region-beginning) (region-end)))
  15829. (line-beginning-position)))
  15830. (b (save-excursion
  15831. (goto-char (max (region-beginning) (region-end)))
  15832. (if (bolp) (1- (point)) (line-end-position))))
  15833. (c (save-excursion
  15834. (goto-char b)
  15835. (move-beginning-of-line (if (bolp) 1 2))
  15836. (point)))
  15837. (d (save-excursion
  15838. (goto-char b)
  15839. (move-end-of-line (if (bolp) 1 2))
  15840. (point))))
  15841. (transpose-regions a b c d)
  15842. (goto-char d)))
  15843. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15844. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15845. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15846. (t (org-drag-element-forward))))
  15847. (defun org-shiftup (&optional arg)
  15848. "Act on current element according to context.
  15849. Call `org-timestamp-up' or `org-priority-up', or
  15850. `org-previous-item', or `org-table-move-cell-up'. See the
  15851. individual commands for more information."
  15852. (interactive "P")
  15853. (cond
  15854. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15855. ((and org-support-shift-select (org-region-active-p))
  15856. (org-call-for-shift-select 'previous-line))
  15857. ((org-at-timestamp-p 'lax)
  15858. (call-interactively (if org-edit-timestamp-down-means-later
  15859. 'org-timestamp-down 'org-timestamp-up)))
  15860. ((and (not (eq org-support-shift-select 'always))
  15861. org-enable-priority-commands
  15862. (org-at-heading-p))
  15863. (call-interactively 'org-priority-up))
  15864. ((and (not org-support-shift-select) (org-at-item-p))
  15865. (call-interactively 'org-previous-item))
  15866. ((org-clocktable-try-shift 'up arg))
  15867. ((org-at-table-p) (org-table-move-cell-up))
  15868. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15869. (org-support-shift-select
  15870. (org-call-for-shift-select 'previous-line))
  15871. (t (org-shiftselect-error))))
  15872. (defun org-shiftdown (&optional arg)
  15873. "Act on current element according to context.
  15874. Call `org-timestamp-down' or `org-priority-down', or
  15875. `org-next-item', or `org-table-move-cell-down'. See the
  15876. individual commands for more information."
  15877. (interactive "P")
  15878. (cond
  15879. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15880. ((and org-support-shift-select (org-region-active-p))
  15881. (org-call-for-shift-select 'next-line))
  15882. ((org-at-timestamp-p 'lax)
  15883. (call-interactively (if org-edit-timestamp-down-means-later
  15884. 'org-timestamp-up 'org-timestamp-down)))
  15885. ((and (not (eq org-support-shift-select 'always))
  15886. org-enable-priority-commands
  15887. (org-at-heading-p))
  15888. (call-interactively 'org-priority-down))
  15889. ((and (not org-support-shift-select) (org-at-item-p))
  15890. (call-interactively 'org-next-item))
  15891. ((org-clocktable-try-shift 'down arg))
  15892. ((org-at-table-p) (org-table-move-cell-down))
  15893. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15894. (org-support-shift-select
  15895. (org-call-for-shift-select 'next-line))
  15896. (t (org-shiftselect-error))))
  15897. (defun org-shiftright (&optional arg)
  15898. "Act on the current element according to context.
  15899. This does one of the following:
  15900. - switch a timestamp at point one day into the future
  15901. - on a headline, switch to the next TODO keyword.
  15902. - on an item, switch entire list to the next bullet type
  15903. - on a property line, switch to the next allowed value
  15904. - on a clocktable definition line, move time block into the future
  15905. - in a table, move a single cell right"
  15906. (interactive "P")
  15907. (cond
  15908. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15909. ((and org-support-shift-select (org-region-active-p))
  15910. (org-call-for-shift-select 'forward-char))
  15911. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15912. ((and (not (eq org-support-shift-select 'always))
  15913. (org-at-heading-p))
  15914. (let ((org-inhibit-logging
  15915. (not org-treat-S-cursor-todo-selection-as-state-change))
  15916. (org-inhibit-blocking
  15917. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15918. (org-call-with-arg 'org-todo 'right)))
  15919. ((or (and org-support-shift-select
  15920. (not (eq org-support-shift-select 'always))
  15921. (org-at-item-bullet-p))
  15922. (and (not org-support-shift-select) (org-at-item-p)))
  15923. (org-call-with-arg 'org-cycle-list-bullet nil))
  15924. ((and (not (eq org-support-shift-select 'always))
  15925. (org-at-property-p))
  15926. (call-interactively 'org-property-next-allowed-value))
  15927. ((org-clocktable-try-shift 'right arg))
  15928. ((org-at-table-p) (org-table-move-cell-right))
  15929. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15930. (org-support-shift-select
  15931. (org-call-for-shift-select 'forward-char))
  15932. (t (org-shiftselect-error))))
  15933. (defun org-shiftleft (&optional arg)
  15934. "Act on current element according to context.
  15935. This does one of the following:
  15936. - switch a timestamp at point one day into the past
  15937. - on a headline, switch to the previous TODO keyword.
  15938. - on an item, switch entire list to the previous bullet type
  15939. - on a property line, switch to the previous allowed value
  15940. - on a clocktable definition line, move time block into the past
  15941. - in a table, move a single cell left"
  15942. (interactive "P")
  15943. (cond
  15944. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15945. ((and org-support-shift-select (org-region-active-p))
  15946. (org-call-for-shift-select 'backward-char))
  15947. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15948. ((and (not (eq org-support-shift-select 'always))
  15949. (org-at-heading-p))
  15950. (let ((org-inhibit-logging
  15951. (not org-treat-S-cursor-todo-selection-as-state-change))
  15952. (org-inhibit-blocking
  15953. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15954. (org-call-with-arg 'org-todo 'left)))
  15955. ((or (and org-support-shift-select
  15956. (not (eq org-support-shift-select 'always))
  15957. (org-at-item-bullet-p))
  15958. (and (not org-support-shift-select) (org-at-item-p)))
  15959. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15960. ((and (not (eq org-support-shift-select 'always))
  15961. (org-at-property-p))
  15962. (call-interactively 'org-property-previous-allowed-value))
  15963. ((org-clocktable-try-shift 'left arg))
  15964. ((org-at-table-p) (org-table-move-cell-left))
  15965. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15966. (org-support-shift-select
  15967. (org-call-for-shift-select 'backward-char))
  15968. (t (org-shiftselect-error))))
  15969. (defun org-shiftcontrolright ()
  15970. "Switch to next TODO set."
  15971. (interactive)
  15972. (cond
  15973. ((and org-support-shift-select (org-region-active-p))
  15974. (org-call-for-shift-select 'forward-word))
  15975. ((and (not (eq org-support-shift-select 'always))
  15976. (org-at-heading-p))
  15977. (org-call-with-arg 'org-todo 'nextset))
  15978. (org-support-shift-select
  15979. (org-call-for-shift-select 'forward-word))
  15980. (t (org-shiftselect-error))))
  15981. (defun org-shiftcontrolleft ()
  15982. "Switch to previous TODO set."
  15983. (interactive)
  15984. (cond
  15985. ((and org-support-shift-select (org-region-active-p))
  15986. (org-call-for-shift-select 'backward-word))
  15987. ((and (not (eq org-support-shift-select 'always))
  15988. (org-at-heading-p))
  15989. (org-call-with-arg 'org-todo 'previousset))
  15990. (org-support-shift-select
  15991. (org-call-for-shift-select 'backward-word))
  15992. (t (org-shiftselect-error))))
  15993. (defun org-shiftcontrolup (&optional n)
  15994. "Change timestamps synchronously up in CLOCK log lines.
  15995. Optional argument N tells to change by that many units."
  15996. (interactive "P")
  15997. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15998. (let (org-support-shift-select)
  15999. (org-clock-timestamps-up n))
  16000. (user-error "Not at a clock log")))
  16001. (defun org-shiftcontroldown (&optional n)
  16002. "Change timestamps synchronously down in CLOCK log lines.
  16003. Optional argument N tells to change by that many units."
  16004. (interactive "P")
  16005. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16006. (let (org-support-shift-select)
  16007. (org-clock-timestamps-down n))
  16008. (user-error "Not at a clock log")))
  16009. (defun org-increase-number-at-point (&optional inc)
  16010. "Increment the number at point.
  16011. With an optional prefix numeric argument INC, increment using
  16012. this numeric value."
  16013. (interactive "p")
  16014. (if (not (number-at-point))
  16015. (user-error "Not on a number")
  16016. (unless inc (setq inc 1))
  16017. (let ((pos (point))
  16018. (beg (skip-chars-backward "-+^/*0-9eE."))
  16019. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16020. (setq nap (buffer-substring-no-properties
  16021. (+ pos beg) (+ pos beg end)))
  16022. (delete-region (+ pos beg) (+ pos beg end))
  16023. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16024. (when (org-at-table-p)
  16025. (org-table-align)
  16026. (org-table-end-of-field 1))))
  16027. (defun org-decrease-number-at-point (&optional inc)
  16028. "Decrement the number at point.
  16029. With an optional prefix numeric argument INC, decrement using
  16030. this numeric value."
  16031. (interactive "p")
  16032. (org-increase-number-at-point (- (or inc 1))))
  16033. (defun org-ctrl-c-ret ()
  16034. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16035. (interactive)
  16036. (cond
  16037. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16038. (t (call-interactively 'org-insert-heading))))
  16039. (defun org-find-visible ()
  16040. (let ((s (point)))
  16041. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16042. (get-char-property s 'invisible)))
  16043. s))
  16044. (defun org-find-invisible ()
  16045. (let ((s (point)))
  16046. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16047. (not (get-char-property s 'invisible))))
  16048. s))
  16049. (defun org-copy-visible (beg end)
  16050. "Copy the visible parts of the region."
  16051. (interactive "r")
  16052. (let ((result ""))
  16053. (while (/= beg end)
  16054. (when (get-char-property beg 'invisible)
  16055. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16056. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16057. (setq result (concat result (buffer-substring beg next)))
  16058. (setq beg next)))
  16059. (setq deactivate-mark t)
  16060. (kill-new result)
  16061. (message "Visible strings have been copied to the kill ring.")))
  16062. (defun org-copy-special ()
  16063. "Copy region in table or copy current subtree.
  16064. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16065. context. See the individual commands for more information."
  16066. (interactive)
  16067. (call-interactively
  16068. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16069. (defun org-cut-special ()
  16070. "Cut region in table or cut current subtree.
  16071. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16072. context. See the individual commands for more information."
  16073. (interactive)
  16074. (call-interactively
  16075. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16076. (defun org-paste-special (arg)
  16077. "Paste rectangular region into table, or past subtree relative to level.
  16078. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16079. See the individual commands for more information."
  16080. (interactive "P")
  16081. (if (org-at-table-p)
  16082. (org-table-paste-rectangle)
  16083. (org-paste-subtree arg)))
  16084. (defun org-edit-special (&optional arg)
  16085. "Call a special editor for the element at point.
  16086. When at a table, call the formula editor with `org-table-edit-formulas'.
  16087. When in a source code block, call `org-edit-src-code'.
  16088. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16089. When in an export block, call `org-edit-export-block'.
  16090. When in a LaTeX environment, call `org-edit-latex-environment'.
  16091. When at an #+INCLUDE keyword, visit the included file.
  16092. When at a footnote reference, call `org-edit-footnote-reference'.
  16093. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16094. When at an active timestamp, call `org-time-stamp'.
  16095. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16096. On a link, call `ffap' to visit the link at point.
  16097. Otherwise, return a user error."
  16098. (interactive "P")
  16099. (let ((element (org-element-at-point)))
  16100. (barf-if-buffer-read-only)
  16101. (pcase (org-element-type element)
  16102. (`src-block
  16103. (if (not arg) (org-edit-src-code)
  16104. (let* ((info (org-babel-get-src-block-info))
  16105. (lang (nth 0 info))
  16106. (params (nth 2 info))
  16107. (session (cdr (assq :session params))))
  16108. (if (not session) (org-edit-src-code)
  16109. ;; At a source block with a session and function called
  16110. ;; with an ARG: switch to the buffer related to the
  16111. ;; inferior process.
  16112. (switch-to-buffer
  16113. (funcall (intern (concat "org-babel-prep-session:" lang))
  16114. session params))))))
  16115. (`keyword
  16116. (unless (member (org-element-property :key element)
  16117. '("INCLUDE" "SETUPFILE"))
  16118. (user-error "No special environment to edit here"))
  16119. (let ((value (org-element-property :value element)))
  16120. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16121. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16122. (or (match-string 1 value)
  16123. (match-string 0 value)))))
  16124. (when (org-file-url-p file)
  16125. (user-error "Files located with a URL cannot be edited"))
  16126. (org-link-open-from-string
  16127. (format "[[%s]]" (expand-file-name file))))))
  16128. (`table
  16129. (if (eq (org-element-property :type element) 'table.el)
  16130. (org-edit-table.el)
  16131. (call-interactively 'org-table-edit-formulas)))
  16132. ;; Only Org tables contain `table-row' type elements.
  16133. (`table-row (call-interactively 'org-table-edit-formulas))
  16134. (`example-block (org-edit-src-code))
  16135. (`export-block (org-edit-export-block))
  16136. (`fixed-width (org-edit-fixed-width-region))
  16137. (`latex-environment (org-edit-latex-environment))
  16138. (`planning
  16139. (let ((proplist (cadr element)))
  16140. (mapc #'call-interactively
  16141. (remq nil
  16142. (list
  16143. (when (plist-get proplist :deadline) #'org-deadline)
  16144. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16145. (_
  16146. ;; No notable element at point. Though, we may be at a link or
  16147. ;; a footnote reference, which are objects. Thus, scan deeper.
  16148. (let ((context (org-element-context element)))
  16149. (pcase (org-element-type context)
  16150. (`footnote-reference (org-edit-footnote-reference))
  16151. (`inline-src-block (org-edit-inline-src-code))
  16152. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16153. (call-interactively #'org-time-stamp-inactive)
  16154. (call-interactively #'org-time-stamp)))
  16155. (`link (call-interactively #'ffap))
  16156. (_ (user-error "No special environment to edit here"))))))))
  16157. (defun org-ctrl-c-ctrl-c (&optional arg)
  16158. "Set tags in headline, or update according to changed information at point.
  16159. This command does many different things, depending on context:
  16160. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16161. this is what we do.
  16162. - If the cursor is on a statistics cookie, update it.
  16163. - If the cursor is in a headline, prompt for tags and insert them
  16164. into the current line, aligned to `org-tags-column'. When called
  16165. with prefix arg, realign all tags in the current buffer.
  16166. - If the cursor is in one of the special #+KEYWORD lines, this
  16167. triggers scanning the buffer for these lines and updating the
  16168. information.
  16169. - If the cursor is inside a table, realign the table. This command
  16170. works even if the automatic table editor has been turned off.
  16171. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16172. the entire table.
  16173. - If the cursor is at a footnote reference or definition, jump to
  16174. the corresponding definition or references, respectively.
  16175. - If the cursor is a the beginning of a dynamic block, update it.
  16176. - If the current buffer is a capture buffer, close note and file it.
  16177. - If the cursor is on a <<<target>>>, update radio targets and
  16178. corresponding links in this buffer.
  16179. - If the cursor is on a numbered item in a plain list, renumber the
  16180. ordered list.
  16181. - If the cursor is on a checkbox, toggle it.
  16182. - If the cursor is on a code block, evaluate it. The variable
  16183. `org-confirm-babel-evaluate' can be used to control prompting
  16184. before code block evaluation, by default every code block
  16185. evaluation requires confirmation. Code block evaluation can be
  16186. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16187. (interactive "P")
  16188. (cond
  16189. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16190. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16191. (org-remove-occur-highlights)
  16192. (message "Temporary highlights/overlays removed from current buffer"))
  16193. ((and (local-variable-p 'org-finish-function)
  16194. (fboundp org-finish-function))
  16195. (funcall org-finish-function))
  16196. ((org-babel-hash-at-point))
  16197. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16198. (t
  16199. (let* ((context
  16200. (org-element-lineage
  16201. (org-element-context)
  16202. ;; Limit to supported contexts.
  16203. '(babel-call clock dynamic-block footnote-definition
  16204. footnote-reference inline-babel-call inline-src-block
  16205. inlinetask item keyword node-property paragraph
  16206. plain-list planning property-drawer radio-target
  16207. src-block statistics-cookie table table-cell table-row
  16208. timestamp)
  16209. t))
  16210. (type (org-element-type context)))
  16211. ;; For convenience: at the first line of a paragraph on the same
  16212. ;; line as an item, apply function on that item instead.
  16213. (when (eq type 'paragraph)
  16214. (let ((parent (org-element-property :parent context)))
  16215. (when (and (eq (org-element-type parent) 'item)
  16216. (= (line-beginning-position)
  16217. (org-element-property :begin parent)))
  16218. (setq context parent)
  16219. (setq type 'item))))
  16220. ;; Act according to type of element or object at point.
  16221. ;;
  16222. ;; Do nothing on a blank line, except if it is contained in
  16223. ;; a source block. Hence, we first check if point is in such
  16224. ;; a block and then if it is at a blank line.
  16225. (pcase type
  16226. ((or `inline-src-block `src-block)
  16227. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16228. (org-babel-eval-wipe-error-buffer)
  16229. (org-babel-execute-src-block
  16230. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16231. ((guard (org-match-line "[ \t]*$"))
  16232. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16233. (user-error
  16234. (substitute-command-keys
  16235. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16236. ((or `babel-call `inline-babel-call)
  16237. (let ((info (org-babel-lob-get-info context)))
  16238. (when info (org-babel-execute-src-block nil info))))
  16239. (`clock (org-clock-update-time-maybe))
  16240. (`dynamic-block
  16241. (save-excursion
  16242. (goto-char (org-element-property :post-affiliated context))
  16243. (org-update-dblock)))
  16244. (`footnote-definition
  16245. (goto-char (org-element-property :post-affiliated context))
  16246. (call-interactively 'org-footnote-action))
  16247. (`footnote-reference (call-interactively #'org-footnote-action))
  16248. ((or `headline `inlinetask)
  16249. (save-excursion (goto-char (org-element-property :begin context))
  16250. (call-interactively #'org-set-tags-command)))
  16251. (`item
  16252. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16253. ;; unconditionally, whereas `C-u' will toggle its presence.
  16254. ;; Without a universal argument, if the item has a checkbox,
  16255. ;; toggle it. Otherwise repair the list.
  16256. (let* ((box (org-element-property :checkbox context))
  16257. (struct (org-element-property :structure context))
  16258. (old-struct (copy-tree struct))
  16259. (parents (org-list-parents-alist struct))
  16260. (prevs (org-list-prevs-alist struct))
  16261. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16262. (org-list-set-checkbox
  16263. (org-element-property :begin context) struct
  16264. (cond ((equal arg '(16)) "[-]")
  16265. ((and (not box) (equal arg '(4))) "[ ]")
  16266. ((or (not box) (equal arg '(4))) nil)
  16267. ((eq box 'on) "[ ]")
  16268. (t "[X]")))
  16269. ;; Mimic `org-list-write-struct' but with grabbing a return
  16270. ;; value from `org-list-struct-fix-box'.
  16271. (org-list-struct-fix-ind struct parents 2)
  16272. (org-list-struct-fix-item-end struct)
  16273. (org-list-struct-fix-bul struct prevs)
  16274. (org-list-struct-fix-ind struct parents)
  16275. (let ((block-item
  16276. (org-list-struct-fix-box struct parents prevs orderedp)))
  16277. (if (and box (equal struct old-struct))
  16278. (if (equal arg '(16))
  16279. (message "Checkboxes already reset")
  16280. (user-error "Cannot toggle this checkbox: %s"
  16281. (if (eq box 'on)
  16282. "all subitems checked"
  16283. "unchecked subitems")))
  16284. (org-list-struct-apply-struct struct old-struct)
  16285. (org-update-checkbox-count-maybe))
  16286. (when block-item
  16287. (message "Checkboxes were removed due to empty box at line %d"
  16288. (org-current-line block-item))))))
  16289. (`keyword
  16290. (let ((org-inhibit-startup-visibility-stuff t)
  16291. (org-startup-align-all-tables nil))
  16292. (when (boundp 'org-table-coordinate-overlays)
  16293. (mapc #'delete-overlay org-table-coordinate-overlays)
  16294. (setq org-table-coordinate-overlays nil))
  16295. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16296. (message "Local setup has been refreshed"))
  16297. (`plain-list
  16298. ;; At a plain list, with a double C-u argument, set
  16299. ;; checkboxes of each item to "[-]", whereas a single one
  16300. ;; will toggle their presence according to the state of the
  16301. ;; first item in the list. Without an argument, repair the
  16302. ;; list.
  16303. (let* ((begin (org-element-property :contents-begin context))
  16304. (struct (org-element-property :structure context))
  16305. (old-struct (copy-tree struct))
  16306. (first-box (save-excursion
  16307. (goto-char begin)
  16308. (looking-at org-list-full-item-re)
  16309. (match-string-no-properties 3)))
  16310. (new-box (cond ((equal arg '(16)) "[-]")
  16311. ((equal arg '(4)) (unless first-box "[ ]"))
  16312. ((equal first-box "[X]") "[ ]")
  16313. (t "[X]"))))
  16314. (cond
  16315. (arg
  16316. (dolist (pos
  16317. (org-list-get-all-items
  16318. begin struct (org-list-prevs-alist struct)))
  16319. (org-list-set-checkbox pos struct new-box)))
  16320. ((and first-box (eq (point) begin))
  16321. ;; For convenience, when point is at bol on the first
  16322. ;; item of the list and no argument is provided, simply
  16323. ;; toggle checkbox of that item, if any.
  16324. (org-list-set-checkbox begin struct new-box)))
  16325. (when (equal
  16326. (org-list-write-struct
  16327. struct (org-list-parents-alist struct) old-struct)
  16328. old-struct)
  16329. (message "Cannot update this checkbox"))
  16330. (org-update-checkbox-count-maybe)))
  16331. ((or `property-drawer `node-property)
  16332. (call-interactively #'org-property-action))
  16333. (`radio-target
  16334. (call-interactively #'org-update-radio-target-regexp))
  16335. (`statistics-cookie
  16336. (call-interactively #'org-update-statistics-cookies))
  16337. ((or `table `table-cell `table-row)
  16338. ;; At a table, recalculate every field and align it. Also
  16339. ;; send the table if necessary. If the table has
  16340. ;; a `table.el' type, just give up. At a table row or cell,
  16341. ;; maybe recalculate line but always align table.
  16342. (if (eq (org-element-property :type context) 'table.el)
  16343. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16344. Use `\\[org-edit-special]' to edit table.el tables"))
  16345. (if (or (eq type 'table)
  16346. ;; Check if point is at a TBLFM line.
  16347. (and (eq type 'table-row)
  16348. (= (point) (org-element-property :end context))))
  16349. (save-excursion
  16350. (if (org-at-TBLFM-p)
  16351. (progn (require 'org-table)
  16352. (org-table-calc-current-TBLFM))
  16353. (goto-char (org-element-property :contents-begin context))
  16354. (org-call-with-arg 'org-table-recalculate (or arg t))
  16355. (orgtbl-send-table 'maybe)))
  16356. (org-table-maybe-eval-formula)
  16357. (cond (arg (call-interactively #'org-table-recalculate))
  16358. ((org-table-maybe-recalculate-line))
  16359. (t (org-table-align))))))
  16360. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16361. (org-timestamp-change 0 'day))
  16362. ((and `nil (guard (org-at-heading-p)))
  16363. ;; When point is on an unsupported object type, we can miss
  16364. ;; the fact that it also is at a heading. Handle it here.
  16365. (call-interactively #'org-set-tags-command))
  16366. ((guard
  16367. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16368. (_
  16369. (user-error
  16370. (substitute-command-keys
  16371. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16372. (defun org-mode-restart ()
  16373. (interactive)
  16374. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16375. (funcall major-mode)
  16376. (hack-local-variables)
  16377. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16378. (org-indent-mode -1))
  16379. (org-reset-file-cache))
  16380. (message "%s restarted" major-mode))
  16381. (defun org-flag-above-first-heading (&optional arg)
  16382. "Hide from bob up to the first heading.
  16383. Move point to the beginning of first heading or end of buffer."
  16384. (goto-char (point-min))
  16385. (unless (org-at-heading-p)
  16386. (outline-next-heading))
  16387. (unless (bobp)
  16388. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16389. (defun org-show-branches-buffer ()
  16390. "Show all branches in the buffer."
  16391. (org-flag-above-first-heading)
  16392. (outline-hide-sublevels 1)
  16393. (unless (eobp)
  16394. (outline-show-branches)
  16395. (while (outline-get-next-sibling)
  16396. (outline-show-branches)))
  16397. (goto-char (point-min)))
  16398. (defun org-kill-note-or-show-branches ()
  16399. "Abort storing current note, or show just branches."
  16400. (interactive)
  16401. (if org-finish-function
  16402. (let ((org-note-abort t))
  16403. (funcall org-finish-function))
  16404. (if (org-before-first-heading-p)
  16405. (org-show-branches-buffer)
  16406. (outline-hide-subtree)
  16407. (outline-show-branches))))
  16408. (defun org-delete-indentation (&optional arg)
  16409. "Join current line to previous and fix whitespace at join.
  16410. If previous line is a headline add to headline title. Otherwise
  16411. the function calls `delete-indentation'.
  16412. With a non-nil optional argument, join it to the following one."
  16413. (interactive "*P")
  16414. (if (save-excursion
  16415. (beginning-of-line (if arg 1 0))
  16416. (let ((case-fold-search nil))
  16417. (looking-at org-complex-heading-regexp)))
  16418. ;; At headline.
  16419. (let ((tags-column (when (match-beginning 5)
  16420. (save-excursion (goto-char (match-beginning 5))
  16421. (current-column))))
  16422. (string (concat " " (progn (when arg (forward-line 1))
  16423. (org-trim (delete-and-extract-region
  16424. (line-beginning-position)
  16425. (line-end-position)))))))
  16426. (unless (bobp) (delete-region (point) (1- (point))))
  16427. (goto-char (or (match-end 4)
  16428. (match-beginning 5)
  16429. (match-end 0)))
  16430. (skip-chars-backward " \t")
  16431. (save-excursion (insert string))
  16432. ;; Adjust alignment of tags.
  16433. (cond
  16434. ((not tags-column)) ;no tags
  16435. (org-auto-align-tags (org-align-tags))
  16436. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16437. (delete-indentation arg)))
  16438. (defun org-open-line (n)
  16439. "Insert a new row in tables, call `open-line' elsewhere.
  16440. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16441. As a special case, when a document starts with a table, allow to
  16442. call `open-line' on the very first character."
  16443. (interactive "*p")
  16444. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16445. (org-table-insert-row)
  16446. (open-line n)))
  16447. (defun org-return (&optional indent)
  16448. "Goto next table row or insert a newline.
  16449. Calls `org-table-next-row' or `newline', depending on context.
  16450. When optional INDENT argument is non-nil, call
  16451. `newline-and-indent' instead of `newline'.
  16452. When `org-return-follows-link' is non-nil and point is on
  16453. a timestamp or a link, call `org-open-at-point'. However, it
  16454. will not happen if point is in a table or on a \"dead\"
  16455. object (e.g., within a comment). In these case, you need to use
  16456. `org-open-at-point' directly."
  16457. (interactive)
  16458. (let ((context (if org-return-follows-link (org-element-context)
  16459. (org-element-at-point))))
  16460. (cond
  16461. ;; In a table, call `org-table-next-row'. However, before first
  16462. ;; column or after last one, split the table.
  16463. ((or (and (eq 'table (org-element-type context))
  16464. (not (eq 'table.el (org-element-property :type context)))
  16465. (>= (point) (org-element-property :contents-begin context))
  16466. (< (point) (org-element-property :contents-end context)))
  16467. (org-element-lineage context '(table-row table-cell) t))
  16468. (if (or (looking-at-p "[ \t]*$")
  16469. (save-excursion (skip-chars-backward " \t") (bolp)))
  16470. (insert "\n")
  16471. (org-table-justify-field-maybe)
  16472. (call-interactively #'org-table-next-row)))
  16473. ;; On a link or a timestamp, call `org-open-at-point' if
  16474. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16475. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16476. ((and org-return-follows-link
  16477. (or (and (eq 'link (org-element-type context))
  16478. ;; Ensure point is not on the white spaces after
  16479. ;; the link.
  16480. (let ((origin (point)))
  16481. (org-with-point-at (org-element-property :end context)
  16482. (skip-chars-backward " \t")
  16483. (> (point) origin))))
  16484. (org-in-regexp org-ts-regexp-both nil t)
  16485. (org-in-regexp org-tsr-regexp-both nil t)
  16486. (org-in-regexp org-link-any-re nil t)))
  16487. (call-interactively #'org-open-at-point))
  16488. ;; Insert newline in heading, but preserve tags.
  16489. ((and (not (bolp))
  16490. (let ((case-fold-search nil))
  16491. (org-match-line org-complex-heading-regexp)))
  16492. ;; At headline. Split line. However, if point is on keyword,
  16493. ;; priority cookie or tags, do not break any of them: add
  16494. ;; a newline after the headline instead.
  16495. (let ((tags-column (and (match-beginning 5)
  16496. (save-excursion (goto-char (match-beginning 5))
  16497. (current-column))))
  16498. (string
  16499. (when (and (match-end 4) (org-point-in-group (point) 4))
  16500. (delete-and-extract-region (point) (match-end 4)))))
  16501. ;; Adjust tag alignment.
  16502. (cond
  16503. ((not (and tags-column string)))
  16504. (org-auto-align-tags (org-align-tags))
  16505. (t (org--align-tags-here tags-column))) ;preserve tags column
  16506. (end-of-line)
  16507. (org-show-entry)
  16508. (if indent (newline-and-indent) (newline))
  16509. (when string (save-excursion (insert (org-trim string))))))
  16510. ;; In a list, make sure indenting keeps trailing text within.
  16511. ((and indent
  16512. (not (eolp))
  16513. (org-element-lineage context '(item)))
  16514. (let ((trailing-data
  16515. (delete-and-extract-region (point) (line-end-position))))
  16516. (newline-and-indent)
  16517. (save-excursion (insert trailing-data))))
  16518. (t
  16519. ;; Do not auto-fill when point is in an Org property drawer.
  16520. (let ((auto-fill-function (and (not (org-at-property-p))
  16521. auto-fill-function)))
  16522. (if indent
  16523. (newline-and-indent)
  16524. (newline)))))))
  16525. (defun org-return-indent ()
  16526. "Goto next table row or insert a newline and indent.
  16527. Calls `org-table-next-row' or `newline-and-indent', depending on
  16528. context. See the individual commands for more information."
  16529. (interactive)
  16530. (org-return t))
  16531. (defun org-ctrl-c-tab (&optional arg)
  16532. "Toggle columns width in a table, or show children.
  16533. Call `org-table-toggle-column-width' if point is in a table.
  16534. Otherwise, call `org-show-children'. ARG is the level to hide."
  16535. (interactive "p")
  16536. (if (org-at-table-p)
  16537. (call-interactively #'org-table-toggle-column-width)
  16538. (if (org-before-first-heading-p)
  16539. (progn
  16540. (org-flag-above-first-heading)
  16541. (outline-hide-sublevels (or arg 1))
  16542. (goto-char (point-min)))
  16543. (outline-hide-subtree)
  16544. (org-show-children arg))))
  16545. (defun org-ctrl-c-star ()
  16546. "Compute table, or change heading status of lines.
  16547. Calls `org-table-recalculate' or `org-toggle-heading',
  16548. depending on context."
  16549. (interactive)
  16550. (cond
  16551. ((org-at-table-p)
  16552. (call-interactively 'org-table-recalculate))
  16553. (t
  16554. ;; Convert all lines in region to list items
  16555. (call-interactively 'org-toggle-heading))))
  16556. (defun org-ctrl-c-minus ()
  16557. "Insert separator line in table or modify bullet status of line.
  16558. Also turns a plain line or a region of lines into list items.
  16559. Calls `org-table-insert-hline', `org-toggle-item', or
  16560. `org-cycle-list-bullet', depending on context."
  16561. (interactive)
  16562. (cond
  16563. ((org-at-table-p)
  16564. (call-interactively 'org-table-insert-hline))
  16565. ((org-region-active-p)
  16566. (call-interactively 'org-toggle-item))
  16567. ((org-in-item-p)
  16568. (call-interactively 'org-cycle-list-bullet))
  16569. (t
  16570. (call-interactively 'org-toggle-item))))
  16571. (defun org-toggle-heading (&optional nstars)
  16572. "Convert headings to normal text, or items or text to headings.
  16573. If there is no active region, only convert the current line.
  16574. With a `\\[universal-argument]' prefix, convert the whole list at
  16575. point into heading.
  16576. In a region:
  16577. - If the first non blank line is a headline, remove the stars
  16578. from all headlines in the region.
  16579. - If it is a normal line, turn each and every normal line (i.e.,
  16580. not an heading or an item) in the region into headings. If you
  16581. want to convert only the first line of this region, use one
  16582. universal prefix argument.
  16583. - If it is a plain list item, turn all plain list items into headings.
  16584. When converting a line into a heading, the number of stars is chosen
  16585. such that the lines become children of the current entry. However,
  16586. when a numeric prefix argument is given, its value determines the
  16587. number of stars to add."
  16588. (interactive "P")
  16589. (let ((skip-blanks
  16590. (function
  16591. ;; Return beginning of first non-blank line, starting from
  16592. ;; line at POS.
  16593. (lambda (pos)
  16594. (save-excursion
  16595. (goto-char pos)
  16596. (while (org-at-comment-p) (forward-line))
  16597. (skip-chars-forward " \r\t\n")
  16598. (point-at-bol)))))
  16599. beg end toggled)
  16600. ;; Determine boundaries of changes. If a universal prefix has
  16601. ;; been given, put the list in a region. If region ends at a bol,
  16602. ;; do not consider the last line to be in the region.
  16603. (when (and current-prefix-arg (org-at-item-p))
  16604. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16605. (org-mark-element))
  16606. (if (org-region-active-p)
  16607. (setq beg (funcall skip-blanks (region-beginning))
  16608. end (copy-marker (save-excursion
  16609. (goto-char (region-end))
  16610. (if (bolp) (point) (point-at-eol)))))
  16611. (setq beg (funcall skip-blanks (point-at-bol))
  16612. end (copy-marker (point-at-eol))))
  16613. ;; Ensure inline tasks don't count as headings.
  16614. (org-with-limited-levels
  16615. (save-excursion
  16616. (goto-char beg)
  16617. (cond
  16618. ;; Case 1. Started at an heading: de-star headings.
  16619. ((org-at-heading-p)
  16620. (while (< (point) end)
  16621. (when (org-at-heading-p t)
  16622. (looking-at org-outline-regexp) (replace-match "")
  16623. (setq toggled t))
  16624. (forward-line)))
  16625. ;; Case 2. Started at an item: change items into headlines.
  16626. ;; One star will be added by `org-list-to-subtree'.
  16627. ((org-at-item-p)
  16628. (while (< (point) end)
  16629. (when (org-at-item-p)
  16630. ;; Pay attention to cases when region ends before list.
  16631. (let* ((struct (org-list-struct))
  16632. (list-end
  16633. (min (org-list-get-bottom-point struct) (1+ end))))
  16634. (save-restriction
  16635. (narrow-to-region (point) list-end)
  16636. (insert (org-list-to-subtree
  16637. (org-list-to-lisp t)
  16638. (pcase (org-current-level)
  16639. (`nil 1)
  16640. (l (1+ (org-reduced-level l)))))
  16641. "\n")))
  16642. (setq toggled t))
  16643. (forward-line)))
  16644. ;; Case 3. Started at normal text: make every line an heading,
  16645. ;; skipping headlines and items.
  16646. (t (let* ((stars
  16647. (make-string
  16648. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16649. (add-stars
  16650. (cond (nstars "") ; stars from prefix only
  16651. ((equal stars "") "*") ; before first heading
  16652. (org-odd-levels-only "**") ; inside heading, odd
  16653. (t "*"))) ; inside heading, oddeven
  16654. (rpl (concat stars add-stars " "))
  16655. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16656. (while (< (point) (if (equal nstars '(4)) lend end))
  16657. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16658. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16659. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16660. (forward-line)))))))
  16661. (unless toggled (message "Cannot toggle heading from here"))))
  16662. (defun org-meta-return (&optional arg)
  16663. "Insert a new heading or wrap a region in a table.
  16664. Calls `org-insert-heading', `org-insert-item' or
  16665. `org-table-wrap-region', depending on context. When called with
  16666. an argument, unconditionally call `org-insert-heading'."
  16667. (interactive "P")
  16668. (org-check-before-invisible-edit 'insert)
  16669. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16670. (call-interactively (cond (arg #'org-insert-heading)
  16671. ((org-at-table-p) #'org-table-wrap-region)
  16672. ((org-in-item-p) #'org-insert-item)
  16673. (t #'org-insert-heading)))))
  16674. ;;; Menu entries
  16675. (defsubst org-in-subtree-not-table-p ()
  16676. "Are we in a subtree and not in a table?"
  16677. (and (not (org-before-first-heading-p))
  16678. (not (org-at-table-p))))
  16679. ;; Define the Org mode menus
  16680. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  16681. '("Tbl"
  16682. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16683. ["Next Field" org-cycle (org-at-table-p)]
  16684. ["Previous Field" org-shifttab (org-at-table-p)]
  16685. ["Next Row" org-return (org-at-table-p)]
  16686. "--"
  16687. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16688. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16689. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16690. "--"
  16691. ("Column"
  16692. ["Move Column Left" org-metaleft (org-at-table-p)]
  16693. ["Move Column Right" org-metaright (org-at-table-p)]
  16694. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16695. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16696. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16697. ("Row"
  16698. ["Move Row Up" org-metaup (org-at-table-p)]
  16699. ["Move Row Down" org-metadown (org-at-table-p)]
  16700. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16701. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16702. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16703. "--"
  16704. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16705. ("Rectangle"
  16706. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16707. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16708. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16709. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16710. "--"
  16711. ("Calculate"
  16712. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16713. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16714. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16715. "--"
  16716. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16717. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16718. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16719. "--"
  16720. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16721. "--"
  16722. ["Sum Column/Rectangle" org-table-sum
  16723. (or (org-at-table-p) (org-region-active-p))]
  16724. ["Which Column?" org-table-current-column (org-at-table-p)])
  16725. ["Debug Formulas"
  16726. org-table-toggle-formula-debugger
  16727. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16728. ["Show Col/Row Numbers"
  16729. org-table-toggle-coordinate-overlays
  16730. :style toggle
  16731. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16732. "--"
  16733. ["Create" org-table-create (not (org-at-table-p))]
  16734. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16735. ["Import from File" org-table-import (not (org-at-table-p))]
  16736. ["Export to File" org-table-export (org-at-table-p)]
  16737. "--"
  16738. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16739. "--"
  16740. ("Plot"
  16741. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16742. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16743. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16744. '("Org"
  16745. ("Show/Hide"
  16746. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16747. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16748. ["Sparse Tree..." org-sparse-tree t]
  16749. ["Reveal Context" org-reveal t]
  16750. ["Show All" org-show-all t]
  16751. "--"
  16752. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16753. "--"
  16754. ["New Heading" org-insert-heading t]
  16755. ("Navigate Headings"
  16756. ["Up" outline-up-heading t]
  16757. ["Next" outline-next-visible-heading t]
  16758. ["Previous" outline-previous-visible-heading t]
  16759. ["Next Same Level" outline-forward-same-level t]
  16760. ["Previous Same Level" outline-backward-same-level t]
  16761. "--"
  16762. ["Jump" org-goto t])
  16763. ("Edit Structure"
  16764. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16765. "--"
  16766. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16767. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16768. "--"
  16769. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16770. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16771. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16772. "--"
  16773. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16774. "--"
  16775. ["Copy visible text" org-copy-visible t]
  16776. "--"
  16777. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16778. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16779. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16780. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16781. "--"
  16782. ["Sort Region/Children" org-sort t]
  16783. "--"
  16784. ["Convert to odd levels" org-convert-to-odd-levels t]
  16785. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16786. ("Editing"
  16787. ["Emphasis..." org-emphasize t]
  16788. ["Edit Source Example" org-edit-special t]
  16789. "--"
  16790. ["Footnote new/jump" org-footnote-action t]
  16791. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16792. ("Archive"
  16793. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16794. "--"
  16795. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16796. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16797. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16798. )
  16799. "--"
  16800. ("Hyperlinks"
  16801. ["Store Link (Global)" org-store-link t]
  16802. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16803. ["Insert Link" org-insert-link t]
  16804. ["Follow Link" org-open-at-point t]
  16805. "--"
  16806. ["Next link" org-next-link t]
  16807. ["Previous link" org-previous-link t]
  16808. "--"
  16809. ["Descriptive Links"
  16810. org-toggle-link-display
  16811. :style radio
  16812. :selected org-descriptive-links
  16813. ]
  16814. ["Literal Links"
  16815. org-toggle-link-display
  16816. :style radio
  16817. :selected (not org-descriptive-links)])
  16818. "--"
  16819. ("TODO Lists"
  16820. ["TODO/DONE/-" org-todo t]
  16821. ("Select keyword"
  16822. ["Next keyword" org-shiftright (org-at-heading-p)]
  16823. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16824. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16825. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16826. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16827. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16828. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16829. "--"
  16830. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16831. :selected org-enforce-todo-dependencies :style toggle :active t]
  16832. "Settings for tree at point"
  16833. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16834. :selected (org-entry-get nil "ORDERED")
  16835. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16836. ["Do Children parallel" org-toggle-ordered-property :style radio
  16837. :selected (not (org-entry-get nil "ORDERED"))
  16838. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16839. "--"
  16840. ["Set Priority" org-priority t]
  16841. ["Priority Up" org-shiftup t]
  16842. ["Priority Down" org-shiftdown t]
  16843. "--"
  16844. ["Get news from all feeds" org-feed-update-all t]
  16845. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16846. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16847. ("TAGS and Properties"
  16848. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16849. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16850. "--"
  16851. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16852. ["Column view of properties" org-columns t]
  16853. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16854. ("Dates and Scheduling"
  16855. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16856. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16857. ("Change Date"
  16858. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16859. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16860. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16861. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16862. ["Compute Time Range" org-evaluate-time-range t]
  16863. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16864. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16865. "--"
  16866. ["Custom time format" org-toggle-time-stamp-overlays
  16867. :style radio :selected org-display-custom-times]
  16868. "--"
  16869. ["Goto Calendar" org-goto-calendar t]
  16870. ["Date from Calendar" org-date-from-calendar t]
  16871. "--"
  16872. ["Start/Restart Timer" org-timer-start t]
  16873. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16874. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16875. ["Insert Timer String" org-timer t]
  16876. ["Insert Timer Item" org-timer-item t])
  16877. ("Logging work"
  16878. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16879. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16880. ["Clock out" org-clock-out t]
  16881. ["Clock cancel" org-clock-cancel t]
  16882. "--"
  16883. ["Mark as default task" org-clock-mark-default-task t]
  16884. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16885. ["Goto running clock" org-clock-goto t]
  16886. "--"
  16887. ["Display times" org-clock-display t]
  16888. ["Create clock table" org-clock-report t]
  16889. "--"
  16890. ["Record DONE time"
  16891. (progn (setq org-log-done (not org-log-done))
  16892. (message "Switching to %s will %s record a timestamp"
  16893. (car org-done-keywords)
  16894. (if org-log-done "automatically" "not")))
  16895. :style toggle :selected org-log-done])
  16896. "--"
  16897. ["Agenda Command..." org-agenda t]
  16898. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16899. ("File List for Agenda")
  16900. ("Special views current file"
  16901. ["TODO Tree" org-show-todo-tree t]
  16902. ["Check Deadlines" org-check-deadlines t]
  16903. ["Tags/Property tree" org-match-sparse-tree t])
  16904. "--"
  16905. ["Export/Publish..." org-export-dispatch t]
  16906. ("LaTeX"
  16907. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16908. :style toggle :selected org-cdlatex-mode]
  16909. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16910. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16911. ["Modify math symbol" org-cdlatex-math-modify
  16912. (org-inside-LaTeX-fragment-p)]
  16913. ["Insert citation" org-reftex-citation t])
  16914. "--"
  16915. ("MobileOrg"
  16916. ["Push Files and Views" org-mobile-push t]
  16917. ["Get Captured and Flagged" org-mobile-pull t]
  16918. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  16919. "--"
  16920. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  16921. "--"
  16922. ("Documentation"
  16923. ["Show Version" org-version t]
  16924. ["Info Documentation" org-info t]
  16925. ["Browse Org News" org-browse-news t])
  16926. ("Customize"
  16927. ["Browse Org Group" org-customize t]
  16928. "--"
  16929. ["Expand This Menu" org-create-customize-menu
  16930. (fboundp 'customize-menu-create)])
  16931. ["Send bug report" org-submit-bug-report t]
  16932. "--"
  16933. ("Refresh/Reload"
  16934. ["Refresh setup current buffer" org-mode-restart t]
  16935. ["Reload Org (after update)" org-reload t]
  16936. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16937. (defun org-info (&optional node)
  16938. "Read documentation for Org in the info system.
  16939. With optional NODE, go directly to that node."
  16940. (interactive)
  16941. (info (format "(org)%s" (or node ""))))
  16942. (defun org-browse-news ()
  16943. "Browse the news for the latest major release."
  16944. (interactive)
  16945. (browse-url "https://orgmode.org/Changes.html"))
  16946. ;;;###autoload
  16947. (defun org-submit-bug-report ()
  16948. "Submit a bug report on Org via mail.
  16949. Don't hesitate to report any problems or inaccurate documentation.
  16950. If you don't have setup sending mail from (X)Emacs, please copy the
  16951. output buffer into your mail program, as it gives us important
  16952. information about your Org version and configuration."
  16953. (interactive)
  16954. (require 'reporter)
  16955. (defvar reporter-prompt-for-summary-p)
  16956. (org-load-modules-maybe)
  16957. (org-require-autoloaded-modules)
  16958. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16959. (reporter-submit-bug-report
  16960. "emacs-orgmode@gnu.org"
  16961. (org-version nil 'full)
  16962. (let (list)
  16963. (save-window-excursion
  16964. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16965. (delete-other-windows)
  16966. (erase-buffer)
  16967. (insert "You are about to submit a bug report to the Org mailing list.
  16968. We would like to add your full Org and Outline configuration to the
  16969. bug report. This greatly simplifies the work of the maintainer and
  16970. other experts on the mailing list.
  16971. HOWEVER, some variables you have customized may contain private
  16972. information. The names of customers, colleagues, or friends, might
  16973. appear in the form of file names, tags, todo states, or search strings.
  16974. If you answer yes to the prompt, you might want to check and remove
  16975. such private information before sending the email.")
  16976. (add-text-properties (point-min) (point-max) '(face org-warning))
  16977. (when (yes-or-no-p "Include your Org configuration ")
  16978. (mapatoms
  16979. (lambda (v)
  16980. (and (boundp v)
  16981. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16982. (or (and (symbol-value v)
  16983. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16984. (and
  16985. (get v 'custom-type) (get v 'standard-value)
  16986. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16987. (push v list)))))
  16988. (kill-buffer (get-buffer "*Warn about privacy*"))
  16989. list))
  16990. nil nil
  16991. "Remember to cover the basics, that is, what you expected to happen and
  16992. what in fact did happen. You don't know how to make a good report? See
  16993. https://orgmode.org/manual/Feedback.html#Feedback
  16994. Your bug report will be posted to the Org mailing list.
  16995. ------------------------------------------------------------------------")
  16996. (save-excursion
  16997. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16998. (replace-match "\\1Bug: \\3 [\\2]")))))
  16999. (defun org-install-agenda-files-menu ()
  17000. (let ((bl (buffer-list)))
  17001. (save-excursion
  17002. (while bl
  17003. (set-buffer (pop bl))
  17004. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17005. (when (derived-mode-p 'org-mode)
  17006. (easy-menu-change
  17007. '("Org") "File List for Agenda"
  17008. (append
  17009. (list
  17010. ["Edit File List" (org-edit-agenda-file-list) t]
  17011. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17012. ["Remove Current File from List" org-remove-file t]
  17013. ["Cycle through agenda files" org-cycle-agenda-files t]
  17014. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17015. "--")
  17016. (mapcar 'org-file-menu-entry
  17017. ;; Prevent initialization from failing.
  17018. (ignore-errors (org-agenda-files t)))))))))
  17019. ;;;; Documentation
  17020. (defun org-require-autoloaded-modules ()
  17021. (interactive)
  17022. (mapc #'require
  17023. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17024. org-table org-timer)))
  17025. ;;;###autoload
  17026. (defun org-reload (&optional uncompiled)
  17027. "Reload all Org Lisp files.
  17028. With prefix arg UNCOMPILED, load the uncompiled versions."
  17029. (interactive "P")
  17030. (require 'loadhist)
  17031. (let* ((org-dir (org-find-library-dir "org"))
  17032. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17033. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17034. (remove-re (format "\\`%s\\'"
  17035. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17036. (feats (delete-dups
  17037. (mapcar 'file-name-sans-extension
  17038. (mapcar 'file-name-nondirectory
  17039. (delq nil
  17040. (mapcar 'feature-file
  17041. features))))))
  17042. (lfeat (append
  17043. (sort
  17044. (setq feats
  17045. (delq nil (mapcar
  17046. (lambda (f)
  17047. (if (and (string-match feature-re f)
  17048. (not (string-match remove-re f)))
  17049. f nil))
  17050. feats)))
  17051. 'string-lessp)
  17052. (list "org-version" "org")))
  17053. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17054. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17055. load-uncore load-misses)
  17056. (setq load-misses
  17057. (delq 't
  17058. (mapcar (lambda (f)
  17059. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17060. (and (string= org-dir contrib-dir)
  17061. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17062. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17063. (add-to-list 'load-uncore f 'append)
  17064. 't)
  17065. f))
  17066. lfeat)))
  17067. (when load-uncore
  17068. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17069. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  17070. (if load-misses
  17071. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17072. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17073. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17074. ;;;###autoload
  17075. (defun org-customize ()
  17076. "Call the customize function with org as argument."
  17077. (interactive)
  17078. (org-load-modules-maybe)
  17079. (org-require-autoloaded-modules)
  17080. (customize-browse 'org))
  17081. (defun org-create-customize-menu ()
  17082. "Create a full customization menu for Org mode, insert it into the menu."
  17083. (interactive)
  17084. (org-load-modules-maybe)
  17085. (org-require-autoloaded-modules)
  17086. (if (fboundp 'customize-menu-create)
  17087. (progn
  17088. (easy-menu-change
  17089. '("Org") "Customize"
  17090. `(["Browse Org group" org-customize t]
  17091. "--"
  17092. ,(customize-menu-create 'org)
  17093. ["Set" Custom-set t]
  17094. ["Save" Custom-save t]
  17095. ["Reset to Current" Custom-reset-current t]
  17096. ["Reset to Saved" Custom-reset-saved t]
  17097. ["Reset to Standard Settings" Custom-reset-standard t]))
  17098. (message "\"Org\"-menu now contains full customization menu"))
  17099. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17100. ;;;; Miscellaneous stuff
  17101. ;;; Generally useful functions
  17102. (defun org-in-clocktable-p ()
  17103. "Check if the cursor is in a clocktable."
  17104. (let ((pos (point)) start)
  17105. (save-excursion
  17106. (end-of-line 1)
  17107. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17108. (setq start (match-beginning 0))
  17109. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17110. (>= (match-end 0) pos)
  17111. start))))
  17112. (defun org-in-verbatim-emphasis ()
  17113. (save-match-data
  17114. (and (org-in-regexp org-verbatim-re 2)
  17115. (>= (point) (match-beginning 3))
  17116. (<= (point) (match-end 4)))))
  17117. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17118. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17119. (if (and marker (marker-buffer marker)
  17120. (buffer-live-p (marker-buffer marker)))
  17121. (progn
  17122. (pop-to-buffer-same-window (marker-buffer marker))
  17123. (when (or (> marker (point-max)) (< marker (point-min)))
  17124. (widen))
  17125. (goto-char marker)
  17126. (org-show-context 'org-goto))
  17127. (if bookmark
  17128. (bookmark-jump bookmark)
  17129. (error "Cannot find location"))))
  17130. (defun org-quote-csv-field (s)
  17131. "Quote field for inclusion in CSV material."
  17132. (if (string-match "[\",]" s)
  17133. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17134. s))
  17135. (defun org-force-self-insert (N)
  17136. "Needed to enforce self-insert under remapping."
  17137. (interactive "p")
  17138. (self-insert-command N))
  17139. (defun org-quote-vert (s)
  17140. "Replace \"|\" with \"\\vert\"."
  17141. (while (string-match "|" s)
  17142. (setq s (replace-match "\\vert" t t s)))
  17143. s)
  17144. (defun org-uuidgen-p (s)
  17145. "Is S an ID created by UUIDGEN?"
  17146. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17147. (defun org-in-src-block-p (&optional inside)
  17148. "Whether point is in a code source block.
  17149. When INSIDE is non-nil, don't consider we are within a source
  17150. block when point is at #+BEGIN_SRC or #+END_SRC."
  17151. (let ((case-fold-search t))
  17152. (or (and (eq (get-char-property (point) 'src-block) t))
  17153. (and (not inside)
  17154. (save-match-data
  17155. (save-excursion
  17156. (beginning-of-line)
  17157. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17158. (defun org-context ()
  17159. "Return a list of contexts of the current cursor position.
  17160. If several contexts apply, all are returned.
  17161. Each context entry is a list with a symbol naming the context, and
  17162. two positions indicating start and end of the context. Possible
  17163. contexts are:
  17164. :headline anywhere in a headline
  17165. :headline-stars on the leading stars in a headline
  17166. :todo-keyword on a TODO keyword (including DONE) in a headline
  17167. :tags on the TAGS in a headline
  17168. :priority on the priority cookie in a headline
  17169. :item on the first line of a plain list item
  17170. :item-bullet on the bullet/number of a plain list item
  17171. :checkbox on the checkbox in a plain list item
  17172. :table in an Org table
  17173. :table-special on a special filed in a table
  17174. :table-table in a table.el table
  17175. :clocktable in a clocktable
  17176. :src-block in a source block
  17177. :link on a hyperlink
  17178. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17179. :latex-fragment on a LaTeX fragment
  17180. :latex-preview on a LaTeX fragment with overlaid preview image
  17181. This function expects the position to be visible because it uses font-lock
  17182. faces as a help to recognize the following contexts: :table-special, :link,
  17183. and :keyword."
  17184. (let* ((f (get-text-property (point) 'face))
  17185. (faces (if (listp f) f (list f)))
  17186. (case-fold-search t)
  17187. (p (point)) clist o)
  17188. ;; First the large context
  17189. (cond
  17190. ((org-at-heading-p t)
  17191. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17192. (when (progn
  17193. (beginning-of-line 1)
  17194. (looking-at org-todo-line-tags-regexp))
  17195. (push (org-point-in-group p 1 :headline-stars) clist)
  17196. (push (org-point-in-group p 2 :todo-keyword) clist)
  17197. (push (org-point-in-group p 4 :tags) clist))
  17198. (goto-char p)
  17199. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17200. (when (looking-at "\\[#[A-Z0-9]\\]")
  17201. (push (org-point-in-group p 0 :priority) clist)))
  17202. ((org-at-item-p)
  17203. (push (org-point-in-group p 2 :item-bullet) clist)
  17204. (push (list :item (point-at-bol)
  17205. (save-excursion (org-end-of-item) (point)))
  17206. clist)
  17207. (and (org-at-item-checkbox-p)
  17208. (push (org-point-in-group p 0 :checkbox) clist)))
  17209. ((org-at-table-p)
  17210. (push (list :table (org-table-begin) (org-table-end)) clist)
  17211. (when (memq 'org-formula faces)
  17212. (push (list :table-special
  17213. (previous-single-property-change p 'face)
  17214. (next-single-property-change p 'face)) clist)))
  17215. ((org-at-table-p 'any)
  17216. (push (list :table-table) clist)))
  17217. (goto-char p)
  17218. (let ((case-fold-search t))
  17219. ;; New the "medium" contexts: clocktables, source blocks
  17220. (cond ((org-in-clocktable-p)
  17221. (push (list :clocktable
  17222. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17223. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17224. (match-beginning 1))
  17225. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17226. (match-end 0))) clist))
  17227. ((org-in-src-block-p)
  17228. (push (list :src-block
  17229. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17230. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17231. (match-beginning 1))
  17232. (and (search-forward "#+END_SRC" nil t)
  17233. (match-beginning 0))) clist))))
  17234. (goto-char p)
  17235. ;; Now the small context
  17236. (cond
  17237. ((org-at-timestamp-p)
  17238. (push (org-point-in-group p 0 :timestamp) clist))
  17239. ((memq 'org-link faces)
  17240. (push (list :link
  17241. (previous-single-property-change p 'face)
  17242. (next-single-property-change p 'face)) clist))
  17243. ((memq 'org-special-keyword faces)
  17244. (push (list :keyword
  17245. (previous-single-property-change p 'face)
  17246. (next-single-property-change p 'face)) clist))
  17247. ((setq o (cl-some
  17248. (lambda (o)
  17249. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17250. o))
  17251. (overlays-at (point))))
  17252. (push (list :latex-fragment
  17253. (overlay-start o) (overlay-end o)) clist)
  17254. (push (list :latex-preview
  17255. (overlay-start o) (overlay-end o)) clist))
  17256. ((org-inside-LaTeX-fragment-p)
  17257. ;; FIXME: positions wrong.
  17258. (push (list :latex-fragment (point) (point)) clist)))
  17259. (setq clist (nreverse (delq nil clist)))
  17260. clist))
  17261. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17262. "Non-nil when point is between matches of START-RE and END-RE.
  17263. Also return a non-nil value when point is on one of the matches.
  17264. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17265. buffer positions. Default values are the positions of headlines
  17266. surrounding the point.
  17267. The functions returns a cons cell whose car (resp. cdr) is the
  17268. position before START-RE (resp. after END-RE)."
  17269. (save-match-data
  17270. (let ((pos (point))
  17271. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17272. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17273. beg end)
  17274. (save-excursion
  17275. ;; Point is on a block when on START-RE or if START-RE can be
  17276. ;; found before it...
  17277. (and (or (org-in-regexp start-re)
  17278. (re-search-backward start-re limit-up t))
  17279. (setq beg (match-beginning 0))
  17280. ;; ... and END-RE after it...
  17281. (goto-char (match-end 0))
  17282. (re-search-forward end-re limit-down t)
  17283. (> (setq end (match-end 0)) pos)
  17284. ;; ... without another START-RE in-between.
  17285. (goto-char (match-beginning 0))
  17286. (not (re-search-backward start-re (1+ beg) t))
  17287. ;; Return value.
  17288. (cons beg end))))))
  17289. (defun org-in-block-p (names)
  17290. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17291. NAMES is a list of strings containing names of blocks.
  17292. Return first block name matched, or nil. Beware that in case of
  17293. nested blocks, the returned name may not belong to the closest
  17294. block from point."
  17295. (save-match-data
  17296. (catch 'exit
  17297. (let ((case-fold-search t)
  17298. (lim-up (save-excursion (outline-previous-heading)))
  17299. (lim-down (save-excursion (outline-next-heading))))
  17300. (dolist (name names)
  17301. (let ((n (regexp-quote name)))
  17302. (when (org-between-regexps-p
  17303. (concat "^[ \t]*#\\+begin_" n)
  17304. (concat "^[ \t]*#\\+end_" n)
  17305. lim-up lim-down)
  17306. (throw 'exit n)))))
  17307. nil)))
  17308. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17309. "Call `multi-occur' with buffers for all agenda files."
  17310. (interactive "sOrg-files matching: ")
  17311. (let* ((files (org-agenda-files))
  17312. (tnames (mapcar #'file-truename files))
  17313. (extra org-agenda-text-search-extra-files))
  17314. (when (eq (car extra) 'agenda-archives)
  17315. (setq extra (cdr extra))
  17316. (setq files (org-add-archive-files files)))
  17317. (dolist (f extra)
  17318. (unless (member (file-truename f) tnames)
  17319. (unless (member f files) (setq files (append files (list f))))
  17320. (setq tnames (append tnames (list (file-truename f))))))
  17321. (multi-occur
  17322. (mapcar (lambda (x)
  17323. (with-current-buffer
  17324. ;; FIXME: Why not just (find-file-noselect x)?
  17325. ;; Is it to avoid the "revert buffer" prompt?
  17326. (or (get-file-buffer x) (find-file-noselect x))
  17327. (widen)
  17328. (current-buffer)))
  17329. files)
  17330. regexp)))
  17331. (add-hook 'occur-mode-find-occurrence-hook
  17332. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17333. (defun org-occur-link-in-agenda-files ()
  17334. "Create a link and search for it in the agendas.
  17335. The link is not stored in `org-stored-links', it is just created
  17336. for the search purpose."
  17337. (interactive)
  17338. (let ((link (condition-case nil
  17339. (org-store-link nil)
  17340. (error "Unable to create a link to here"))))
  17341. (org-occur-in-agenda-files (regexp-quote link))))
  17342. (defun org-back-over-empty-lines ()
  17343. "Move backwards over whitespace, to the beginning of the first empty line.
  17344. Returns the number of empty lines passed."
  17345. (let ((pos (point)))
  17346. (if (cdr (assq 'heading org-blank-before-new-entry))
  17347. (skip-chars-backward " \t\n\r")
  17348. (unless (eobp)
  17349. (forward-line -1)))
  17350. (beginning-of-line 2)
  17351. (goto-char (min (point) pos))
  17352. (count-lines (point) pos)))
  17353. ;;; TODO: Only called once, from ox-odt which should probably use
  17354. ;;; org-export-inline-image-p or something.
  17355. (defun org-file-image-p (file)
  17356. "Return non-nil if FILE is an image."
  17357. (save-match-data
  17358. (string-match (image-file-name-regexp) file)))
  17359. (defun org-get-cursor-date (&optional with-time)
  17360. "Return the date at cursor in as a time.
  17361. This works in the calendar and in the agenda, anywhere else it just
  17362. returns the current time.
  17363. If WITH-TIME is non-nil, returns the time of the event at point (in
  17364. the agenda) or the current time of the day; otherwise returns the
  17365. earliest time on the cursor date that Org treats as that date
  17366. (bearing in mind `org-extend-today-until')."
  17367. (let (date day defd tp hod mod)
  17368. (when with-time
  17369. (setq tp (get-text-property (point) 'time))
  17370. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17371. (setq hod (string-to-number (match-string 1 tp))
  17372. mod (string-to-number (match-string 2 tp))))
  17373. (or tp (let ((now (decode-time)))
  17374. (setq hod (nth 2 now)
  17375. mod (nth 1 now)))))
  17376. (cond
  17377. ((eq major-mode 'calendar-mode)
  17378. (setq date (calendar-cursor-to-date)
  17379. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17380. (nth 1 date) (nth 0 date) (nth 2 date))))
  17381. ((eq major-mode 'org-agenda-mode)
  17382. (setq day (get-text-property (point) 'day))
  17383. (when day
  17384. (setq date (calendar-gregorian-from-absolute day)
  17385. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17386. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17387. (or defd (current-time))))
  17388. (defun org-mark-subtree (&optional up)
  17389. "Mark the current subtree.
  17390. This puts point at the start of the current subtree, and mark at
  17391. the end. If a numeric prefix UP is given, move up into the
  17392. hierarchy of headlines by UP levels before marking the subtree."
  17393. (interactive "P")
  17394. (org-with-limited-levels
  17395. (cond ((org-at-heading-p) (beginning-of-line))
  17396. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17397. (t (outline-previous-visible-heading 1))))
  17398. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17399. (if (called-interactively-p 'any)
  17400. (call-interactively 'org-mark-element)
  17401. (org-mark-element)))
  17402. ;;; Indentation
  17403. (defvar org-element-greater-elements)
  17404. (defun org--get-expected-indentation (element contentsp)
  17405. "Expected indentation column for current line, according to ELEMENT.
  17406. ELEMENT is an element containing point. CONTENTSP is non-nil
  17407. when indentation is to be computed according to contents of
  17408. ELEMENT."
  17409. (let ((type (org-element-type element))
  17410. (start (org-element-property :begin element))
  17411. (post-affiliated (org-element-property :post-affiliated element)))
  17412. (org-with-wide-buffer
  17413. (cond
  17414. (contentsp
  17415. (cl-case type
  17416. ((diary-sexp footnote-definition) 0)
  17417. ((headline inlinetask nil)
  17418. (if (not org-adapt-indentation) 0
  17419. (let ((level (org-current-level)))
  17420. (if level (1+ level) 0))))
  17421. ((item plain-list) (org-list-item-body-column post-affiliated))
  17422. (t
  17423. (goto-char start)
  17424. (current-indentation))))
  17425. ((memq type '(headline inlinetask nil))
  17426. (if (org-match-line "[ \t]*$")
  17427. (org--get-expected-indentation element t)
  17428. 0))
  17429. ((memq type '(diary-sexp footnote-definition)) 0)
  17430. ;; First paragraph of a footnote definition or an item.
  17431. ;; Indent like parent.
  17432. ((< (line-beginning-position) start)
  17433. (org--get-expected-indentation
  17434. (org-element-property :parent element) t))
  17435. ;; At first line: indent according to previous sibling, if any,
  17436. ;; ignoring footnote definitions and inline tasks, or parent's
  17437. ;; contents.
  17438. ((= (line-beginning-position) start)
  17439. (catch 'exit
  17440. (while t
  17441. (if (= (point-min) start) (throw 'exit 0)
  17442. (goto-char (1- start))
  17443. (let* ((previous (org-element-at-point))
  17444. (parent previous))
  17445. (while (and parent (<= (org-element-property :end parent) start))
  17446. (setq previous parent
  17447. parent (org-element-property :parent parent)))
  17448. (cond
  17449. ((not previous) (throw 'exit 0))
  17450. ((> (org-element-property :end previous) start)
  17451. (throw 'exit (org--get-expected-indentation previous t)))
  17452. ((memq (org-element-type previous)
  17453. '(footnote-definition inlinetask))
  17454. (setq start (org-element-property :begin previous)))
  17455. (t (goto-char (org-element-property :begin previous))
  17456. (throw 'exit
  17457. (if (bolp) (current-indentation)
  17458. ;; At first paragraph in an item or
  17459. ;; a footnote definition.
  17460. (org--get-expected-indentation
  17461. (org-element-property :parent previous) t))))))))))
  17462. ;; Otherwise, move to the first non-blank line above.
  17463. (t
  17464. (beginning-of-line)
  17465. (let ((pos (point)))
  17466. (skip-chars-backward " \r\t\n")
  17467. (cond
  17468. ;; Two blank lines end a footnote definition or a plain
  17469. ;; list. When we indent an empty line after them, the
  17470. ;; containing list or footnote definition is over, so it
  17471. ;; qualifies as a previous sibling. Therefore, we indent
  17472. ;; like its first line.
  17473. ((and (memq type '(footnote-definition plain-list))
  17474. (> (count-lines (point) pos) 2))
  17475. (goto-char start)
  17476. (current-indentation))
  17477. ;; Line above is the first one of a paragraph at the
  17478. ;; beginning of an item or a footnote definition. Indent
  17479. ;; like parent.
  17480. ((< (line-beginning-position) start)
  17481. (org--get-expected-indentation
  17482. (org-element-property :parent element) t))
  17483. ;; Line above is the beginning of an element, i.e., point
  17484. ;; was originally on the blank lines between element's start
  17485. ;; and contents.
  17486. ((= (line-beginning-position) post-affiliated)
  17487. (org--get-expected-indentation element t))
  17488. ;; POS is after contents in a greater element. Indent like
  17489. ;; the beginning of the element.
  17490. ((and (memq type org-element-greater-elements)
  17491. (let ((cend (org-element-property :contents-end element)))
  17492. (and cend (<= cend pos))))
  17493. ;; As a special case, if point is at the end of a footnote
  17494. ;; definition or an item, indent like the very last element
  17495. ;; within. If that last element is an item, indent like
  17496. ;; its contents.
  17497. (if (memq type '(footnote-definition item plain-list))
  17498. (let ((last (org-element-at-point)))
  17499. (goto-char pos)
  17500. (org--get-expected-indentation
  17501. last (eq (org-element-type last) 'item)))
  17502. (goto-char start)
  17503. (current-indentation)))
  17504. ;; In any other case, indent like the current line.
  17505. (t (current-indentation)))))))))
  17506. (defun org--align-node-property ()
  17507. "Align node property at point.
  17508. Alignment is done according to `org-property-format', which see."
  17509. (when (save-excursion
  17510. (beginning-of-line)
  17511. (looking-at org-property-re))
  17512. (replace-match
  17513. (concat (match-string 4)
  17514. (org-trim
  17515. (format org-property-format (match-string 1) (match-string 3))))
  17516. t t)))
  17517. (defun org-indent-line ()
  17518. "Indent line depending on context.
  17519. Indentation is done according to the following rules:
  17520. - Footnote definitions, diary sexps, headlines and inline tasks
  17521. have to start at column 0.
  17522. - On the very first line of an element, consider, in order, the
  17523. next rules until one matches:
  17524. 1. If there's a sibling element before, ignoring footnote
  17525. definitions and inline tasks, indent like its first line.
  17526. 2. If element has a parent, indent like its contents. More
  17527. precisely, if parent is an item, indent after the bullet.
  17528. Else, indent like parent's first line.
  17529. 3. Otherwise, indent relatively to current level, if
  17530. `org-adapt-indentation' is non-nil, or to left margin.
  17531. - On a blank line at the end of an element, indent according to
  17532. the type of the element. More precisely
  17533. 1. If element is a plain list, an item, or a footnote
  17534. definition, indent like the very last element within.
  17535. 2. If element is a paragraph, indent like its last non blank
  17536. line.
  17537. 3. Otherwise, indent like its very first line.
  17538. - In the code part of a source block, use language major mode
  17539. to indent current line if `org-src-tab-acts-natively' is
  17540. non-nil. If it is nil, do nothing.
  17541. - Otherwise, indent like the first non-blank line above.
  17542. The function doesn't indent an item as it could break the whole
  17543. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17544. `\\[org-shiftmetaright]'.
  17545. Also align node properties according to `org-property-format'."
  17546. (interactive)
  17547. (cond
  17548. ((org-at-heading-p) 'noindent)
  17549. (t
  17550. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17551. (type (org-element-type element)))
  17552. (cond ((and (memq type '(plain-list item))
  17553. (= (line-beginning-position)
  17554. (org-element-property :post-affiliated element)))
  17555. 'noindent)
  17556. ((and (eq type 'latex-environment)
  17557. (>= (point) (org-element-property :post-affiliated element))
  17558. (< (point) (org-with-wide-buffer
  17559. (goto-char (org-element-property :end element))
  17560. (skip-chars-backward " \r\t\n")
  17561. (line-beginning-position 2))))
  17562. 'noindent)
  17563. ((and (eq type 'src-block)
  17564. org-src-tab-acts-natively
  17565. (> (line-beginning-position)
  17566. (org-element-property :post-affiliated element))
  17567. (< (line-beginning-position)
  17568. (org-with-wide-buffer
  17569. (goto-char (org-element-property :end element))
  17570. (skip-chars-backward " \r\t\n")
  17571. (line-beginning-position))))
  17572. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17573. (t
  17574. (let ((column (org--get-expected-indentation element nil)))
  17575. ;; Preserve current column.
  17576. (if (<= (current-column) (current-indentation))
  17577. (indent-line-to column)
  17578. (save-excursion (indent-line-to column))))
  17579. ;; Align node property. Also preserve current column.
  17580. (when (eq type 'node-property)
  17581. (let ((column (current-column)))
  17582. (org--align-node-property)
  17583. (org-move-to-column column)))))))))
  17584. (defun org-indent-region (start end)
  17585. "Indent each non-blank line in the region.
  17586. Called from a program, START and END specify the region to
  17587. indent. The function will not indent contents of example blocks,
  17588. verse blocks and export blocks as leading white spaces are
  17589. assumed to be significant there."
  17590. (interactive "r")
  17591. (save-excursion
  17592. (goto-char start)
  17593. (skip-chars-forward " \r\t\n")
  17594. (unless (eobp) (beginning-of-line))
  17595. (let ((indent-to
  17596. (lambda (ind pos)
  17597. ;; Set IND as indentation for all lines between point and
  17598. ;; POS. Blank lines are ignored. Leave point after POS
  17599. ;; once done.
  17600. (let ((limit (copy-marker pos)))
  17601. (while (< (point) limit)
  17602. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17603. (forward-line))
  17604. (set-marker limit nil))))
  17605. (end (copy-marker end)))
  17606. (while (< (point) end)
  17607. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17608. (let* ((element (org-element-at-point))
  17609. (type (org-element-type element))
  17610. (element-end (copy-marker (org-element-property :end element)))
  17611. (ind (org--get-expected-indentation element nil)))
  17612. (cond
  17613. ;; Element indented as a single block. Example blocks
  17614. ;; preserving indentation are a special case since the
  17615. ;; "contents" must not be indented whereas the block
  17616. ;; boundaries can.
  17617. ((or (memq type '(export-block latex-environment))
  17618. (and (eq type 'example-block)
  17619. (not
  17620. (or org-src-preserve-indentation
  17621. (org-element-property :preserve-indent element)))))
  17622. (let ((offset (- ind (current-indentation))))
  17623. (unless (zerop offset)
  17624. (indent-rigidly (org-element-property :begin element)
  17625. (org-element-property :end element)
  17626. offset)))
  17627. (goto-char element-end))
  17628. ;; Elements indented line wise. Be sure to exclude
  17629. ;; example blocks (preserving indentation) and source
  17630. ;; blocks from this category as they are treated
  17631. ;; specially later.
  17632. ((or (memq type '(paragraph table table-row))
  17633. (not (or (org-element-property :contents-begin element)
  17634. (memq type '(example-block src-block)))))
  17635. (when (eq type 'node-property)
  17636. (org--align-node-property)
  17637. (beginning-of-line))
  17638. (funcall indent-to ind (min element-end end)))
  17639. ;; Elements consisting of three parts: before the
  17640. ;; contents, the contents, and after the contents. The
  17641. ;; contents are treated specially, according to the
  17642. ;; element type, or not indented at all. Other parts are
  17643. ;; indented as a single block.
  17644. (t
  17645. (let* ((post (copy-marker
  17646. (org-element-property :post-affiliated element)))
  17647. (cbeg
  17648. (copy-marker
  17649. (cond
  17650. ((not (org-element-property :contents-begin element))
  17651. ;; Fake contents for source blocks.
  17652. (org-with-wide-buffer
  17653. (goto-char post)
  17654. (line-beginning-position 2)))
  17655. ((memq type '(footnote-definition item plain-list))
  17656. ;; Contents in these elements could start on
  17657. ;; the same line as the beginning of the
  17658. ;; element. Make sure we start indenting
  17659. ;; from the second line.
  17660. (org-with-wide-buffer
  17661. (goto-char post)
  17662. (end-of-line)
  17663. (skip-chars-forward " \r\t\n")
  17664. (if (eobp) (point) (line-beginning-position))))
  17665. (t (org-element-property :contents-begin element)))))
  17666. (cend (copy-marker
  17667. (or (org-element-property :contents-end element)
  17668. ;; Fake contents for source blocks.
  17669. (org-with-wide-buffer
  17670. (goto-char element-end)
  17671. (skip-chars-backward " \r\t\n")
  17672. (line-beginning-position)))
  17673. t)))
  17674. ;; Do not change items indentation individually as it
  17675. ;; might break the list as a whole. On the other
  17676. ;; hand, when at a plain list, indent it as a whole.
  17677. (cond ((eq type 'plain-list)
  17678. (let ((offset (- ind (current-indentation))))
  17679. (unless (zerop offset)
  17680. (indent-rigidly (org-element-property :begin element)
  17681. (org-element-property :end element)
  17682. offset))
  17683. (goto-char cbeg)))
  17684. ((eq type 'item) (goto-char cbeg))
  17685. (t (funcall indent-to ind (min cbeg end))))
  17686. (when (< (point) end)
  17687. (cl-case type
  17688. ((example-block verse-block))
  17689. (src-block
  17690. ;; In a source block, indent source code
  17691. ;; according to language major mode, but only if
  17692. ;; `org-src-tab-acts-natively' is non-nil.
  17693. (when (and (< (point) end) org-src-tab-acts-natively)
  17694. (ignore-errors
  17695. (org-babel-do-in-edit-buffer
  17696. (indent-region (point-min) (point-max))))))
  17697. (t (org-indent-region (point) (min cend end))))
  17698. (goto-char (min cend end))
  17699. (when (< (point) end)
  17700. (funcall indent-to ind (min element-end end))))
  17701. (set-marker post nil)
  17702. (set-marker cbeg nil)
  17703. (set-marker cend nil))))
  17704. (set-marker element-end nil))))
  17705. (set-marker end nil))))
  17706. (defun org-indent-drawer ()
  17707. "Indent the drawer at point."
  17708. (interactive)
  17709. (unless (save-excursion
  17710. (beginning-of-line)
  17711. (looking-at-p org-drawer-regexp))
  17712. (user-error "Not at a drawer"))
  17713. (let ((element (org-element-at-point)))
  17714. (unless (memq (org-element-type element) '(drawer property-drawer))
  17715. (user-error "Not at a drawer"))
  17716. (org-with-wide-buffer
  17717. (org-indent-region (org-element-property :begin element)
  17718. (org-element-property :end element))))
  17719. (message "Drawer at point indented"))
  17720. (defun org-indent-block ()
  17721. "Indent the block at point."
  17722. (interactive)
  17723. (unless (save-excursion
  17724. (beginning-of-line)
  17725. (let ((case-fold-search t))
  17726. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17727. (user-error "Not at a block"))
  17728. (let ((element (org-element-at-point)))
  17729. (unless (memq (org-element-type element)
  17730. '(comment-block center-block dynamic-block example-block
  17731. export-block quote-block special-block
  17732. src-block verse-block))
  17733. (user-error "Not at a block"))
  17734. (org-with-wide-buffer
  17735. (org-indent-region (org-element-property :begin element)
  17736. (org-element-property :end element))))
  17737. (message "Block at point indented"))
  17738. ;;; Filling
  17739. ;; We use our own fill-paragraph and auto-fill functions.
  17740. ;; `org-fill-paragraph' relies on adaptive filling and context
  17741. ;; checking. Appropriate `fill-prefix' is computed with
  17742. ;; `org-adaptive-fill-function'.
  17743. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17744. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17745. ;; `org-adaptive-fill-function' value. Internally,
  17746. ;; `org-comment-line-break-function' breaks the line.
  17747. ;; `org-setup-filling' installs filling and auto-filling related
  17748. ;; variables during `org-mode' initialization.
  17749. (defun org-setup-filling ()
  17750. (require 'org-element)
  17751. ;; Prevent auto-fill from inserting unwanted new items.
  17752. (when (boundp 'fill-nobreak-predicate)
  17753. (setq-local
  17754. fill-nobreak-predicate
  17755. (org-uniquify
  17756. (append fill-nobreak-predicate
  17757. '(org-fill-line-break-nobreak-p
  17758. org-fill-n-macro-as-item-nobreak-p
  17759. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17760. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17761. (setq-local paragraph-start paragraph-ending)
  17762. (setq-local paragraph-separate paragraph-ending))
  17763. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17764. (setq-local auto-fill-inhibit-regexp nil)
  17765. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17766. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17767. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17768. (defun org-fill-line-break-nobreak-p ()
  17769. "Non-nil when a new line at point would create an Org line break."
  17770. (save-excursion
  17771. (skip-chars-backward " \t")
  17772. (skip-chars-backward "\\\\")
  17773. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17774. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17775. "Non-nil when a new line at point would split a timestamp."
  17776. (and (org-at-timestamp-p 'lax)
  17777. (not (looking-at org-ts-regexp-both))))
  17778. (defun org-fill-n-macro-as-item-nobreak-p ()
  17779. "Non-nil when a new line at point would create a new list."
  17780. ;; During export, a "n" macro followed by a dot or a closing
  17781. ;; parenthesis can end up being parsed as a new list item.
  17782. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17783. (defun org-adaptive-fill-function ()
  17784. "Compute a fill prefix for the current line.
  17785. Return fill prefix, as a string, or nil if current line isn't
  17786. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17787. matches in paragraphs or comments, use it."
  17788. (org-with-wide-buffer
  17789. (unless (org-at-heading-p)
  17790. (let* ((p (line-beginning-position))
  17791. (element (save-excursion
  17792. (beginning-of-line)
  17793. (org-element-at-point)))
  17794. (type (org-element-type element))
  17795. (post-affiliated (org-element-property :post-affiliated element)))
  17796. (unless (< p post-affiliated)
  17797. (cl-case type
  17798. (comment
  17799. (save-excursion
  17800. (beginning-of-line)
  17801. (looking-at "[ \t]*")
  17802. (concat (match-string 0) "# ")))
  17803. (footnote-definition "")
  17804. ((item plain-list)
  17805. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17806. (paragraph
  17807. ;; Fill prefix is usually the same as the current line,
  17808. ;; unless the paragraph is at the beginning of an item.
  17809. (let ((parent (org-element-property :parent element)))
  17810. (save-excursion
  17811. (beginning-of-line)
  17812. (cond ((eq (org-element-type parent) 'item)
  17813. (make-string (org-list-item-body-column
  17814. (org-element-property :begin parent))
  17815. ?\s))
  17816. ((and adaptive-fill-regexp
  17817. ;; Locally disable
  17818. ;; `adaptive-fill-function' to let
  17819. ;; `fill-context-prefix' handle
  17820. ;; `adaptive-fill-regexp' variable.
  17821. (let (adaptive-fill-function)
  17822. (fill-context-prefix
  17823. post-affiliated
  17824. (org-element-property :end element)))))
  17825. ((looking-at "[ \t]+") (match-string 0))
  17826. (t "")))))
  17827. (comment-block
  17828. ;; Only fill contents if P is within block boundaries.
  17829. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17830. (forward-line)
  17831. (point)))
  17832. (cend (save-excursion
  17833. (goto-char (org-element-property :end element))
  17834. (skip-chars-backward " \r\t\n")
  17835. (line-beginning-position))))
  17836. (when (and (>= p cbeg) (< p cend))
  17837. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17838. (match-string 0)
  17839. ""))))))))))
  17840. (defun org-fill-element (&optional justify)
  17841. "Fill element at point, when applicable.
  17842. This function only applies to comment blocks, comments, example
  17843. blocks and paragraphs. Also, as a special case, re-align table
  17844. when point is at one.
  17845. If JUSTIFY is non-nil (interactively, with prefix argument),
  17846. justify as well. If `sentence-end-double-space' is non-nil, then
  17847. period followed by one space does not end a sentence, so don't
  17848. break a line there. The variable `fill-column' controls the
  17849. width for filling.
  17850. For convenience, when point is at a plain list, an item or
  17851. a footnote definition, try to fill the first paragraph within."
  17852. (with-syntax-table org-mode-transpose-word-syntax-table
  17853. ;; Move to end of line in order to get the first paragraph within
  17854. ;; a plain list or a footnote definition.
  17855. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17856. ;; First check if point is in a blank line at the beginning of
  17857. ;; the buffer. In that case, ignore filling.
  17858. (cl-case (org-element-type element)
  17859. ;; Use major mode filling function is source blocks.
  17860. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17861. ;; Align Org tables, leave table.el tables as-is.
  17862. (table-row (org-table-align) t)
  17863. (table
  17864. (when (eq (org-element-property :type element) 'org)
  17865. (save-excursion
  17866. (goto-char (org-element-property :post-affiliated element))
  17867. (org-table-align)))
  17868. t)
  17869. (paragraph
  17870. ;; Paragraphs may contain `line-break' type objects.
  17871. (let ((beg (max (point-min)
  17872. (org-element-property :contents-begin element)))
  17873. (end (min (point-max)
  17874. (org-element-property :contents-end element))))
  17875. ;; Do nothing if point is at an affiliated keyword.
  17876. (if (< (line-end-position) beg) t
  17877. ;; Fill paragraph, taking line breaks into account.
  17878. (save-excursion
  17879. (goto-char beg)
  17880. (let ((cuts (list beg)))
  17881. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17882. (when (eq 'line-break
  17883. (org-element-type
  17884. (save-excursion (backward-char)
  17885. (org-element-context))))
  17886. (push (point) cuts)))
  17887. (dolist (c (delq end cuts))
  17888. (fill-region-as-paragraph c end justify)
  17889. (setq end c))))
  17890. t)))
  17891. ;; Contents of `comment-block' type elements should be
  17892. ;; filled as plain text, but only if point is within block
  17893. ;; markers.
  17894. (comment-block
  17895. (let* ((case-fold-search t)
  17896. (beg (save-excursion
  17897. (goto-char (org-element-property :begin element))
  17898. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17899. (forward-line)
  17900. (point)))
  17901. (end (save-excursion
  17902. (goto-char (org-element-property :end element))
  17903. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17904. (line-beginning-position))))
  17905. (if (or (< (point) beg) (> (point) end)) t
  17906. (fill-region-as-paragraph
  17907. (save-excursion (end-of-line)
  17908. (re-search-backward "^[ \t]*$" beg 'move)
  17909. (line-beginning-position))
  17910. (save-excursion (beginning-of-line)
  17911. (re-search-forward "^[ \t]*$" end 'move)
  17912. (line-beginning-position))
  17913. justify))))
  17914. ;; Fill comments.
  17915. (comment
  17916. (let ((begin (org-element-property :post-affiliated element))
  17917. (end (org-element-property :end element)))
  17918. (when (and (>= (point) begin) (<= (point) end))
  17919. (let ((begin (save-excursion
  17920. (end-of-line)
  17921. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17922. (progn (forward-line) (point))
  17923. begin)))
  17924. (end (save-excursion
  17925. (end-of-line)
  17926. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17927. (1- (line-beginning-position))
  17928. (skip-chars-backward " \r\t\n")
  17929. (line-end-position)))))
  17930. ;; Do not fill comments when at a blank line.
  17931. (when (> end begin)
  17932. (let ((fill-prefix
  17933. (save-excursion
  17934. (beginning-of-line)
  17935. (looking-at "[ \t]*#")
  17936. (let ((comment-prefix (match-string 0)))
  17937. (goto-char (match-end 0))
  17938. (if (looking-at adaptive-fill-regexp)
  17939. (concat comment-prefix (match-string 0))
  17940. (concat comment-prefix " "))))))
  17941. (save-excursion
  17942. (fill-region-as-paragraph begin end justify))))))
  17943. t))
  17944. ;; Ignore every other element.
  17945. (otherwise t)))))
  17946. (defun org-fill-paragraph (&optional justify region)
  17947. "Fill element at point, when applicable.
  17948. This function only applies to comment blocks, comments, example
  17949. blocks and paragraphs. Also, as a special case, re-align table
  17950. when point is at one.
  17951. For convenience, when point is at a plain list, an item or
  17952. a footnote definition, try to fill the first paragraph within.
  17953. If JUSTIFY is non-nil (interactively, with prefix argument),
  17954. justify as well. If `sentence-end-double-space' is non-nil, then
  17955. period followed by one space does not end a sentence, so don't
  17956. break a line there. The variable `fill-column' controls the
  17957. width for filling.
  17958. The REGION argument is non-nil if called interactively; in that
  17959. case, if Transient Mark mode is enabled and the mark is active,
  17960. fill each of the elements in the active region, instead of just
  17961. filling the current element."
  17962. (interactive (progn
  17963. (barf-if-buffer-read-only)
  17964. (list (when current-prefix-arg 'full) t)))
  17965. (let ((hash (and (not (buffer-modified-p))
  17966. (org-buffer-hash))))
  17967. (cond
  17968. ((and region transient-mark-mode mark-active
  17969. (not (eq (region-beginning) (region-end))))
  17970. (let ((origin (point-marker))
  17971. (start (region-beginning)))
  17972. (unwind-protect
  17973. (progn
  17974. (goto-char (region-end))
  17975. (while (> (point) start)
  17976. (org-backward-paragraph)
  17977. (org-fill-element justify)))
  17978. (goto-char origin)
  17979. (set-marker origin nil))))
  17980. (t (org-fill-element justify)))
  17981. ;; If we didn't change anything in the buffer (and the buffer was
  17982. ;; previously unmodified), then flip the modification status back
  17983. ;; to "unchanged".
  17984. (when (and hash (equal hash (org-buffer-hash)))
  17985. (set-buffer-modified-p nil))))
  17986. (defun org-auto-fill-function ()
  17987. "Auto-fill function."
  17988. ;; Check if auto-filling is meaningful.
  17989. (let ((fc (current-fill-column)))
  17990. (when (and fc (> (current-column) fc))
  17991. (let* ((fill-prefix (org-adaptive-fill-function))
  17992. ;; Enforce empty fill prefix, if required. Otherwise, it
  17993. ;; will be computed again.
  17994. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17995. (when fill-prefix (do-auto-fill))))))
  17996. (defun org-comment-line-break-function (&optional soft)
  17997. "Break line at point and indent, continuing comment if within one.
  17998. The inserted newline is marked hard if variable
  17999. `use-hard-newlines' is true, unless optional argument SOFT is
  18000. non-nil."
  18001. (if soft (insert-and-inherit ?\n) (newline 1))
  18002. (save-excursion (forward-char -1) (delete-horizontal-space))
  18003. (delete-horizontal-space)
  18004. (indent-to-left-margin)
  18005. (insert-before-markers-and-inherit fill-prefix))
  18006. ;;; Fixed Width Areas
  18007. (defun org-toggle-fixed-width ()
  18008. "Toggle fixed-width markup.
  18009. Add or remove fixed-width markup on current line, whenever it
  18010. makes sense. Return an error otherwise.
  18011. If a region is active and if it contains only fixed-width areas
  18012. or blank lines, remove all fixed-width markup in it. If the
  18013. region contains anything else, convert all non-fixed-width lines
  18014. to fixed-width ones.
  18015. Blank lines at the end of the region are ignored unless the
  18016. region only contains such lines."
  18017. (interactive)
  18018. (if (not (org-region-active-p))
  18019. ;; No region:
  18020. ;;
  18021. ;; Remove fixed width marker only in a fixed-with element.
  18022. ;;
  18023. ;; Add fixed width maker in paragraphs, in blank lines after
  18024. ;; elements or at the beginning of a headline or an inlinetask,
  18025. ;; and before any one-line elements (e.g., a clock).
  18026. (progn
  18027. (beginning-of-line)
  18028. (let* ((element (org-element-at-point))
  18029. (type (org-element-type element)))
  18030. (cond
  18031. ((and (eq type 'fixed-width)
  18032. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18033. (replace-match
  18034. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18035. ((and (memq type '(babel-call clock comment diary-sexp headline
  18036. horizontal-rule keyword paragraph
  18037. planning))
  18038. (<= (org-element-property :post-affiliated element) (point)))
  18039. (skip-chars-forward " \t")
  18040. (insert ": "))
  18041. ((and (looking-at-p "[ \t]*$")
  18042. (or (eq type 'inlinetask)
  18043. (save-excursion
  18044. (skip-chars-forward " \r\t\n")
  18045. (<= (org-element-property :end element) (point)))))
  18046. (delete-region (point) (line-end-position))
  18047. (org-indent-line)
  18048. (insert ": "))
  18049. (t (user-error "Cannot insert a fixed-width line here")))))
  18050. ;; Region active.
  18051. (let* ((begin (save-excursion
  18052. (goto-char (region-beginning))
  18053. (line-beginning-position)))
  18054. (end (copy-marker
  18055. (save-excursion
  18056. (goto-char (region-end))
  18057. (unless (eolp) (beginning-of-line))
  18058. (if (save-excursion (re-search-backward "\\S-" begin t))
  18059. (progn (skip-chars-backward " \r\t\n") (point))
  18060. (point)))))
  18061. (all-fixed-width-p
  18062. (catch 'not-all-p
  18063. (save-excursion
  18064. (goto-char begin)
  18065. (skip-chars-forward " \r\t\n")
  18066. (when (eobp) (throw 'not-all-p nil))
  18067. (while (< (point) end)
  18068. (let ((element (org-element-at-point)))
  18069. (if (eq (org-element-type element) 'fixed-width)
  18070. (goto-char (org-element-property :end element))
  18071. (throw 'not-all-p nil))))
  18072. t))))
  18073. (if all-fixed-width-p
  18074. (save-excursion
  18075. (goto-char begin)
  18076. (while (< (point) end)
  18077. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18078. (replace-match
  18079. "" nil nil nil
  18080. (if (= (line-end-position) (match-end 0)) 0 1)))
  18081. (forward-line)))
  18082. (let ((min-ind (point-max)))
  18083. ;; Find minimum indentation across all lines.
  18084. (save-excursion
  18085. (goto-char begin)
  18086. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18087. (setq min-ind 0)
  18088. (catch 'zerop
  18089. (while (< (point) end)
  18090. (unless (looking-at-p "[ \t]*$")
  18091. (let ((ind (current-indentation)))
  18092. (setq min-ind (min min-ind ind))
  18093. (when (zerop ind) (throw 'zerop t))))
  18094. (forward-line)))))
  18095. ;; Loop over all lines and add fixed-width markup everywhere
  18096. ;; but in fixed-width lines.
  18097. (save-excursion
  18098. (goto-char begin)
  18099. (while (< (point) end)
  18100. (cond
  18101. ((org-at-heading-p)
  18102. (insert ": ")
  18103. (forward-line)
  18104. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18105. (insert ":")
  18106. (forward-line)))
  18107. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18108. (let* ((element (org-element-at-point))
  18109. (element-end (org-element-property :end element)))
  18110. (if (eq (org-element-type element) 'fixed-width)
  18111. (progn (goto-char element-end)
  18112. (skip-chars-backward " \r\t\n")
  18113. (forward-line))
  18114. (let ((limit (min end element-end)))
  18115. (while (< (point) limit)
  18116. (org-move-to-column min-ind t)
  18117. (insert ": ")
  18118. (forward-line))))))
  18119. (t
  18120. (org-move-to-column min-ind t)
  18121. (insert ": ")
  18122. (forward-line)))))))
  18123. (set-marker end nil))))
  18124. ;;; Blocks
  18125. (defun org-block-map (function &optional start end)
  18126. "Call FUNCTION at the head of all source blocks in the current buffer.
  18127. Optional arguments START and END can be used to limit the range."
  18128. (let ((start (or start (point-min)))
  18129. (end (or end (point-max))))
  18130. (save-excursion
  18131. (goto-char start)
  18132. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18133. (save-excursion
  18134. (save-match-data
  18135. (goto-char (match-beginning 0))
  18136. (funcall function)))))))
  18137. (defun org-next-block (arg &optional backward block-regexp)
  18138. "Jump to the next block.
  18139. With a prefix argument ARG, jump forward ARG many blocks.
  18140. When BACKWARD is non-nil, jump to the previous block.
  18141. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18142. Match data is set according to this regexp when the function
  18143. returns.
  18144. Return point at beginning of the opening line of found block.
  18145. Throw an error if no block is found."
  18146. (interactive "p")
  18147. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18148. (case-fold-search t)
  18149. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18150. (count (or arg 1))
  18151. (origin (point))
  18152. last-element)
  18153. (if backward (beginning-of-line) (end-of-line))
  18154. (while (and (> count 0) (funcall search-fn re nil t))
  18155. (let ((element (save-excursion
  18156. (goto-char (match-beginning 0))
  18157. (save-match-data (org-element-at-point)))))
  18158. (when (and (memq (org-element-type element)
  18159. '(center-block comment-block dynamic-block
  18160. example-block export-block quote-block
  18161. special-block src-block verse-block))
  18162. (<= (match-beginning 0)
  18163. (org-element-property :post-affiliated element)))
  18164. (setq last-element element)
  18165. (cl-decf count))))
  18166. (if (= count 0)
  18167. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18168. (save-match-data (org-show-context)))
  18169. (goto-char origin)
  18170. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18171. (defun org-previous-block (arg &optional block-regexp)
  18172. "Jump to the previous block.
  18173. With a prefix argument ARG, jump backward ARG many source blocks.
  18174. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18175. (interactive "p")
  18176. (org-next-block arg t block-regexp))
  18177. ;;; Comments
  18178. ;; Org comments syntax is quite complex. It requires the entire line
  18179. ;; to be just a comment. Also, even with the right syntax at the
  18180. ;; beginning of line, some elements (e.g., verse-block or
  18181. ;; example-block) don't accept comments. Usual Emacs comment commands
  18182. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18183. ;; Org still relies on `comment-dwim', but cannot trust
  18184. ;; `comment-only-p'. So, `comment-region-function' and
  18185. ;; `uncomment-region-function' both point
  18186. ;; to`org-comment-or-uncomment-region'. Eventually,
  18187. ;; `org-insert-comment' takes care of insertion of comments at the
  18188. ;; beginning of line.
  18189. ;; `org-setup-comments-handling' install comments related variables
  18190. ;; during `org-mode' initialization.
  18191. (defun org-setup-comments-handling ()
  18192. (interactive)
  18193. (setq-local comment-use-syntax nil)
  18194. (setq-local comment-start "# ")
  18195. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18196. (setq-local comment-insert-comment-function 'org-insert-comment)
  18197. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18198. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18199. (defun org-insert-comment ()
  18200. "Insert an empty comment above current line.
  18201. If the line is empty, insert comment at its beginning. When
  18202. point is within a source block, comment according to the related
  18203. major mode."
  18204. (if (let ((element (org-element-at-point)))
  18205. (and (eq (org-element-type element) 'src-block)
  18206. (< (save-excursion
  18207. (goto-char (org-element-property :post-affiliated element))
  18208. (line-end-position))
  18209. (point))
  18210. (> (save-excursion
  18211. (goto-char (org-element-property :end element))
  18212. (skip-chars-backward " \r\t\n")
  18213. (line-beginning-position))
  18214. (point))))
  18215. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18216. (beginning-of-line)
  18217. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18218. (open-line 1))
  18219. (org-indent-line)
  18220. (insert "# ")))
  18221. (defvar comment-empty-lines) ; From newcomment.el.
  18222. (defun org-comment-or-uncomment-region (beg end &rest _)
  18223. "Comment or uncomment each non-blank line in the region.
  18224. Uncomment each non-blank line between BEG and END if it only
  18225. contains commented lines. Otherwise, comment them. If region is
  18226. strictly within a source block, use appropriate comment syntax."
  18227. (if (let ((element (org-element-at-point)))
  18228. (and (eq (org-element-type element) 'src-block)
  18229. (< (save-excursion
  18230. (goto-char (org-element-property :post-affiliated element))
  18231. (line-end-position))
  18232. beg)
  18233. (>= (save-excursion
  18234. (goto-char (org-element-property :end element))
  18235. (skip-chars-backward " \r\t\n")
  18236. (line-beginning-position))
  18237. end)))
  18238. ;; Translate region boundaries for the Org buffer to the source
  18239. ;; buffer.
  18240. (let ((offset (- end beg)))
  18241. (save-excursion
  18242. (goto-char beg)
  18243. (org-babel-do-in-edit-buffer
  18244. (comment-or-uncomment-region (point) (+ offset (point))))))
  18245. (save-restriction
  18246. ;; Restrict region
  18247. (narrow-to-region (save-excursion (goto-char beg)
  18248. (skip-chars-forward " \r\t\n" end)
  18249. (line-beginning-position))
  18250. (save-excursion (goto-char end)
  18251. (skip-chars-backward " \r\t\n" beg)
  18252. (line-end-position)))
  18253. (let ((uncommentp
  18254. ;; UNCOMMENTP is non-nil when every non blank line between
  18255. ;; BEG and END is a comment.
  18256. (save-excursion
  18257. (goto-char (point-min))
  18258. (while (and (not (eobp))
  18259. (let ((element (org-element-at-point)))
  18260. (and (eq (org-element-type element) 'comment)
  18261. (goto-char (min (point-max)
  18262. (org-element-property
  18263. :end element)))))))
  18264. (eobp))))
  18265. (if uncommentp
  18266. ;; Only blank lines and comments in region: uncomment it.
  18267. (save-excursion
  18268. (goto-char (point-min))
  18269. (while (not (eobp))
  18270. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18271. (replace-match "" nil nil nil 1))
  18272. (forward-line)))
  18273. ;; Comment each line in region.
  18274. (let ((min-indent (point-max)))
  18275. ;; First find the minimum indentation across all lines.
  18276. (save-excursion
  18277. (goto-char (point-min))
  18278. (while (and (not (eobp)) (not (zerop min-indent)))
  18279. (unless (looking-at "[ \t]*$")
  18280. (setq min-indent (min min-indent (current-indentation))))
  18281. (forward-line)))
  18282. ;; Then loop over all lines.
  18283. (save-excursion
  18284. (goto-char (point-min))
  18285. (while (not (eobp))
  18286. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18287. ;; Don't get fooled by invisible text (e.g. link path)
  18288. ;; when moving to column MIN-INDENT.
  18289. (let ((buffer-invisibility-spec nil))
  18290. (org-move-to-column min-indent t))
  18291. (insert comment-start))
  18292. (forward-line)))))))))
  18293. (defun org-comment-dwim (_arg)
  18294. "Call the comment command you mean.
  18295. Call `org-toggle-comment' if on a heading, otherwise call
  18296. `comment-dwim', within a source edit buffer if needed."
  18297. (interactive "*P")
  18298. (cond ((org-at-heading-p)
  18299. (call-interactively #'org-toggle-comment))
  18300. ((org-in-src-block-p)
  18301. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18302. (t (call-interactively #'comment-dwim))))
  18303. ;;; Timestamps API
  18304. ;; This section contains tools to operate on, or create, timestamp
  18305. ;; objects, as returned by, e.g. `org-element-context'.
  18306. (defun org-timestamp-from-string (s)
  18307. "Convert Org timestamp S, as a string, into a timestamp object.
  18308. Return nil if S is not a valid timestamp string."
  18309. (when (org-string-nw-p s)
  18310. (with-temp-buffer
  18311. (save-excursion (insert s))
  18312. (org-element-timestamp-parser))))
  18313. (defun org-timestamp-from-time (time &optional with-time inactive)
  18314. "Convert a time value into a timestamp object.
  18315. TIME is an Emacs internal time representation, as returned, e.g.,
  18316. by `current-time'.
  18317. When optional argument WITH-TIME is non-nil, return a timestamp
  18318. object with a time part, i.e., with hours and minutes.
  18319. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18320. return an active timestamp."
  18321. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18322. (org-element-create 'timestamp
  18323. (list :type (if inactive 'inactive 'active)
  18324. :year-start year
  18325. :month-start month
  18326. :day-start day
  18327. :hour-start (and with-time hour)
  18328. :minute-start (and with-time minute)))))
  18329. (defun org-timestamp-to-time (timestamp &optional end)
  18330. "Convert TIMESTAMP object into an Emacs internal time value.
  18331. Use end of date range or time range when END is non-nil.
  18332. Otherwise, use its start."
  18333. (apply #'encode-time
  18334. (cons 0
  18335. (mapcar
  18336. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18337. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18338. '(:minute-start :hour-start :day-start :month-start
  18339. :year-start))))))
  18340. (defun org-timestamp-has-time-p (timestamp)
  18341. "Non-nil when TIMESTAMP has a time specified."
  18342. (org-element-property :hour-start timestamp))
  18343. (defun org-timestamp-format (timestamp format &optional end utc)
  18344. "Format a TIMESTAMP object into a string.
  18345. FORMAT is a format specifier to be passed to
  18346. `format-time-string'.
  18347. When optional argument END is non-nil, use end of date-range or
  18348. time-range, if possible.
  18349. When optional argument UTC is non-nil, time is be expressed as
  18350. Universal Time."
  18351. (format-time-string format (org-timestamp-to-time timestamp end)
  18352. (and utc t)))
  18353. (defun org-timestamp-split-range (timestamp &optional end)
  18354. "Extract a TIMESTAMP object from a date or time range.
  18355. END, when non-nil, means extract the end of the range.
  18356. Otherwise, extract its start.
  18357. Return a new timestamp object."
  18358. (let ((type (org-element-property :type timestamp)))
  18359. (if (memq type '(active inactive diary)) timestamp
  18360. (let ((split-ts (org-element-copy timestamp)))
  18361. ;; Set new type.
  18362. (org-element-put-property
  18363. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18364. ;; Copy start properties over end properties if END is
  18365. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18366. (let ((p-alist '((:minute-start . :minute-end)
  18367. (:hour-start . :hour-end)
  18368. (:day-start . :day-end)
  18369. (:month-start . :month-end)
  18370. (:year-start . :year-end))))
  18371. (dolist (p-cell p-alist)
  18372. (org-element-put-property
  18373. split-ts
  18374. (funcall (if end #'car #'cdr) p-cell)
  18375. (org-element-property
  18376. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18377. ;; Eventually refresh `:raw-value'.
  18378. (org-element-put-property split-ts :raw-value nil)
  18379. (org-element-put-property
  18380. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18381. (defun org-timestamp-translate (timestamp &optional boundary)
  18382. "Translate TIMESTAMP object to custom format.
  18383. Format string is defined in `org-time-stamp-custom-formats',
  18384. which see.
  18385. When optional argument BOUNDARY is non-nil, it is either the
  18386. symbol `start' or `end'. In this case, only translate the
  18387. starting or ending part of TIMESTAMP if it is a date or time
  18388. range. Otherwise, translate both parts.
  18389. Return timestamp as-is if `org-display-custom-times' is nil or if
  18390. it has a `diary' type."
  18391. (let ((type (org-element-property :type timestamp)))
  18392. (if (or (not org-display-custom-times) (eq type 'diary))
  18393. (org-element-interpret-data timestamp)
  18394. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18395. org-time-stamp-custom-formats)))
  18396. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18397. (concat (org-timestamp-format timestamp fmt)
  18398. "--"
  18399. (org-timestamp-format timestamp fmt t))
  18400. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18401. ;;; Other stuff
  18402. (defvar reftex-docstruct-symbol)
  18403. (defvar org--rds)
  18404. (defun org-reftex-citation ()
  18405. "Use reftex-citation to insert a citation into the buffer.
  18406. This looks for a line like
  18407. #+BIBLIOGRAPHY: foo plain option:-d
  18408. and derives from it that foo.bib is the bibliography file relevant
  18409. for this document. It then installs the necessary environment for RefTeX
  18410. to work in this buffer and calls `reftex-citation' to insert a citation
  18411. into the buffer.
  18412. Export of such citations to both LaTeX and HTML is handled by the contributed
  18413. package ox-bibtex by Taru Karttunen."
  18414. (interactive)
  18415. (let ((reftex-docstruct-symbol 'org--rds)
  18416. org--rds bib)
  18417. (org-with-wide-buffer
  18418. (let ((case-fold-search t)
  18419. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18420. (if (not (save-excursion
  18421. (or (re-search-forward re nil t)
  18422. (re-search-backward re nil t))))
  18423. (user-error "No bibliography defined in file")
  18424. (setq bib (concat (match-string 1) ".bib")
  18425. org--rds (list (list 'bib bib))))))
  18426. (call-interactively 'reftex-citation)))
  18427. ;;;; Functions extending outline functionality
  18428. (defun org-beginning-of-line (&optional n)
  18429. "Go to the beginning of the current visible line.
  18430. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18431. symbol `reversed', on the first attempt move to where the
  18432. headline text starts, and only move to beginning of line when the
  18433. cursor is already before the start of the text of the headline.
  18434. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18435. start of the text on the second attempt.
  18436. With argument N not nil or 1, move forward N - 1 lines first."
  18437. (interactive "^p")
  18438. (let ((origin (point))
  18439. (special (pcase org-special-ctrl-a/e
  18440. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18441. deactivate-mark)
  18442. ;; First move to a visible line.
  18443. (if (bound-and-true-p visual-line-mode)
  18444. (beginning-of-visual-line n)
  18445. (move-beginning-of-line n)
  18446. ;; `move-beginning-of-line' may leave point after invisible
  18447. ;; characters if line starts with such of these (e.g., with
  18448. ;; a link at column 0). Really move to the beginning of the
  18449. ;; current visible line.
  18450. (beginning-of-line))
  18451. (cond
  18452. ;; No special behavior. Point is already at the beginning of
  18453. ;; a line, logical or visual.
  18454. ((not special))
  18455. ;; `beginning-of-visual-line' left point before logical beginning
  18456. ;; of line: point is at the beginning of a visual line. Bail
  18457. ;; out.
  18458. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18459. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18460. ;; At a headline, special position is before the title, but
  18461. ;; after any TODO keyword or priority cookie.
  18462. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18463. (line-end-position)))
  18464. (bol (point)))
  18465. (if (eq special 'reversed)
  18466. (when (and (= origin bol) (eq last-command this-command))
  18467. (goto-char refpos))
  18468. (when (or (> origin refpos) (= origin bol))
  18469. (goto-char refpos)))))
  18470. ((and (looking-at org-list-full-item-re)
  18471. (memq (org-element-type (save-match-data (org-element-at-point)))
  18472. '(item plain-list)))
  18473. ;; Set special position at first white space character after
  18474. ;; bullet, and check-box, if any.
  18475. (let ((after-bullet
  18476. (let ((box (match-end 3)))
  18477. (cond ((not box) (match-end 1))
  18478. ((eq (char-after box) ?\s) (1+ box))
  18479. (t box)))))
  18480. (if (eq special 'reversed)
  18481. (when (and (= (point) origin) (eq last-command this-command))
  18482. (goto-char after-bullet))
  18483. (when (or (> origin after-bullet) (= (point) origin))
  18484. (goto-char after-bullet)))))
  18485. ;; No special context. Point is already at beginning of line.
  18486. (t nil))))
  18487. (defun org-end-of-line (&optional n)
  18488. "Go to the end of the line, but before ellipsis, if any.
  18489. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18490. symbol `reversed', ignore tags on the first attempt, and only
  18491. move to after the tags when the cursor is already beyond the end
  18492. of the headline.
  18493. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18494. on the second attempt.
  18495. With argument N not nil or 1, move forward N - 1 lines first."
  18496. (interactive "^p")
  18497. (let ((origin (point))
  18498. (special (pcase org-special-ctrl-a/e
  18499. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18500. deactivate-mark)
  18501. ;; First move to a visible line.
  18502. (if (bound-and-true-p visual-line-mode)
  18503. (beginning-of-visual-line n)
  18504. (move-beginning-of-line n))
  18505. (cond
  18506. ;; At a headline, with tags.
  18507. ((and special
  18508. (save-excursion
  18509. (beginning-of-line)
  18510. (let ((case-fold-search nil))
  18511. (looking-at org-complex-heading-regexp)))
  18512. (match-end 5))
  18513. (let ((tags (save-excursion
  18514. (goto-char (match-beginning 5))
  18515. (skip-chars-backward " \t")
  18516. (point)))
  18517. (visual-end (and (bound-and-true-p visual-line-mode)
  18518. (save-excursion
  18519. (end-of-visual-line)
  18520. (point)))))
  18521. ;; If `end-of-visual-line' brings us before end of line or
  18522. ;; even tags, i.e., the headline spans over multiple visual
  18523. ;; lines, move there.
  18524. (cond ((and visual-end
  18525. (< visual-end tags)
  18526. (<= origin visual-end))
  18527. (goto-char visual-end))
  18528. ((eq special 'reversed)
  18529. (if (and (= origin (line-end-position))
  18530. (eq this-command last-command))
  18531. (goto-char tags)
  18532. (end-of-line)))
  18533. (t
  18534. (if (or (< origin tags) (= origin (line-end-position)))
  18535. (goto-char tags)
  18536. (end-of-line))))))
  18537. ((bound-and-true-p visual-line-mode)
  18538. (let ((bol (line-beginning-position)))
  18539. (end-of-visual-line)
  18540. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18541. ;; end of a line, backtrack and use `end-of-line' instead.
  18542. (when (/= bol (line-beginning-position))
  18543. (goto-char bol)
  18544. (end-of-line))))
  18545. (t (end-of-line)))))
  18546. (defun org-backward-sentence (&optional _arg)
  18547. "Go to beginning of sentence, or beginning of table field.
  18548. This will call `backward-sentence' or `org-table-beginning-of-field',
  18549. depending on context."
  18550. (interactive)
  18551. (let* ((element (org-element-at-point))
  18552. (contents-begin (org-element-property :contents-begin element))
  18553. (table (org-element-lineage element '(table) t)))
  18554. (if (and table
  18555. (> (point) contents-begin)
  18556. (<= (point) (org-element-property :contents-end table)))
  18557. (call-interactively #'org-table-beginning-of-field)
  18558. (save-restriction
  18559. (when (and contents-begin
  18560. (< (point-min) contents-begin)
  18561. (> (point) contents-begin))
  18562. (narrow-to-region contents-begin
  18563. (org-element-property :contents-end element)))
  18564. (call-interactively #'backward-sentence)))))
  18565. (defun org-forward-sentence (&optional _arg)
  18566. "Go to end of sentence, or end of table field.
  18567. This will call `forward-sentence' or `org-table-end-of-field',
  18568. depending on context."
  18569. (interactive)
  18570. (if (and (org-at-heading-p)
  18571. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18572. (save-restriction
  18573. (narrow-to-region (line-beginning-position) (line-end-position))
  18574. (call-interactively #'forward-sentence))
  18575. (let* ((element (org-element-at-point))
  18576. (contents-end (org-element-property :contents-end element))
  18577. (table (org-element-lineage element '(table) t)))
  18578. (if (and table
  18579. (>= (point) (org-element-property :contents-begin table))
  18580. (< (point) contents-end))
  18581. (call-interactively #'org-table-end-of-field)
  18582. (save-restriction
  18583. (when (and contents-end
  18584. (> (point-max) contents-end)
  18585. ;; Skip blank lines between elements.
  18586. (< (org-element-property :end element)
  18587. (save-excursion (goto-char contents-end)
  18588. (skip-chars-forward " \r\t\n"))))
  18589. (narrow-to-region (org-element-property :contents-begin element)
  18590. contents-end))
  18591. ;; End of heading is considered as the end of a sentence.
  18592. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18593. (call-interactively #'forward-sentence)))))))
  18594. (defun org-kill-line (&optional _arg)
  18595. "Kill line, to tags or end of line."
  18596. (interactive)
  18597. (cond
  18598. ((or (not org-special-ctrl-k)
  18599. (bolp)
  18600. (not (org-at-heading-p)))
  18601. (when (and (get-char-property (line-end-position) 'invisible)
  18602. org-ctrl-k-protect-subtree
  18603. (or (eq org-ctrl-k-protect-subtree 'error)
  18604. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18605. (user-error
  18606. (substitute-command-keys
  18607. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18608. (call-interactively
  18609. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18610. ((org-match-line org-tag-line-re)
  18611. (let ((end (save-excursion
  18612. (goto-char (match-beginning 1))
  18613. (skip-chars-backward " \t")
  18614. (point))))
  18615. (if (<= end (point)) ;on tags part
  18616. (kill-region (point) (line-end-position))
  18617. (kill-region (point) end)))
  18618. (org-align-tags))
  18619. (t (kill-region (point) (line-end-position)))))
  18620. (defun org-yank (&optional arg)
  18621. "Yank. If the kill is a subtree, treat it specially.
  18622. This command will look at the current kill and check if is a single
  18623. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18624. cursor is at the beginning of a line or after the stars of a currently
  18625. empty headline, then the yank is handled specially. How exactly depends
  18626. on the value of the following variables.
  18627. `org-yank-folded-subtrees'
  18628. By default, this variable is non-nil, which results in
  18629. subtree(s) being folded after insertion, except if doing so
  18630. would swallow text after the yanked text.
  18631. `org-yank-adjusted-subtrees'
  18632. When non-nil (the default value is nil), the subtree will be
  18633. promoted or demoted in order to fit into the local outline tree
  18634. structure, which means that the level will be adjusted so that it
  18635. becomes the smaller one of the two *visible* surrounding headings.
  18636. Any prefix to this command will cause `yank' to be called directly with
  18637. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18638. will just
  18639. plainly yank the text as it is.
  18640. \[1] The test checks if the first non-white line is a heading
  18641. and if there are no other headings with fewer stars."
  18642. (interactive "P")
  18643. (org-yank-generic 'yank arg))
  18644. (defun org-yank-generic (command arg)
  18645. "Perform some yank-like command.
  18646. This function implements the behavior described in the `org-yank'
  18647. documentation. However, it has been generalized to work for any
  18648. interactive command with similar behavior."
  18649. ;; pretend to be command COMMAND
  18650. (setq this-command command)
  18651. (if arg
  18652. (call-interactively command)
  18653. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18654. (and (org-kill-is-subtree-p)
  18655. (or (bolp)
  18656. (and (looking-at "[ \t]*$")
  18657. (string-match
  18658. "\\`\\*+\\'"
  18659. (buffer-substring (point-at-bol) (point)))))))
  18660. swallowp)
  18661. (cond
  18662. ((and subtreep org-yank-folded-subtrees)
  18663. (let ((beg (point))
  18664. end)
  18665. (if (and subtreep org-yank-adjusted-subtrees)
  18666. (org-paste-subtree nil nil 'for-yank)
  18667. (call-interactively command))
  18668. (setq end (point))
  18669. (goto-char beg)
  18670. (when (and (bolp) subtreep
  18671. (not (setq swallowp
  18672. (org-yank-folding-would-swallow-text beg end))))
  18673. (org-with-limited-levels
  18674. (or (looking-at org-outline-regexp)
  18675. (re-search-forward org-outline-regexp-bol end t))
  18676. (while (and (< (point) end) (looking-at org-outline-regexp))
  18677. (org-flag-subtree t)
  18678. (org-cycle-show-empty-lines 'folded)
  18679. (condition-case nil
  18680. (outline-forward-same-level 1)
  18681. (error (goto-char end))))))
  18682. (when swallowp
  18683. (message
  18684. "Inserted text not folded because that would swallow text"))
  18685. (goto-char end)
  18686. (skip-chars-forward " \t\n\r")
  18687. (beginning-of-line 1)
  18688. (push-mark beg 'nomsg)))
  18689. ((and subtreep org-yank-adjusted-subtrees)
  18690. (let ((beg (point-at-bol)))
  18691. (org-paste-subtree nil nil 'for-yank)
  18692. (push-mark beg 'nomsg)))
  18693. (t
  18694. (call-interactively command))))))
  18695. (defun org-yank-folding-would-swallow-text (beg end)
  18696. "Would hide-subtree at BEG swallow any text after END?"
  18697. (let (level)
  18698. (org-with-limited-levels
  18699. (save-excursion
  18700. (goto-char beg)
  18701. (when (or (looking-at org-outline-regexp)
  18702. (re-search-forward org-outline-regexp-bol end t))
  18703. (setq level (org-outline-level)))
  18704. (goto-char end)
  18705. (skip-chars-forward " \t\r\n\v\f")
  18706. (not (or (eobp)
  18707. (and (bolp) (looking-at-p org-outline-regexp)
  18708. (<= (org-outline-level) level))))))))
  18709. (defun org-back-to-heading (&optional invisible-ok)
  18710. "Call `outline-back-to-heading', but provide a better error message."
  18711. (condition-case nil
  18712. (outline-back-to-heading invisible-ok)
  18713. (error (error "Before first headline at position %d in buffer %s"
  18714. (point) (current-buffer)))))
  18715. (defun org-before-first-heading-p ()
  18716. "Before first heading?"
  18717. (org-with-limited-levels
  18718. (save-excursion
  18719. (end-of-line)
  18720. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18721. (defun org-at-heading-p (&optional _)
  18722. "Non-nil when on a headline."
  18723. (outline-on-heading-p t))
  18724. (defun org-in-commented-heading-p (&optional no-inheritance)
  18725. "Non-nil if point is under a commented heading.
  18726. This function also checks ancestors of the current headline,
  18727. unless optional argument NO-INHERITANCE is non-nil."
  18728. (cond
  18729. ((org-before-first-heading-p) nil)
  18730. ((let ((headline (nth 4 (org-heading-components))))
  18731. (and headline
  18732. (let ((case-fold-search nil))
  18733. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18734. headline)))))
  18735. (no-inheritance nil)
  18736. (t
  18737. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18738. (defun org-at-comment-p nil
  18739. "Is cursor in a commented line?"
  18740. (save-excursion
  18741. (save-match-data
  18742. (beginning-of-line)
  18743. (looking-at "^[ \t]*# "))))
  18744. (defun org-at-drawer-p nil
  18745. "Is cursor at a drawer keyword?"
  18746. (save-excursion
  18747. (move-beginning-of-line 1)
  18748. (looking-at org-drawer-regexp)))
  18749. (defun org-at-block-p nil
  18750. "Is cursor at a block keyword?"
  18751. (save-excursion
  18752. (move-beginning-of-line 1)
  18753. (looking-at org-block-regexp)))
  18754. (defun org-point-at-end-of-empty-headline ()
  18755. "If point is at the end of an empty headline, return t, else nil.
  18756. If the heading only contains a TODO keyword, it is still still considered
  18757. empty."
  18758. (let ((case-fold-search nil))
  18759. (and (looking-at "[ \t]*$")
  18760. org-todo-line-regexp
  18761. (save-excursion
  18762. (beginning-of-line)
  18763. (looking-at org-todo-line-regexp)
  18764. (string= (match-string 3) "")))))
  18765. (defun org-at-heading-or-item-p ()
  18766. (or (org-at-heading-p) (org-at-item-p)))
  18767. (defun org-up-heading-all (arg)
  18768. "Move to the heading line of which the present line is a subheading.
  18769. This function considers both visible and invisible heading lines.
  18770. With argument, move up ARG levels."
  18771. (outline-up-heading arg t))
  18772. (defun org-up-heading-safe ()
  18773. "Move to the heading line of which the present line is a subheading.
  18774. This version will not throw an error. It will return the level of the
  18775. headline found, or nil if no higher level is found.
  18776. Also, this function will be a lot faster than `outline-up-heading',
  18777. because it relies on stars being the outline starters. This can really
  18778. make a significant difference in outlines with very many siblings."
  18779. (when (ignore-errors (org-back-to-heading t))
  18780. (let ((level-up (1- (funcall outline-level))))
  18781. (and (> level-up 0)
  18782. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18783. (funcall outline-level)))))
  18784. (defun org-first-sibling-p ()
  18785. "Is this heading the first child of its parents?"
  18786. (interactive)
  18787. (let ((re org-outline-regexp-bol)
  18788. level l)
  18789. (unless (org-at-heading-p t)
  18790. (user-error "Not at a heading"))
  18791. (setq level (funcall outline-level))
  18792. (save-excursion
  18793. (if (not (re-search-backward re nil t))
  18794. t
  18795. (setq l (funcall outline-level))
  18796. (< l level)))))
  18797. (defun org-goto-sibling (&optional previous)
  18798. "Goto the next sibling, even if it is invisible.
  18799. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18800. when a sibling was found. When none is found, return nil and don't
  18801. move point."
  18802. (let ((fun (if previous 're-search-backward 're-search-forward))
  18803. (pos (point))
  18804. (re org-outline-regexp-bol)
  18805. level l)
  18806. (when (ignore-errors (org-back-to-heading t))
  18807. (setq level (funcall outline-level))
  18808. (catch 'exit
  18809. (or previous (forward-char 1))
  18810. (while (funcall fun re nil t)
  18811. (setq l (funcall outline-level))
  18812. (when (< l level) (goto-char pos) (throw 'exit nil))
  18813. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18814. (goto-char pos)
  18815. nil))))
  18816. (defun org-show-siblings ()
  18817. "Show all siblings of the current headline."
  18818. (save-excursion
  18819. (while (org-goto-sibling) (org-flag-heading nil)))
  18820. (save-excursion
  18821. (while (org-goto-sibling 'previous)
  18822. (org-flag-heading nil))))
  18823. (defun org-goto-first-child ()
  18824. "Goto the first child, even if it is invisible.
  18825. Return t when a child was found. Otherwise don't move point and
  18826. return nil."
  18827. (let (level (pos (point)) (re org-outline-regexp-bol))
  18828. (when (ignore-errors (org-back-to-heading t))
  18829. (setq level (outline-level))
  18830. (forward-char 1)
  18831. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18832. (progn (goto-char (match-beginning 0)) t)
  18833. (goto-char pos) nil))))
  18834. (defun org-show-hidden-entry ()
  18835. "Show an entry where even the heading is hidden."
  18836. (save-excursion
  18837. (org-show-entry)))
  18838. (defun org-flag-heading (flag &optional entry)
  18839. "Flag the current heading. FLAG non-nil means make invisible.
  18840. When ENTRY is non-nil, show the entire entry."
  18841. (save-excursion
  18842. (org-back-to-heading t)
  18843. ;; Check if we should show the entire entry
  18844. (if (not entry)
  18845. (org-flag-region
  18846. (line-end-position 0) (line-end-position) flag 'outline)
  18847. (org-show-entry)
  18848. (save-excursion
  18849. (and (outline-next-heading)
  18850. (org-flag-heading nil))))))
  18851. (defun org-get-next-sibling ()
  18852. "Move to next heading of the same level, and return point.
  18853. If there is no such heading, return nil.
  18854. This is like outline-next-sibling, but invisible headings are ok."
  18855. (let ((level (funcall outline-level)))
  18856. (outline-next-heading)
  18857. (while (and (not (eobp)) (> (funcall outline-level) level))
  18858. (outline-next-heading))
  18859. (unless (or (eobp) (< (funcall outline-level) level))
  18860. (point))))
  18861. (defun org-get-last-sibling ()
  18862. "Move to previous heading of the same level, and return point.
  18863. If there is no such heading, return nil."
  18864. (let ((opoint (point))
  18865. (level (funcall outline-level)))
  18866. (outline-previous-heading)
  18867. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18868. (while (and (> (funcall outline-level) level)
  18869. (not (bobp)))
  18870. (outline-previous-heading))
  18871. (unless (< (funcall outline-level) level)
  18872. (point)))))
  18873. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18874. "Goto to the end of a subtree."
  18875. ;; This contains an exact copy of the original function, but it uses
  18876. ;; `org-back-to-heading', to make it work also in invisible
  18877. ;; trees. And is uses an invisible-ok argument.
  18878. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18879. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18880. ;; with many children and grandchildren etc, this can be much faster
  18881. ;; than the outline version.
  18882. (org-back-to-heading invisible-ok)
  18883. (let ((first t)
  18884. (level (funcall outline-level)))
  18885. (if (and (derived-mode-p 'org-mode) (< level 1000))
  18886. ;; A true heading (not a plain list item), in Org
  18887. ;; This means we can easily find the end by looking
  18888. ;; only for the right number of stars. Using a regexp to do
  18889. ;; this is so much faster than using a Lisp loop.
  18890. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  18891. (forward-char 1)
  18892. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  18893. ;; something else, do it the slow way
  18894. (while (and (not (eobp))
  18895. (or first (> (funcall outline-level) level)))
  18896. (setq first nil)
  18897. (outline-next-heading)))
  18898. (unless to-heading
  18899. (when (memq (preceding-char) '(?\n ?\^M))
  18900. ;; Go to end of line before heading
  18901. (forward-char -1)
  18902. (when (memq (preceding-char) '(?\n ?\^M))
  18903. ;; leave blank line before heading
  18904. (forward-char -1)))))
  18905. (point))
  18906. (defun org-end-of-meta-data (&optional full)
  18907. "Skip planning line and properties drawer in current entry.
  18908. When optional argument FULL is non-nil, also skip empty lines,
  18909. clocking lines and regular drawers at the beginning of the
  18910. entry."
  18911. (org-back-to-heading t)
  18912. (forward-line)
  18913. (when (looking-at-p org-planning-line-re) (forward-line))
  18914. (when (looking-at org-property-drawer-re)
  18915. (goto-char (match-end 0))
  18916. (forward-line))
  18917. (when (and full (not (org-at-heading-p)))
  18918. (catch 'exit
  18919. (let ((end (save-excursion (outline-next-heading) (point)))
  18920. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18921. (while (not (eobp))
  18922. (cond ((looking-at-p org-drawer-regexp)
  18923. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18924. (forward-line)
  18925. (throw 'exit t)))
  18926. ((looking-at-p re) (forward-line))
  18927. (t (throw 'exit t))))))))
  18928. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18929. "Move forward to the ARG'th subheading at same level as this one.
  18930. Stop at the first and last subheadings of a superior heading.
  18931. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18932. non-nil it will also look at invisible ones."
  18933. (interactive "p")
  18934. (let ((backward? (and arg (< arg 0))))
  18935. (if (org-before-first-heading-p)
  18936. (if backward? (goto-char (point-min)) (outline-next-heading))
  18937. (org-back-to-heading invisible-ok)
  18938. (unless backward? (end-of-line)) ;do not match current headline
  18939. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18940. (f (if backward? #'re-search-backward #'re-search-forward))
  18941. (count (if arg (abs arg) 1))
  18942. (result (point)))
  18943. (while (and (> count 0)
  18944. (funcall f org-outline-regexp-bol nil 'move))
  18945. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18946. (cond ((< l level) (setq count 0))
  18947. ((and (= l level)
  18948. (or invisible-ok
  18949. (not (org-invisible-p
  18950. (line-beginning-position)))))
  18951. (cl-decf count)
  18952. (when (= l level) (setq result (point)))))))
  18953. (goto-char result))
  18954. (beginning-of-line))))
  18955. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18956. "Move backward to the ARG'th subheading at same level as this one.
  18957. Stop at the first and last subheadings of a superior heading."
  18958. (interactive "p")
  18959. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18960. (defun org-next-visible-heading (arg)
  18961. "Move to the next visible heading.
  18962. This function wraps `outline-next-visible-heading' with
  18963. `org-with-limited-levels' in order to skip over inline tasks and
  18964. respect customization of `org-odd-levels-only'."
  18965. (interactive "p")
  18966. (org-with-limited-levels
  18967. (outline-next-visible-heading arg)))
  18968. (defun org-previous-visible-heading (arg)
  18969. "Move to the previous visible heading.
  18970. This function wraps `outline-previous-visible-heading' with
  18971. `org-with-limited-levels' in order to skip over inline tasks and
  18972. respect customization of `org-odd-levels-only'."
  18973. (interactive "p")
  18974. (org-with-limited-levels
  18975. (outline-previous-visible-heading arg)))
  18976. (defun org-forward-paragraph ()
  18977. "Move forward to beginning of next paragraph or equivalent.
  18978. The function moves point to the beginning of the next visible
  18979. structural element, which can be a paragraph, a table, a list
  18980. item, etc. It also provides some special moves for convenience:
  18981. - On an affiliated keyword, jump to the beginning of the
  18982. relative element.
  18983. - On an item or a footnote definition, move to the second
  18984. element inside, if any.
  18985. - On a table or a property drawer, jump after it.
  18986. - On a verse or source block, stop after blank lines."
  18987. (interactive)
  18988. (unless (eobp)
  18989. (let* ((deactivate-mark nil)
  18990. (element (org-element-at-point))
  18991. (type (org-element-type element))
  18992. (post-affiliated (org-element-property :post-affiliated element))
  18993. (contents-begin (org-element-property :contents-begin element))
  18994. (contents-end (org-element-property :contents-end element))
  18995. (end (let ((end (org-element-property :end element)) (parent element))
  18996. (while (and (setq parent (org-element-property :parent parent))
  18997. (= (org-element-property :contents-end parent) end))
  18998. (setq end (org-element-property :end parent)))
  18999. end)))
  19000. (cond ((not element)
  19001. (skip-chars-forward " \r\t\n")
  19002. (or (eobp) (beginning-of-line)))
  19003. ;; On affiliated keywords, move to element's beginning.
  19004. ((< (point) post-affiliated)
  19005. (goto-char post-affiliated))
  19006. ;; At a table row, move to the end of the table. Similarly,
  19007. ;; at a node property, move to the end of the property
  19008. ;; drawer.
  19009. ((memq type '(node-property table-row))
  19010. (goto-char (org-element-property
  19011. :end (org-element-property :parent element))))
  19012. ((memq type '(property-drawer table)) (goto-char end))
  19013. ;; Consider blank lines as separators in verse and source
  19014. ;; blocks to ease editing.
  19015. ((memq type '(src-block verse-block))
  19016. (when (eq type 'src-block)
  19017. (setq contents-end
  19018. (save-excursion (goto-char end)
  19019. (skip-chars-backward " \r\t\n")
  19020. (line-beginning-position))))
  19021. (beginning-of-line)
  19022. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19023. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19024. (goto-char end)
  19025. (skip-chars-forward " \r\t\n")
  19026. (if (= (point) contents-end) (goto-char end)
  19027. (beginning-of-line))))
  19028. ;; With no contents, just skip element.
  19029. ((not contents-begin) (goto-char end))
  19030. ;; If contents are invisible, skip the element altogether.
  19031. ((org-invisible-p (line-end-position))
  19032. (cl-case type
  19033. (headline
  19034. (org-with-limited-levels (outline-next-visible-heading 1)))
  19035. ;; At a plain list, make sure we move to the next item
  19036. ;; instead of skipping the whole list.
  19037. (plain-list (forward-char)
  19038. (org-forward-paragraph))
  19039. (otherwise (goto-char end))))
  19040. ((>= (point) contents-end) (goto-char end))
  19041. ((>= (point) contents-begin)
  19042. ;; This can only happen on paragraphs and plain lists.
  19043. (cl-case type
  19044. (paragraph (goto-char end))
  19045. ;; At a plain list, try to move to second element in
  19046. ;; first item, if possible.
  19047. (plain-list (end-of-line)
  19048. (org-forward-paragraph))))
  19049. ;; When contents start on the middle of a line (e.g. in
  19050. ;; items and footnote definitions), try to reach first
  19051. ;; element starting after current line.
  19052. ((> (line-end-position) contents-begin)
  19053. (end-of-line)
  19054. (org-forward-paragraph))
  19055. (t (goto-char contents-begin))))))
  19056. (defun org-backward-paragraph ()
  19057. "Move backward to start of previous paragraph or equivalent.
  19058. The function moves point to the beginning of the current
  19059. structural element, which can be a paragraph, a table, a list
  19060. item, etc., or to the beginning of the previous visible one if
  19061. point is already there. It also provides some special moves for
  19062. convenience:
  19063. - On an affiliated keyword, jump to the first one.
  19064. - On a table or a property drawer, move to its beginning.
  19065. - On comment, example, export, src and verse blocks, stop
  19066. before blank lines."
  19067. (interactive)
  19068. (unless (bobp)
  19069. (let* ((deactivate-mark nil)
  19070. (element (org-element-at-point))
  19071. (type (org-element-type element))
  19072. (contents-end (org-element-property :contents-end element))
  19073. (post-affiliated (org-element-property :post-affiliated element))
  19074. (begin (org-element-property :begin element))
  19075. (special? ;blocks handled specially
  19076. (memq type '(comment-block example-block export-block src-block
  19077. verse-block)))
  19078. (contents-begin
  19079. (if special?
  19080. ;; These types have no proper contents. Fake line
  19081. ;; below the block opening line as contents beginning.
  19082. (save-excursion (goto-char begin) (line-beginning-position 2))
  19083. (org-element-property :contents-begin element))))
  19084. (cond
  19085. ((not element) (goto-char (point-min)))
  19086. ((= (point) begin)
  19087. (backward-char)
  19088. (org-backward-paragraph))
  19089. ((<= (point) post-affiliated) (goto-char begin))
  19090. ;; Special behavior: on a table or a property drawer, move to
  19091. ;; its beginning.
  19092. ((memq type '(node-property table-row))
  19093. (goto-char (org-element-property
  19094. :post-affiliated (org-element-property :parent element))))
  19095. (special?
  19096. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19097. ;; Inside a verse block, see blank lines as paragraph
  19098. ;; separators.
  19099. (let ((origin (point)))
  19100. (skip-chars-backward " \r\t\n" contents-begin)
  19101. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19102. (skip-chars-forward " \r\t\n" origin)
  19103. (if (= (point) origin) (goto-char contents-begin)
  19104. (beginning-of-line))))))
  19105. ((eq type 'paragraph) (goto-char contents-begin)
  19106. ;; When at first paragraph in an item or a footnote definition,
  19107. ;; move directly to beginning of line.
  19108. (let ((parent-contents
  19109. (org-element-property
  19110. :contents-begin (org-element-property :parent element))))
  19111. (when (and parent-contents (= parent-contents contents-begin))
  19112. (beginning-of-line))))
  19113. ;; At the end of a greater element, move to the beginning of
  19114. ;; the last element within.
  19115. ((and contents-end (>= (point) contents-end))
  19116. (goto-char (1- contents-end))
  19117. (org-backward-paragraph))
  19118. (t (goto-char (or post-affiliated begin))))
  19119. ;; Ensure we never leave point invisible.
  19120. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19121. (defun org-forward-element ()
  19122. "Move forward by one element.
  19123. Move to the next element at the same level, when possible."
  19124. (interactive)
  19125. (cond ((eobp) (user-error "Cannot move further down"))
  19126. ((org-with-limited-levels (org-at-heading-p))
  19127. (let ((origin (point)))
  19128. (goto-char (org-end-of-subtree nil t))
  19129. (unless (org-with-limited-levels (org-at-heading-p))
  19130. (goto-char origin)
  19131. (user-error "Cannot move further down"))))
  19132. (t
  19133. (let* ((elem (org-element-at-point))
  19134. (end (org-element-property :end elem))
  19135. (parent (org-element-property :parent elem)))
  19136. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19137. (goto-char (org-element-property :end parent)))
  19138. ((integer-or-marker-p end) (goto-char end))
  19139. (t (message "No element at point")))))))
  19140. (defun org-backward-element ()
  19141. "Move backward by one element.
  19142. Move to the previous element at the same level, when possible."
  19143. (interactive)
  19144. (cond ((bobp) (user-error "Cannot move further up"))
  19145. ((org-with-limited-levels (org-at-heading-p))
  19146. ;; At a headline, move to the previous one, if any, or stay
  19147. ;; here.
  19148. (let ((origin (point)))
  19149. (org-with-limited-levels (org-backward-heading-same-level 1))
  19150. ;; When current headline has no sibling above, move to its
  19151. ;; parent.
  19152. (when (= (point) origin)
  19153. (or (org-with-limited-levels (org-up-heading-safe))
  19154. (progn (goto-char origin)
  19155. (user-error "Cannot move further up"))))))
  19156. (t
  19157. (let* ((elem (org-element-at-point))
  19158. (beg (org-element-property :begin elem)))
  19159. (cond
  19160. ;; Move to beginning of current element if point isn't
  19161. ;; there already.
  19162. ((null beg) (message "No element at point"))
  19163. ((/= (point) beg) (goto-char beg))
  19164. (t (goto-char beg)
  19165. (skip-chars-backward " \r\t\n")
  19166. (unless (bobp)
  19167. (let ((prev (org-element-at-point)))
  19168. (goto-char (org-element-property :begin prev))
  19169. (while (and (setq prev (org-element-property :parent prev))
  19170. (<= (org-element-property :end prev) beg))
  19171. (goto-char (org-element-property :begin prev)))))))))))
  19172. (defun org-up-element ()
  19173. "Move to upper element."
  19174. (interactive)
  19175. (if (org-with-limited-levels (org-at-heading-p))
  19176. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19177. (let* ((elem (org-element-at-point))
  19178. (parent (org-element-property :parent elem)))
  19179. (if parent (goto-char (org-element-property :begin parent))
  19180. (if (org-with-limited-levels (org-before-first-heading-p))
  19181. (user-error "No surrounding element")
  19182. (org-with-limited-levels (org-back-to-heading)))))))
  19183. (defun org-down-element ()
  19184. "Move to inner element."
  19185. (interactive)
  19186. (let ((element (org-element-at-point)))
  19187. (cond
  19188. ((memq (org-element-type element) '(plain-list table))
  19189. (goto-char (org-element-property :contents-begin element))
  19190. (forward-char))
  19191. ((memq (org-element-type element) org-element-greater-elements)
  19192. ;; If contents are hidden, first disclose them.
  19193. (when (org-invisible-p (line-end-position)) (org-cycle))
  19194. (goto-char (or (org-element-property :contents-begin element)
  19195. (user-error "No content for this element"))))
  19196. (t (user-error "No inner element")))))
  19197. (defun org-drag-element-backward ()
  19198. "Move backward element at point."
  19199. (interactive)
  19200. (let ((elem (or (org-element-at-point)
  19201. (user-error "No element at point"))))
  19202. (if (eq (org-element-type elem) 'headline)
  19203. ;; Preserve point when moving a whole tree, even if point was
  19204. ;; on blank lines below the headline.
  19205. (let ((offset (skip-chars-backward " \t\n")))
  19206. (unwind-protect (org-move-subtree-up)
  19207. (forward-char (- offset))))
  19208. (let ((prev-elem
  19209. (save-excursion
  19210. (goto-char (org-element-property :begin elem))
  19211. (skip-chars-backward " \r\t\n")
  19212. (unless (bobp)
  19213. (let* ((beg (org-element-property :begin elem))
  19214. (prev (org-element-at-point))
  19215. (up prev))
  19216. (while (and (setq up (org-element-property :parent up))
  19217. (<= (org-element-property :end up) beg))
  19218. (setq prev up))
  19219. prev)))))
  19220. ;; Error out if no previous element or previous element is
  19221. ;; a parent of the current one.
  19222. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19223. (user-error "Cannot drag element backward")
  19224. (let ((pos (point)))
  19225. (org-element-swap-A-B prev-elem elem)
  19226. (goto-char (+ (org-element-property :begin prev-elem)
  19227. (- pos (org-element-property :begin elem))))))))))
  19228. (defun org-drag-element-forward ()
  19229. "Move forward element at point."
  19230. (interactive)
  19231. (let* ((pos (point))
  19232. (elem (or (org-element-at-point)
  19233. (user-error "No element at point"))))
  19234. (when (= (point-max) (org-element-property :end elem))
  19235. (user-error "Cannot drag element forward"))
  19236. (goto-char (org-element-property :end elem))
  19237. (let ((next-elem (org-element-at-point)))
  19238. (when (or (org-element-nested-p elem next-elem)
  19239. (and (eq (org-element-type next-elem) 'headline)
  19240. (not (eq (org-element-type elem) 'headline))))
  19241. (goto-char pos)
  19242. (user-error "Cannot drag element forward"))
  19243. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19244. ;; body's length (without final blanks) and by the length of
  19245. ;; blanks between ELEM and NEXT-ELEM.
  19246. (let ((size-next (- (save-excursion
  19247. (goto-char (org-element-property :end next-elem))
  19248. (skip-chars-backward " \r\t\n")
  19249. (forward-line)
  19250. ;; Small correction if buffer doesn't end
  19251. ;; with a newline character.
  19252. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19253. (org-element-property :begin next-elem)))
  19254. (size-blank (- (org-element-property :end elem)
  19255. (save-excursion
  19256. (goto-char (org-element-property :end elem))
  19257. (skip-chars-backward " \r\t\n")
  19258. (forward-line)
  19259. (point)))))
  19260. (org-element-swap-A-B elem next-elem)
  19261. (goto-char (+ pos size-next size-blank))))))
  19262. (defun org-drag-line-forward (arg)
  19263. "Drag the line at point ARG lines forward."
  19264. (interactive "p")
  19265. (dotimes (_ (abs arg))
  19266. (let ((c (current-column)))
  19267. (if (< 0 arg)
  19268. (progn
  19269. (beginning-of-line 2)
  19270. (transpose-lines 1)
  19271. (beginning-of-line 0))
  19272. (transpose-lines 1)
  19273. (beginning-of-line -1))
  19274. (org-move-to-column c))))
  19275. (defun org-drag-line-backward (arg)
  19276. "Drag the line at point ARG lines backward."
  19277. (interactive "p")
  19278. (org-drag-line-forward (- arg)))
  19279. (defun org-mark-element ()
  19280. "Put point at beginning of this element, mark at end.
  19281. Interactively, if this command is repeated or (in Transient Mark
  19282. mode) if the mark is active, it marks the next element after the
  19283. ones already marked."
  19284. (interactive)
  19285. (let (deactivate-mark)
  19286. (if (and (called-interactively-p 'any)
  19287. (or (and (eq last-command this-command) (mark t))
  19288. (and transient-mark-mode mark-active)))
  19289. (set-mark
  19290. (save-excursion
  19291. (goto-char (mark))
  19292. (goto-char (org-element-property :end (org-element-at-point)))))
  19293. (let ((element (org-element-at-point)))
  19294. (end-of-line)
  19295. (push-mark (org-element-property :end element) t t)
  19296. (goto-char (org-element-property :begin element))))))
  19297. (defun org-narrow-to-element ()
  19298. "Narrow buffer to current element."
  19299. (interactive)
  19300. (let ((elem (org-element-at-point)))
  19301. (cond
  19302. ((eq (car elem) 'headline)
  19303. (narrow-to-region
  19304. (org-element-property :begin elem)
  19305. (org-element-property :end elem)))
  19306. ((memq (car elem) org-element-greater-elements)
  19307. (narrow-to-region
  19308. (org-element-property :contents-begin elem)
  19309. (org-element-property :contents-end elem)))
  19310. (t
  19311. (narrow-to-region
  19312. (org-element-property :begin elem)
  19313. (org-element-property :end elem))))))
  19314. (defun org-transpose-element ()
  19315. "Transpose current and previous elements, keeping blank lines between.
  19316. Point is moved after both elements."
  19317. (interactive)
  19318. (org-skip-whitespace)
  19319. (let ((end (org-element-property :end (org-element-at-point))))
  19320. (org-drag-element-backward)
  19321. (goto-char end)))
  19322. (defun org-unindent-buffer ()
  19323. "Un-indent the visible part of the buffer.
  19324. Relative indentation (between items, inside blocks, etc.) isn't
  19325. modified."
  19326. (interactive)
  19327. (unless (eq major-mode 'org-mode)
  19328. (user-error "Cannot un-indent a buffer not in Org mode"))
  19329. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19330. (unindent-tree
  19331. (lambda (contents)
  19332. (dolist (element (reverse contents))
  19333. (if (memq (org-element-type element) '(headline section))
  19334. (funcall unindent-tree (org-element-contents element))
  19335. (save-excursion
  19336. (save-restriction
  19337. (narrow-to-region
  19338. (org-element-property :begin element)
  19339. (org-element-property :end element))
  19340. (org-do-remove-indentation))))))))
  19341. (funcall unindent-tree (org-element-contents parse-tree))))
  19342. (defun org-make-options-regexp (kwds &optional extra)
  19343. "Make a regular expression for keyword lines.
  19344. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19345. when non-nil, is a regexp matching keywords names."
  19346. (concat "^[ \t]*#\\+\\("
  19347. (regexp-opt kwds)
  19348. (and extra (concat (and kwds "\\|") extra))
  19349. "\\):[ \t]*\\(.*\\)"))
  19350. ;;; Conveniently switch to Info nodes
  19351. (defun org-info-find-node (&optional nodename)
  19352. "Find Info documentation NODENAME or Org documentation according context.
  19353. Started from `gnus-info-find-node'."
  19354. (interactive)
  19355. (Info-goto-node
  19356. (or nodename
  19357. (let ((default-org-info-node "(org) Top"))
  19358. (cond
  19359. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19360. ((eq 'org-mode major-mode)
  19361. (let* ((context (org-element-at-point))
  19362. (element-info-nodes ; compare to `org-element-all-elements'.
  19363. `((babel-call . "(org) Evaluating Code Blocks")
  19364. (center-block . "(org) Paragraphs")
  19365. (clock . ,default-org-info-node)
  19366. (comment . "(org) Comment Lines")
  19367. (comment-block . "(org) Comment Lines")
  19368. (diary-sexp . ,default-org-info-node)
  19369. (drawer . "(org) Drawers")
  19370. (dynamic-block . "(org) Dynamic Blocks")
  19371. (example-block . "(org) Literal Examples")
  19372. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19373. (fixed-width . ,default-org-info-node)
  19374. (footnote-definition . "(org) Creating Footnotes")
  19375. (headline . "(org) Document Structure")
  19376. (horizontal-rule . "(org) Built-in Table Editor")
  19377. (inlinetask . ,default-org-info-node)
  19378. (item . "(org) Plain Lists")
  19379. (keyword . "(org) Per-file keywords")
  19380. (latex-environment . "(org) LaTeX Export")
  19381. (node-property . "(org) Properties and Columns")
  19382. (paragraph . "(org) Paragraphs")
  19383. (plain-list . "(org) Plain Lists")
  19384. (planning . "(org) Deadlines and Scheduling")
  19385. (property-drawer . "(org) Properties and Columns")
  19386. (quote-block . "(org) Paragraphs")
  19387. (section . ,default-org-info-node)
  19388. (special-block . ,default-org-info-node)
  19389. (src-block . "(org) Working with Source Code")
  19390. (table . "(org) Tables")
  19391. (table-row . "(org) Tables")
  19392. (verse-block . "(org) Paragraphs"))))
  19393. (or (cdr (assoc (car context) element-info-nodes))
  19394. default-org-info-node)))
  19395. (t default-org-info-node))))))
  19396. ;;; Finish up
  19397. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19398. (lambda () (add-hook 'change-major-mode-hook
  19399. 'org-show-all 'append 'local)))
  19400. (provide 'org)
  19401. (run-hooks 'org-load-hook)
  19402. ;;; org.el ends here