org.el 816 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153
  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-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; URL: https://orgmode.org
  9. ;; Package-Requires: ((emacs "25.1"))
  10. ;; Version: 9.6-dev
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the Org mode website,
  55. ;; you can read the same text online as HTML. There is also an excellent
  56. ;; reference card made by Philip Rooke. This card can be found in the
  57. ;; doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'org-compat)
  67. (org-assert-version)
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (condition-case nil
  74. (load (concat (file-name-directory load-file-name)
  75. "org-loaddefs.el")
  76. nil t t t)
  77. (error
  78. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  79. (sit-for 3)
  80. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  81. (sit-for 3)))
  82. (eval-and-compile (require 'org-macs))
  83. (require 'org-compat)
  84. (require 'org-keys)
  85. (require 'ol)
  86. (require 'oc)
  87. (require 'org-table)
  88. (require 'org-fold)
  89. (require 'org-cycle)
  90. (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
  91. (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
  92. (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
  93. (defalias 'org-global-cycle #'org-cycle-global)
  94. (defalias 'org-overview #'org-cycle-overview)
  95. (defalias 'org-content #'org-cycle-content)
  96. (defalias 'org-reveal #'org-fold-reveal)
  97. (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
  98. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  99. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  100. (defvar org-outline-regexp "\\*+ "
  101. "Regexp to match Org headlines.")
  102. (defvar org-outline-regexp-bol "^\\*+ "
  103. "Regexp to match Org headlines.
  104. This is similar to `org-outline-regexp' but additionally makes
  105. sure that we are at the beginning of the line.")
  106. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  107. "Matches a headline, putting stars and text into groups.
  108. Stars are put in group 1 and the trimmed body in group 2.")
  109. (declare-function calendar-check-holidays "holidays" (date))
  110. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  111. (declare-function cdlatex-math-symbol "ext:cdlatex")
  112. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  113. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  114. (declare-function org-add-archive-files "org-archive" (files))
  115. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  116. (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
  117. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  118. (declare-function org-agenda-redo "org-agenda" (&optional all))
  119. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  120. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  121. (declare-function org-archive-subtree-default "org-archive" ())
  122. (declare-function org-archive-to-archive-sibling "org-archive" ())
  123. (declare-function org-attach "org-attach" ())
  124. (declare-function org-attach-dir "org-attach"
  125. (&optional create-if-not-exists-p no-fs-check))
  126. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  127. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  128. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  129. (declare-function org-clock-auto-clockout "org-clock" ())
  130. (declare-function org-clock-cancel "org-clock" ())
  131. (declare-function org-clock-display "org-clock" (&optional arg))
  132. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  133. (declare-function org-clock-goto "org-clock" (&optional select))
  134. (declare-function org-clock-in "org-clock" (&optional select start-time))
  135. (declare-function org-clock-in-last "org-clock" (&optional arg))
  136. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  137. (declare-function org-clock-out-if-current "org-clock" ())
  138. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  139. (declare-function org-clock-report "org-clock" (&optional arg))
  140. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  141. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  142. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  143. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  144. (declare-function org-clock-update-time-maybe "org-clock" ())
  145. (declare-function org-clocktable-shift "org-clock" (dir n))
  146. (declare-function org-columns-quit "org-colview" ())
  147. (declare-function org-columns-insert-dblock "org-colview" ())
  148. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  149. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  150. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  151. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  152. (declare-function org-element-cache-refresh "org-element" (pos))
  153. (declare-function org-element-cache-reset "org-element" (&optional all))
  154. (declare-function org-element-cache-map "org-element" (func &rest keys))
  155. (declare-function org-element-contents "org-element" (element))
  156. (declare-function org-element-context "org-element" (&optional element))
  157. (declare-function org-element-copy "org-element" (datum))
  158. (declare-function org-element-create "org-element" (type &optional props &rest children))
  159. (declare-function org-element-extract-element "org-element" (element))
  160. (declare-function org-element-insert-before "org-element" (element location))
  161. (declare-function org-element-interpret-data "org-element" (data))
  162. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  163. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  164. (declare-function org-element-link-parser "org-element" ())
  165. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  166. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  167. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  168. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  169. (declare-function org-element-property "org-element" (property element))
  170. (declare-function org-element-put-property "org-element" (element property value))
  171. (declare-function org-element-restriction "org-element" (element))
  172. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  173. (declare-function org-element-timestamp-parser "org-element" ())
  174. (declare-function org-element-type "org-element" (element))
  175. (declare-function org-element--cache-active-p "org-element" ())
  176. (declare-function org-export-dispatch "ox" (&optional arg))
  177. (declare-function org-export-get-backend "ox" (name))
  178. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  179. (declare-function org-feed-goto-inbox "org-feed" (feed))
  180. (declare-function org-feed-update-all "org-feed" ())
  181. (declare-function org-goto "org-goto" (&optional alternative-interface))
  182. (declare-function org-id-find-id-file "org-id" (id))
  183. (declare-function org-id-get-create "org-id" (&optional force))
  184. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  185. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  186. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  187. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  188. (declare-function org-num-mode "org-num" (&optional arg))
  189. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  190. (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
  191. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  192. (declare-function org-timer "org-timer" (&optional restart no-insert))
  193. (declare-function org-timer-item "org-timer" (&optional arg))
  194. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  195. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  196. (declare-function org-timer-start "org-timer" (&optional offset))
  197. (declare-function org-timer-stop "org-timer" ())
  198. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  199. (declare-function org-update-radio-target-regexp "ol" ())
  200. (defvar org-agenda-buffer-name)
  201. (defvar org-element-paragraph-separate)
  202. (defvar org-element-cache-map-continue-from)
  203. (defvar org-element--timestamp-regexp)
  204. (defvar org-indent-indentation-per-level)
  205. (defvar org-radio-target-regexp)
  206. (defvar org-target-link-regexp)
  207. (defvar org-target-regexp)
  208. (defvar org-id-overriding-file-name)
  209. ;; load languages based on value of `org-babel-load-languages'
  210. (defvar org-babel-load-languages)
  211. (defvar crm-separator) ; dynamically scoped param
  212. ;;;###autoload
  213. (defun org-babel-do-load-languages (sym value)
  214. "Load the languages defined in `org-babel-load-languages'."
  215. (set-default-toplevel-value sym value)
  216. (dolist (pair org-babel-load-languages)
  217. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  218. (if active
  219. (require (intern (concat "ob-" lang)))
  220. (fmakunbound
  221. (intern (concat "org-babel-execute:" lang)))
  222. (fmakunbound
  223. (intern (concat "org-babel-expand-body:" lang)))))))
  224. ;;;###autoload
  225. (defun org-babel-load-file (file &optional compile)
  226. "Load Emacs Lisp source code blocks in the Org FILE.
  227. This function exports the source code using `org-babel-tangle'
  228. and then loads the resulting file using `load-file'. With
  229. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  230. byte-compiled before it is loaded."
  231. (interactive "fFile to load: \nP")
  232. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  233. ;; Tangle only if the Org file is newer than the Elisp file.
  234. (unless (org-file-newer-than-p
  235. tangled-file
  236. (file-attribute-modification-time
  237. (file-attributes (file-truename file))))
  238. ;; Make sure that tangled file modification time is
  239. ;; updated even when `org-babel-tangle-file' does not make changes.
  240. ;; This avoids re-tangling changed FILE where the changes did
  241. ;; not affect the tangled code.
  242. (when (file-exists-p tangled-file)
  243. (set-file-times tangled-file))
  244. (org-babel-tangle-file file
  245. tangled-file
  246. (rx string-start
  247. (or "emacs-lisp" "elisp")
  248. string-end)))
  249. (if compile
  250. (progn
  251. (byte-compile-file tangled-file)
  252. (load-file (byte-compile-dest-file tangled-file))
  253. (message "Compiled and loaded %s" tangled-file))
  254. (load-file tangled-file)
  255. (message "Loaded %s" tangled-file))))
  256. (defcustom org-babel-load-languages '((emacs-lisp . t))
  257. "Languages which can be evaluated in Org buffers.
  258. \\<org-mode-map>
  259. This list can be used to load support for any of the available
  260. languages with babel support (see info node `(org) Languages'). Each
  261. language will depend on a different set of system executables and/or
  262. Emacs modes.
  263. When a language is \"loaded\", code blocks in that language can
  264. be evaluated with `org-babel-execute-src-block', which is bound
  265. by default to \\[org-ctrl-c-ctrl-c].
  266. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  267. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  268. default, only Emacs Lisp is loaded, since it has no specific
  269. requirement."
  270. :group 'org-babel
  271. :set 'org-babel-do-load-languages
  272. :version "24.1"
  273. :type '(alist :tag "Babel Languages"
  274. :key-type
  275. (choice
  276. (const :tag "Awk" awk)
  277. (const :tag "C" C)
  278. (const :tag "R" R)
  279. (const :tag "Calc" calc)
  280. (const :tag "Clojure" clojure)
  281. (const :tag "CSS" css)
  282. (const :tag "Ditaa" ditaa)
  283. (const :tag "Dot" dot)
  284. (const :tag "Emacs Lisp" emacs-lisp)
  285. (const :tag "Forth" forth)
  286. (const :tag "Fortran" fortran)
  287. (const :tag "Gnuplot" gnuplot)
  288. (const :tag "Haskell" haskell)
  289. (const :tag "Java" java)
  290. (const :tag "Javascript" js)
  291. (const :tag "LaTeX" latex)
  292. (const :tag "Lilypond" lilypond)
  293. (const :tag "Lisp" lisp)
  294. (const :tag "Makefile" makefile)
  295. (const :tag "Maxima" maxima)
  296. (const :tag "Matlab" matlab)
  297. (const :tag "Ocaml" ocaml)
  298. (const :tag "Octave" octave)
  299. (const :tag "Org" org)
  300. (const :tag "Perl" perl)
  301. (const :tag "Pico Lisp" picolisp)
  302. (const :tag "PlantUML" plantuml)
  303. (const :tag "Python" python)
  304. (const :tag "Ruby" ruby)
  305. (const :tag "Sass" sass)
  306. (const :tag "Scala" scala)
  307. (const :tag "Scheme" scheme)
  308. (const :tag "Screen" screen)
  309. (const :tag "Shell Script" shell)
  310. (const :tag "Sql" sql)
  311. (const :tag "Sqlite" sqlite)
  312. (const :tag "Stan" stan))
  313. :value-type (boolean :tag "Activate" :value t)))
  314. ;;;; Customization variables
  315. (defcustom org-clone-delete-id nil
  316. "Remove ID property of clones of a subtree.
  317. When non-nil, clones of a subtree don't inherit the ID property.
  318. Otherwise they inherit the ID property with a new unique
  319. identifier."
  320. :type 'boolean
  321. :version "24.1"
  322. :group 'org-id)
  323. ;;; Version
  324. (org-check-version)
  325. ;;;###autoload
  326. (defun org-version (&optional here full message)
  327. "Show the Org version.
  328. Interactively, or when MESSAGE is non-nil, show it in echo area.
  329. With prefix argument, or when HERE is non-nil, insert it at point.
  330. In non-interactive uses, a reduced version string is output unless
  331. FULL is given."
  332. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  333. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  334. (save-load-suffixes load-suffixes)
  335. (load-suffixes (list ".el"))
  336. (org-install-dir
  337. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  338. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  339. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  340. (let* ((load-suffixes save-load-suffixes)
  341. (release (org-release))
  342. (git-version (org-git-version))
  343. (version (format "Org mode version %s (%s @ %s)"
  344. release
  345. git-version
  346. (if org-install-dir
  347. (if (string= org-dir org-install-dir)
  348. org-install-dir
  349. (concat "mixed installation! "
  350. org-install-dir
  351. " and "
  352. org-dir))
  353. "org-loaddefs.el can not be found!")))
  354. (version1 (if full version release)))
  355. (when here (insert version1))
  356. (when message (message "%s" version1))
  357. version1)))
  358. (defconst org-version (org-version))
  359. ;;; Syntax Constants
  360. ;;;; Comments
  361. (defconst org-comment-regexp
  362. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  363. "Regular expression for comment lines.")
  364. ;;;; Keyword
  365. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  366. "Regular expression for keyword-lines.")
  367. ;;;; Block
  368. (defconst org-block-regexp
  369. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  370. "Regular expression for hiding blocks.")
  371. (defconst org-dblock-start-re
  372. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  373. "Matches the start line of a dynamic block, with parameters.")
  374. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  375. "Matches the end of a dynamic block.")
  376. ;;;; Timestamp
  377. (defconst org-ts--internal-regexp
  378. (rx (seq
  379. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  380. (optional " " (*? nonl))))
  381. "Regular expression matching the innards of a time stamp.")
  382. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  383. "Regular expression for fast time stamp matching.")
  384. (defconst org-ts-regexp-inactive
  385. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  386. "Regular expression for fast inactive time stamp matching.")
  387. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  388. "Regular expression for fast time stamp matching.")
  389. (defconst org-ts-regexp0
  390. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  391. "Regular expression matching time strings for analysis.
  392. This one does not require the space after the date, so it can be used
  393. on a string that terminates immediately after the date.")
  394. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  395. "Regular expression matching time strings for analysis.")
  396. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  397. "Regular expression matching time stamps, with groups.")
  398. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  399. "Regular expression matching time stamps (also [..]), with groups.")
  400. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  401. "Regular expression matching a time stamp range.")
  402. (defconst org-tr-regexp-both
  403. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  404. "Regular expression matching a time stamp range.")
  405. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  406. org-ts-regexp "\\)?")
  407. "Regular expression matching a time stamp or time stamp range.")
  408. (defconst org-tsr-regexp-both
  409. (concat org-ts-regexp-both "\\(--?-?"
  410. org-ts-regexp-both "\\)?")
  411. "Regular expression matching a time stamp or time stamp range.
  412. The time stamps may be either active or inactive.")
  413. (defconst org-repeat-re
  414. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  415. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  416. "Regular expression for specifying repeated events.
  417. After a match, group 1 contains the repeat expression.")
  418. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  419. "Formats for `format-time-string' which are used for time stamps.")
  420. ;;;; Clock and Planning
  421. (defconst org-clock-string "CLOCK:"
  422. "String used as prefix for timestamps clocking work hours on an item.")
  423. (defvar org-closed-string "CLOSED:"
  424. "String used as the prefix for timestamps logging closing a TODO entry.")
  425. (defvar org-deadline-string "DEADLINE:"
  426. "String to mark deadline entries.
  427. \\<org-mode-map>
  428. A deadline is this string, followed by a time stamp. It must be
  429. a word, terminated by a colon. You can insert a schedule keyword
  430. and a timestamp with `\\[org-deadline]'.")
  431. (defvar org-scheduled-string "SCHEDULED:"
  432. "String to mark scheduled TODO entries.
  433. \\<org-mode-map>
  434. A schedule is this string, followed by a time stamp. It must be
  435. a word, terminated by a colon. You can insert a schedule keyword
  436. and a timestamp with `\\[org-schedule]'.")
  437. (defconst org-ds-keyword-length
  438. (+ 2
  439. (apply #'max
  440. (mapcar #'length
  441. (list org-deadline-string org-scheduled-string
  442. org-clock-string org-closed-string))))
  443. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  444. (defconst org-planning-line-re
  445. (concat "^[ \t]*"
  446. (regexp-opt
  447. (list org-closed-string org-deadline-string org-scheduled-string)
  448. t))
  449. "Matches a line with planning info.
  450. Matched keyword is in group 1.")
  451. (defconst org-clock-line-re
  452. (concat "^[ \t]*" org-clock-string)
  453. "Matches a line with clock info.")
  454. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  455. "Matches the DEADLINE keyword.")
  456. (defconst org-deadline-time-regexp
  457. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  458. "Matches the DEADLINE keyword together with a time stamp.")
  459. (defconst org-deadline-time-hour-regexp
  460. (concat "\\<" org-deadline-string
  461. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  462. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  463. (defconst org-deadline-line-regexp
  464. (concat "\\<\\(" org-deadline-string "\\).*")
  465. "Matches the DEADLINE keyword and the rest of the line.")
  466. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  467. "Matches the SCHEDULED keyword.")
  468. (defconst org-scheduled-time-regexp
  469. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  470. "Matches the SCHEDULED keyword together with a time stamp.")
  471. (defconst org-scheduled-time-hour-regexp
  472. (concat "\\<" org-scheduled-string
  473. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  474. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  475. (defconst org-closed-time-regexp
  476. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  477. "Matches the CLOSED keyword together with a time stamp.")
  478. (defconst org-keyword-time-regexp
  479. (concat "\\<"
  480. (regexp-opt
  481. (list org-scheduled-string org-deadline-string org-closed-string
  482. org-clock-string)
  483. t)
  484. " *[[<]\\([^]>]+\\)[]>]")
  485. "Matches any of the 4 keywords, together with the time stamp.")
  486. (defconst org-keyword-time-not-clock-regexp
  487. (concat
  488. "\\<"
  489. (regexp-opt
  490. (list org-scheduled-string org-deadline-string org-closed-string) t)
  491. " *[[<]\\([^]>]+\\)[]>]")
  492. "Matches any of the 3 keywords, together with the time stamp.")
  493. (defconst org-all-time-keywords
  494. (mapcar (lambda (w) (substring w 0 -1))
  495. (list org-scheduled-string org-deadline-string
  496. org-clock-string org-closed-string))
  497. "List of time keywords.")
  498. ;;;; Drawer
  499. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  500. "Matches first or last line of a hidden block.
  501. Group 1 contains drawer's name or \"END\".")
  502. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  503. "Regular expression matching the first line of a property drawer.")
  504. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  505. "Regular expression matching the last line of a property drawer.")
  506. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  507. "Regular expression matching the first line of a clock drawer.")
  508. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  509. "Regular expression matching the last line of a clock drawer.")
  510. (defconst org-logbook-drawer-re
  511. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  512. (*? (0+ nonl) "\n")
  513. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  514. "Matches an entire LOGBOOK drawer.")
  515. (defconst org-property-drawer-re
  516. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  517. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  518. "[ \t]*:END:[ \t]*$")
  519. "Matches an entire property drawer.")
  520. (defconst org-clock-drawer-re
  521. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  522. org-clock-drawer-end-re "\\)\n?")
  523. "Matches an entire clock drawer.")
  524. ;;;; Headline
  525. (defconst org-heading-keyword-regexp-format
  526. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  527. "Printf format for a regexp matching a headline with some keyword.
  528. This regexp will match the headline of any node which has the
  529. exact keyword that is put into the format. The keyword isn't in
  530. any group by default, but the stars and the body are.")
  531. (defconst org-heading-keyword-maybe-regexp-format
  532. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  533. "Printf format for a regexp matching a headline, possibly with some keyword.
  534. This regexp can match any headline with the specified keyword, or
  535. without a keyword. The keyword isn't in any group by default,
  536. but the stars and the body are.")
  537. (defconst org-archive-tag "ARCHIVE"
  538. "The tag that marks a subtree as archived.
  539. An archived subtree does not open during visibility cycling, and does
  540. not contribute to the agenda listings.")
  541. (defconst org-tag-re "[[:alnum:]_@#%]+"
  542. "Regexp matching a single tag.")
  543. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  544. "Regexp matching the tag group at the end of a line, with leading spaces.
  545. Tags are stored in match group 1. Match group 2 stores the tags
  546. without the enclosing colons.")
  547. (defconst org-tag-line-re
  548. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  549. "Regexp matching tags in a headline.
  550. Tags are stored in match group 1. Match group 2 stores the tags
  551. without the enclosing colons.")
  552. (eval-and-compile
  553. (defconst org-comment-string "COMMENT"
  554. "Entries starting with this keyword will never be exported.
  555. \\<org-mode-map>
  556. An entry can be toggled between COMMENT and normal with
  557. `\\[org-toggle-comment]'."))
  558. ;;;; LaTeX Environments and Fragments
  559. (defconst org-latex-regexps
  560. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  561. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  562. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  563. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  564. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  565. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  566. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  567. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  568. "Regular expressions for matching embedded LaTeX.")
  569. ;;;; Node Property
  570. (defconst org-effort-property "Effort"
  571. "The property that is being used to keep track of effort estimates.
  572. Effort estimates given in this property need to be in the format
  573. defined in org-duration.el.")
  574. ;;; The custom variables
  575. (defgroup org nil
  576. "Outline-based notes management and organizer."
  577. :tag "Org"
  578. :group 'outlines
  579. :group 'calendar)
  580. (defcustom org-mode-hook nil
  581. "Mode hook for Org mode, run after the mode was turned on."
  582. :group 'org
  583. :type 'hook)
  584. (defcustom org-load-hook nil
  585. "Hook that is run after org.el has been loaded."
  586. :group 'org
  587. :type 'hook)
  588. (make-obsolete-variable
  589. 'org-load-hook
  590. "use `with-eval-after-load' instead." "9.5")
  591. (defcustom org-log-buffer-setup-hook nil
  592. "Hook that is run after an Org log buffer is created."
  593. :group 'org
  594. :version "24.1"
  595. :type 'hook)
  596. (defvar org-modules) ; defined below
  597. (defvar org-modules-loaded nil
  598. "Have the modules been loaded already?")
  599. ;;;###autoload
  600. (defun org-load-modules-maybe (&optional force)
  601. "Load all extensions listed in `org-modules'."
  602. (when (or force (not org-modules-loaded))
  603. (dolist (ext org-modules)
  604. (condition-case nil (require ext)
  605. (error (message "Problems while trying to load feature `%s'" ext))))
  606. (setq org-modules-loaded t)))
  607. (defun org-set-modules (var value)
  608. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  609. (set-default-toplevel-value var value)
  610. (when (featurep 'org)
  611. (org-load-modules-maybe 'force)
  612. (org-element-cache-reset 'all)))
  613. (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  614. "Modules that should always be loaded together with org.el.
  615. If a description starts with <C>, the file is not part of Emacs and Org mode,
  616. so loading it will require that you have properly installed org-contrib
  617. package from NonGNU Emacs Lisp Package Archive
  618. https://elpa.nongnu.org/nongnu/org-contrib.html
  619. You can also use this system to load external packages (i.e. neither Org
  620. core modules, nor org-contrib modules). Just add symbols
  621. to the end of the list. If the package is called org-xyz.el, then you need
  622. to add the symbol `xyz', and the package must have a call to:
  623. (provide \\='org-xyz)
  624. For export specific modules, see also `org-export-backends'."
  625. :group 'org
  626. :set 'org-set-modules
  627. :package-version '(Org . "9.5")
  628. :type
  629. '(set :greedy t
  630. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  631. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  632. (const :tag " crypt: Encryption of subtrees" org-crypt)
  633. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  634. (const :tag " docview: Links to Docview buffers" ol-docview)
  635. (const :tag " doi: Links to DOI references" ol-doi)
  636. (const :tag " eww: Store link to URL of Eww" ol-eww)
  637. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  638. (const :tag " habit: Track your consistency with habits" org-habit)
  639. (const :tag " id: Global IDs for identifying entries" org-id)
  640. (const :tag " info: Links to Info nodes" ol-info)
  641. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  642. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  643. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  644. (const :tag " mouse: Additional mouse support" org-mouse)
  645. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  646. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  647. (const :tag " tempo: Fast completion for structures" org-tempo)
  648. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  649. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  650. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  651. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  652. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  653. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  654. (const :tag "C collector: Collect properties into tables" org-collector)
  655. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  656. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  657. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  658. (const :tag "C eval: Include command output as text" org-eval)
  659. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  660. (const :tag "C git-link: Links to specific file version" ol-git-link)
  661. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  662. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  663. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  664. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  665. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  666. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  667. (const :tag "C man: Links to man pages in Org mode" ol-man)
  668. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  669. (const :tag "C notify: Notifications for Org mode" org-notify)
  670. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  671. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  672. (const :tag "C registry: A registry for Org links" org-registry)
  673. (const :tag "C screen: Visit screen sessions through links" org-screen)
  674. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  675. (const :tag "C secretary: Team management with Org" org-secretary)
  676. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  677. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  678. (const :tag "C track: Keep up with Org mode development" org-track)
  679. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  680. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  681. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  682. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  683. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  684. (defvar org-export-registered-backends) ; From ox.el.
  685. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  686. (declare-function org-export-backend-name "ox" (backend) t)
  687. (defcustom org-export-backends '(ascii html icalendar latex odt)
  688. "List of export back-ends that should be always available.
  689. If a description starts with <C>, the file is not part of Emacs and Org mode,
  690. so loading it will require that you have properly installed org-contrib
  691. package from NonGNU Emacs Lisp Package Archive
  692. https://elpa.nongnu.org/nongnu/org-contrib.html
  693. Unlike to `org-modules', libraries in this list will not be
  694. loaded along with Org, but only once the export framework is
  695. needed.
  696. This variable needs to be set before org.el is loaded. If you
  697. need to make a change while Emacs is running, use the customize
  698. interface or run the following code, where VAL stands for the new
  699. value of the variable, after updating it:
  700. (progn
  701. (setq org-export-registered-backends
  702. (cl-remove-if-not
  703. (lambda (backend)
  704. (let ((name (org-export-backend-name backend)))
  705. (or (memq name val)
  706. (catch \\='parentp
  707. (dolist (b val)
  708. (and (org-export-derived-backend-p b name)
  709. (throw \\='parentp t)))))))
  710. org-export-registered-backends))
  711. (let ((new-list (mapcar #\\='org-export-backend-name
  712. org-export-registered-backends)))
  713. (dolist (backend val)
  714. (cond
  715. ((not (load (format \"ox-%s\" backend) t t))
  716. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  717. backend))
  718. ((not (memq backend new-list)) (push backend new-list))))
  719. (set-default \\='org-export-backends new-list)))
  720. Adding a back-end to this list will also pull the back-end it
  721. depends on, if any."
  722. :group 'org
  723. :group 'org-export
  724. :version "26.1"
  725. :package-version '(Org . "9.0")
  726. :initialize 'custom-initialize-set
  727. :set (lambda (var val)
  728. (if (not (featurep 'ox)) (set-default-toplevel-value var val)
  729. ;; Any back-end not required anymore (not present in VAL and not
  730. ;; a parent of any back-end in the new value) is removed from the
  731. ;; list of registered back-ends.
  732. (setq org-export-registered-backends
  733. (cl-remove-if-not
  734. (lambda (backend)
  735. (let ((name (org-export-backend-name backend)))
  736. (or (memq name val)
  737. (catch 'parentp
  738. (dolist (b val)
  739. (and (org-export-derived-backend-p b name)
  740. (throw 'parentp t)))))))
  741. org-export-registered-backends))
  742. ;; Now build NEW-LIST of both new back-ends and required
  743. ;; parents.
  744. (let ((new-list (mapcar #'org-export-backend-name
  745. org-export-registered-backends)))
  746. (dolist (backend val)
  747. (cond
  748. ((not (load (format "ox-%s" backend) t t))
  749. (message "Problems while trying to load export back-end `%s'"
  750. backend))
  751. ((not (memq backend new-list)) (push backend new-list))))
  752. ;; Set VAR to that list with fixed dependencies.
  753. (set-default-toplevel-value var new-list))))
  754. :type '(set :greedy t
  755. (const :tag " ascii Export buffer to ASCII format" ascii)
  756. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  757. (const :tag " html Export buffer to HTML format" html)
  758. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  759. (const :tag " latex Export buffer to LaTeX format" latex)
  760. (const :tag " man Export buffer to MAN format" man)
  761. (const :tag " md Export buffer to Markdown format" md)
  762. (const :tag " odt Export buffer to ODT format" odt)
  763. (const :tag " org Export buffer to Org format" org)
  764. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  765. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  766. (const :tag "C deck Export buffer to deck.js presentations" deck)
  767. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  768. (const :tag "C groff Export buffer to Groff format" groff)
  769. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  770. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  771. (const :tag "C s5 Export buffer to s5 presentations" s5)
  772. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  773. (eval-after-load 'ox
  774. '(dolist (backend org-export-backends)
  775. (condition-case nil (require (intern (format "ox-%s" backend)))
  776. (error (message "Problems while trying to load export back-end `%s'"
  777. backend)))))
  778. (defcustom org-support-shift-select nil
  779. "Non-nil means make shift-cursor commands select text when possible.
  780. \\<org-mode-map>
  781. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  782. start selecting a region, or enlarge regions started in this way.
  783. In Org mode, in special contexts, these same keys are used for
  784. other purposes, important enough to compete with shift selection.
  785. Org tries to balance these needs by supporting `shift-select-mode'
  786. outside these special contexts, under control of this variable.
  787. The default of this variable is nil, to avoid confusing behavior. Shifted
  788. cursor keys will then execute Org commands in the following contexts:
  789. - on a headline, changing TODO state (left/right) and priority (up/down)
  790. - on a time stamp, changing the time
  791. - in a plain list item, changing the bullet type
  792. - in a property definition line, switching between allowed values
  793. - in the BEGIN line of a clock table (changing the time block).
  794. - in a table, moving the cell in the specified direction.
  795. Outside these contexts, the commands will throw an error.
  796. When this variable is t and the cursor is not in a special
  797. context, Org mode will support shift-selection for making and
  798. enlarging regions. To make this more effective, the bullet
  799. cycling will no longer happen anywhere in an item line, but only
  800. if the cursor is exactly on the bullet.
  801. If you set this variable to the symbol `always', then the keys
  802. will not be special in headlines, property lines, item lines, and
  803. table cells, to make shift selection work there as well. If this is
  804. what you want, you can use the following alternative commands:
  805. `\\[org-todo]' and `\\[org-priority]' \
  806. to change TODO state and priority,
  807. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  808. can be used to switch TODO sets,
  809. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  810. and properties can be edited by hand or in column view.
  811. However, when the cursor is on a timestamp, shift-cursor commands
  812. will still edit the time stamp - this is just too good to give up."
  813. :group 'org
  814. :type '(choice
  815. (const :tag "Never" nil)
  816. (const :tag "When outside special context" t)
  817. (const :tag "Everywhere except timestamps" always)))
  818. (defcustom org-loop-over-headlines-in-active-region t
  819. "Shall some commands act upon headlines in the active region?
  820. When set to t, some commands will be performed in all headlines
  821. within the active region.
  822. When set to `start-level', some commands will be performed in all
  823. headlines within the active region, provided that these headlines
  824. are of the same level than the first one.
  825. When set to a string, those commands will be performed on the
  826. matching headlines within the active region. Such string must be
  827. a tags/property/todo match as it is used in the agenda tags view.
  828. The list of commands is: `org-schedule', `org-deadline',
  829. `org-todo', `org-set-tags-command', `org-archive-subtree',
  830. `org-archive-set-tag', `org-toggle-archive-tag' and
  831. `org-archive-to-archive-sibling'. The archiving commands skip
  832. already archived entries.
  833. See `org-agenda-loop-over-headlines-in-active-region' for the
  834. equivalent option for agenda views."
  835. :type '(choice (const :tag "Don't loop" nil)
  836. (const :tag "All headlines in active region" t)
  837. (const :tag "In active region, headlines at the same level than the first one" start-level)
  838. (string :tag "Tags/Property/Todo matcher"))
  839. :package-version '(Org . "9.4")
  840. :group 'org-todo
  841. :group 'org-archive)
  842. (defcustom org-startup-folded 'showeverything
  843. "Non-nil means entering Org mode will switch to OVERVIEW.
  844. This can also be configured on a per-file basis by adding one of
  845. the following lines anywhere in the buffer:
  846. #+STARTUP: fold (or `overview', this is equivalent)
  847. #+STARTUP: nofold (or `showall', this is equivalent)
  848. #+STARTUP: content
  849. #+STARTUP: show<n>levels (<n> = 2..5)
  850. #+STARTUP: showeverything
  851. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  852. to ignore this option when Org opens agenda files for the first
  853. time."
  854. :group 'org-startup
  855. :package-version '(Org . "9.4")
  856. :type '(choice
  857. (const :tag "nofold: show all" nil)
  858. (const :tag "fold: overview" t)
  859. (const :tag "fold: show two levels" show2levels)
  860. (const :tag "fold: show three levels" show3levels)
  861. (const :tag "fold: show four levels" show4evels)
  862. (const :tag "fold: show five levels" show5levels)
  863. (const :tag "content: all headlines" content)
  864. (const :tag "show everything, even drawers" showeverything)))
  865. (defcustom org-startup-truncated t
  866. "Non-nil means entering Org mode will set `truncate-lines'.
  867. This is useful since some lines containing links can be very long and
  868. uninteresting. Also tables look terrible when wrapped.
  869. The variable `org-startup-truncated' allows to configure
  870. truncation for Org mode different to the other modes that use the
  871. variable `truncate-lines' and as a shortcut instead of putting
  872. the variable `truncate-lines' into the `org-mode-hook'. If one
  873. wants to configure truncation for Org mode not statically but
  874. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  875. the variable `truncate-lines' has to be used because in such a
  876. case it is too late to set the variable `org-startup-truncated'."
  877. :group 'org-startup
  878. :type 'boolean)
  879. (defcustom org-startup-indented nil
  880. "Non-nil means turn on `org-indent-mode' on startup.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: indent
  884. #+STARTUP: noindent"
  885. :group 'org-structure
  886. :type '(choice
  887. (const :tag "Not" nil)
  888. (const :tag "Globally (slow on startup in large files)" t)))
  889. (defcustom org-startup-numerated nil
  890. "Non-nil means turn on `org-num-mode' on startup.
  891. This can also be configured on a per-file basis by adding one of
  892. the following lines anywhere in the buffer:
  893. #+STARTUP: num
  894. #+STARTUP: nonum"
  895. :group 'org-structure
  896. :package-version '(Org . "9.4")
  897. :type '(choice
  898. (const :tag "Not" nil)
  899. (const :tag "Globally" t)))
  900. (defcustom org-use-sub-superscripts t
  901. "Non-nil means interpret \"_\" and \"^\" for display.
  902. If you want to control how Org exports those characters, see
  903. `org-export-with-sub-superscripts'.
  904. When this option is turned on, you can use TeX-like syntax for
  905. sub- and superscripts within the buffer. Several characters after
  906. \"_\" or \"^\" will be considered as a single item - so grouping
  907. with {} is normally not needed. For example, the following things
  908. will be parsed as single sub- or superscripts:
  909. 10^24 or 10^tau several digits will be considered 1 item.
  910. 10^-12 or 10^-tau a leading sign with digits or a word
  911. x^2-y^3 will be read as x^2 - y^3, because items are
  912. terminated by almost any nonword/nondigit char.
  913. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  914. Still, ambiguity is possible. So when in doubt, use {} to enclose
  915. the sub/superscript. If you set this variable to the symbol `{}',
  916. the braces are *required* in order to trigger interpretations as
  917. sub/superscript. This can be helpful in documents that need \"_\"
  918. frequently in plain text."
  919. :group 'org-startup
  920. :version "24.4"
  921. :package-version '(Org . "8.0")
  922. :type '(choice
  923. (const :tag "Always interpret" t)
  924. (const :tag "Only with braces" {})
  925. (const :tag "Never interpret" nil)))
  926. (defcustom org-startup-with-beamer-mode nil
  927. "Non-nil means turn on `org-beamer-mode' on startup.
  928. This can also be configured on a per-file basis by adding one of
  929. the following lines anywhere in the buffer:
  930. #+STARTUP: beamer"
  931. :group 'org-startup
  932. :version "24.1"
  933. :type 'boolean)
  934. (defcustom org-startup-align-all-tables nil
  935. "Non-nil means align all tables when visiting a file.
  936. This can also be configured on a per-file basis by adding one of
  937. the following lines anywhere in the buffer:
  938. #+STARTUP: align
  939. #+STARTUP: noalign"
  940. :group 'org-startup
  941. :type 'boolean)
  942. (defcustom org-startup-shrink-all-tables nil
  943. "Non-nil means shrink all table columns with a width cookie.
  944. This can also be configured on a per-file basis by adding one of
  945. the following lines anywhere in the buffer:
  946. #+STARTUP: shrink"
  947. :group 'org-startup
  948. :type 'boolean
  949. :version "27.1"
  950. :package-version '(Org . "9.2")
  951. :safe #'booleanp)
  952. (defcustom org-startup-with-inline-images nil
  953. "Non-nil means show inline images when loading a new Org file.
  954. This can also be configured on a per-file basis by adding one of
  955. the following lines anywhere in the buffer:
  956. #+STARTUP: inlineimages
  957. #+STARTUP: noinlineimages"
  958. :group 'org-startup
  959. :version "24.1"
  960. :type 'boolean)
  961. (defcustom org-startup-with-latex-preview nil
  962. "Non-nil means preview LaTeX fragments when loading a new Org file.
  963. This can also be configured on a per-file basis by adding one of
  964. the following lines anywhere in the buffer:
  965. #+STARTUP: latexpreview
  966. #+STARTUP: nolatexpreview"
  967. :group 'org-startup
  968. :version "24.4"
  969. :package-version '(Org . "8.0")
  970. :type 'boolean)
  971. (defcustom org-insert-mode-line-in-empty-file nil
  972. "Non-nil means insert the first line setting Org mode in empty files.
  973. When the function `org-mode' is called interactively in an empty file, this
  974. normally means that the file name does not automatically trigger Org mode.
  975. To ensure that the file will always be in Org mode in the future, a
  976. line enforcing Org mode will be inserted into the buffer, if this option
  977. has been set."
  978. :group 'org-startup
  979. :type 'boolean)
  980. (defcustom org-ellipsis nil
  981. "The ellipsis to use in the Org mode outline.
  982. When nil, just use the standard three dots. When a non-empty string,
  983. use that string instead.
  984. The change affects only Org mode (which will then use its own display table).
  985. Changing this requires executing `\\[org-mode]' in a buffer to become
  986. effective. It cannot be set as a local variable."
  987. :group 'org-startup
  988. :type '(choice (const :tag "Default" nil)
  989. (string :tag "String" :value "...#")))
  990. (defvar org-display-table nil
  991. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  992. (defcustom org-directory "~/org"
  993. "Directory with Org files.
  994. This is just a default location to look for Org files. There is no need
  995. at all to put your files into this directory. It is used in the
  996. following situations:
  997. 1. When a capture template specifies a target file that is not an
  998. absolute path. The path will then be interpreted relative to
  999. `org-directory'
  1000. 2. When the value of variable `org-agenda-files' is a single file, any
  1001. relative paths in this file will be taken as relative to
  1002. `org-directory'."
  1003. :group 'org-refile
  1004. :group 'org-capture
  1005. :type 'directory)
  1006. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1007. "Default target for storing notes.
  1008. Used as a fall back file for org-capture.el, for templates that
  1009. do not specify a target file."
  1010. :group 'org-refile
  1011. :group 'org-capture
  1012. :type 'file)
  1013. (defcustom org-reverse-note-order nil
  1014. "Non-nil means store new notes at the beginning of a file or entry.
  1015. When nil, new notes will be filed to the end of a file or entry.
  1016. This can also be a list with cons cells of regular expressions that
  1017. are matched against file names, and values."
  1018. :group 'org-capture
  1019. :group 'org-refile
  1020. :type '(choice
  1021. (const :tag "Reverse always" t)
  1022. (const :tag "Reverse never" nil)
  1023. (repeat :tag "By file name regexp"
  1024. (cons regexp boolean))))
  1025. (defgroup org-keywords nil
  1026. "Keywords in Org mode."
  1027. :tag "Org Keywords"
  1028. :group 'org)
  1029. (defcustom org-closed-keep-when-no-todo nil
  1030. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1031. :group 'org-todo
  1032. :group 'org-keywords
  1033. :version "24.4"
  1034. :package-version '(Org . "8.0")
  1035. :type 'boolean)
  1036. (defgroup org-structure nil
  1037. "Options concerning the general structure of Org files."
  1038. :tag "Org Structure"
  1039. :group 'org)
  1040. (defcustom org-indirect-buffer-display 'other-window
  1041. "How should indirect tree buffers be displayed?
  1042. This applies to indirect buffers created with the commands
  1043. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1044. Valid values are:
  1045. current-window Display in the current window
  1046. other-window Just display in another window.
  1047. dedicated-frame Create one new frame, and re-use it each time.
  1048. new-frame Make a new frame each time. Note that in this case
  1049. previously-made indirect buffers are kept, and you need to
  1050. kill these buffers yourself."
  1051. :group 'org-structure
  1052. :group 'org-agenda-windows
  1053. :type '(choice
  1054. (const :tag "In current window" current-window)
  1055. (const :tag "In current frame, other window" other-window)
  1056. (const :tag "Each time a new frame" new-frame)
  1057. (const :tag "One dedicated frame" dedicated-frame)))
  1058. (defconst org-file-apps-gnu
  1059. '((remote . emacs)
  1060. (system . mailcap)
  1061. (t . mailcap))
  1062. "Default file applications on a UNIX or GNU/Linux system.
  1063. See `org-file-apps'.")
  1064. (defconst org-file-apps-macos
  1065. '((remote . emacs)
  1066. (system . "open %s")
  1067. ("ps.gz" . "gv %s")
  1068. ("eps.gz" . "gv %s")
  1069. ("dvi" . "xdvi %s")
  1070. ("fig" . "xfig %s")
  1071. (t . "open %s"))
  1072. "Default file applications on a macOS system.
  1073. The system \"open\" is known as a default, but we use X11 applications
  1074. for some files for which the OS does not have a good default.
  1075. See `org-file-apps'.")
  1076. (defconst org-file-apps-windowsnt
  1077. (list '(remote . emacs)
  1078. (cons 'system (lambda (file _path)
  1079. (with-no-warnings (w32-shell-execute "open" file))))
  1080. (cons t (lambda (file _path)
  1081. (with-no-warnings (w32-shell-execute "open" file)))))
  1082. "Default file applications on a Windows NT system.
  1083. The system \"open\" is used for most files.
  1084. See `org-file-apps'.")
  1085. (defcustom org-file-apps
  1086. '((auto-mode . emacs)
  1087. (directory . emacs)
  1088. ("\\.mm\\'" . default)
  1089. ("\\.x?html?\\'" . default)
  1090. ("\\.pdf\\'" . default))
  1091. "Applications for opening `file:path' items in a document.
  1092. \\<org-mode-map>
  1093. Org mode uses system defaults for different file types, but you
  1094. can use this variable to set the application for a given file
  1095. extension. The entries in this list are cons cells where the car
  1096. identifies files and the cdr the corresponding command.
  1097. Possible values for the file identifier are:
  1098. \"string\" A string as a file identifier can be interpreted in different
  1099. ways, depending on its contents:
  1100. - Alphanumeric characters only:
  1101. Match links with this file extension.
  1102. Example: (\"pdf\" . \"evince %s\")
  1103. to open PDFs with evince.
  1104. - Regular expression: Match links where the
  1105. filename matches the regexp. If you want to
  1106. use groups here, use shy groups.
  1107. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1108. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1109. to open *.html and *.xhtml with firefox.
  1110. - Regular expression which contains (non-shy) groups:
  1111. Match links where the whole link, including \"::\", and
  1112. anything after that, matches the regexp.
  1113. In a custom command string, %1, %2, etc. are replaced with
  1114. the parts of the link that were matched by the groups.
  1115. For backwards compatibility, if a command string is given
  1116. that does not use any of the group matches, this case is
  1117. handled identically to the second one (i.e. match against
  1118. file name only).
  1119. In a custom function, you can access the group matches with
  1120. (match-string n link).
  1121. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1122. \"evince -p %1 %s\")
  1123. to open [[file:document.pdf::5]] with evince at page 5.
  1124. Likely, you will need more entries: without page
  1125. number; with search pattern; with cross-reference
  1126. anchor; some combination of options. Consider simple
  1127. pattern here and a Lisp function to determine command
  1128. line arguments instead. Passing argument list to
  1129. `call-process' or `make-process' directly allows to
  1130. avoid treating some character in peculiar file names
  1131. as shell specialls causing executing part of file
  1132. name as a subcommand.
  1133. `directory' Matches a directory
  1134. `remote' Matches a remote file, accessible through tramp or efs.
  1135. Remote files most likely should be visited through Emacs
  1136. because external applications cannot handle such paths.
  1137. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1138. so all files Emacs knows how to handle. Using this with
  1139. command `emacs' will open most files in Emacs. Beware that this
  1140. will also open html files inside Emacs, unless you add
  1141. (\"html\" . default) to the list as well.
  1142. `system' The system command to open files, like `open' on Windows
  1143. and macOS, and mailcap under GNU/Linux. This is the command
  1144. that will be selected if you call `org-open-at-point' with a
  1145. double prefix argument (`\\[universal-argument] \
  1146. \\[universal-argument] \\[org-open-at-point]').
  1147. t Default for files not matched by any of the other options.
  1148. Possible values for the command are:
  1149. `emacs' The file will be visited by the current Emacs process.
  1150. `default' Use the default application for this file type, which is the
  1151. association for t in the list, most likely in the system-specific
  1152. part. This can be used to overrule an unwanted setting in the
  1153. system-specific variable.
  1154. `system' Use the system command for opening files, like \"open\".
  1155. This command is specified by the entry whose car is `system'.
  1156. Most likely, the system-specific version of this variable
  1157. does define this command, but you can overrule/replace it
  1158. here.
  1159. `mailcap' Use command specified in the mailcaps.
  1160. string A command to be executed by a shell; %s will be replaced
  1161. by the path to the file.
  1162. function A Lisp function, which will be called with two arguments:
  1163. the file path and the original link string, without the
  1164. \"file:\" prefix.
  1165. For more examples, see the system specific constants
  1166. `org-file-apps-macos'
  1167. `org-file-apps-windowsnt'
  1168. `org-file-apps-gnu'."
  1169. :group 'org
  1170. :package-version '(Org . "9.4")
  1171. :type '(repeat
  1172. (cons (choice :value ""
  1173. (string :tag "Extension")
  1174. (const :tag "System command to open files" system)
  1175. (const :tag "Default for unrecognized files" t)
  1176. (const :tag "Remote file" remote)
  1177. (const :tag "Links to a directory" directory)
  1178. (const :tag "Any files that have Emacs modes"
  1179. auto-mode))
  1180. (choice :value ""
  1181. (const :tag "Visit with Emacs" emacs)
  1182. (const :tag "Use default" default)
  1183. (const :tag "Use the system command" system)
  1184. (string :tag "Command")
  1185. (function :tag "Function")))))
  1186. (defcustom org-resource-download-policy 'prompt
  1187. "The policy applied to requests to obtain remote resources.
  1188. This affects keywords like #+setupfile and #+incude on export,
  1189. `org-persist-write:url',and `org-attach-url' in non-interactive
  1190. Emacs sessions.
  1191. This recognises four possible values:
  1192. - t, remote resources should always be downloaded.
  1193. - prompt, you will be prompted to download resources nt considered safe.
  1194. - safe, only resources considered safe will be downloaded.
  1195. - nil, never download remote resources.
  1196. A resource is considered safe if it matches one of the patterns
  1197. in `org-safe-remote-resources'."
  1198. :group 'org
  1199. :type '(choice (const :tag "Always download remote resources" t)
  1200. (const :tag "Prompt before downloading an unsafe resource" prompt)
  1201. (const :tag "Only download resources considered safe" safe)
  1202. (const :tag "Never download any resources" nil)))
  1203. (defcustom org-safe-remote-resources nil
  1204. "A list of regexp patterns matching safe URIs.
  1205. URI regexps are applied to both URLs and Org files requesting
  1206. remote resources."
  1207. :group 'org
  1208. :type '(list regexp))
  1209. (defcustom org-open-non-existing-files nil
  1210. "Non-nil means `org-open-file' opens non-existing files.
  1211. When nil, an error is thrown.
  1212. This variable applies only to external applications because they
  1213. might choke on non-existing files. If the link is to a file that
  1214. will be opened in Emacs, the variable is ignored."
  1215. :group 'org
  1216. :type 'boolean
  1217. :safe #'booleanp)
  1218. (defcustom org-open-directory-means-index-dot-org nil
  1219. "When non-nil a link to a directory really means to \"index.org\".
  1220. When nil, following a directory link runs Dired or opens
  1221. a finder/explorer window on that directory."
  1222. :group 'org
  1223. :type 'boolean
  1224. :safe #'booleanp)
  1225. (defcustom org-bookmark-names-plist
  1226. '(:last-capture "org-capture-last-stored"
  1227. :last-refile "org-refile-last-stored"
  1228. :last-capture-marker "org-capture-last-stored-marker")
  1229. "Names for bookmarks automatically set by some Org commands.
  1230. This can provide strings as names for a number of bookmarks Org sets
  1231. automatically. The following keys are currently implemented:
  1232. :last-capture
  1233. :last-capture-marker
  1234. :last-refile
  1235. When a key does not show up in the property list, the corresponding bookmark
  1236. is not set."
  1237. :group 'org-structure
  1238. :type 'plist)
  1239. (defgroup org-edit-structure nil
  1240. "Options concerning structure editing in Org mode."
  1241. :tag "Org Edit Structure"
  1242. :group 'org-structure)
  1243. (defcustom org-odd-levels-only nil
  1244. "Non-nil means skip even levels and only use odd levels for the outline.
  1245. This has the effect that two stars are being added/taken away in
  1246. promotion/demotion commands. It also influences how levels are
  1247. handled by the exporters.
  1248. Changing it requires restart of `font-lock-mode' to become effective
  1249. for fontification also in regions already fontified.
  1250. You may also set this on a per-file basis by adding one of the following
  1251. lines to the buffer:
  1252. #+STARTUP: odd
  1253. #+STARTUP: oddeven"
  1254. :group 'org-edit-structure
  1255. :group 'org-appearance
  1256. :type 'boolean)
  1257. (defcustom org-adapt-indentation nil
  1258. "Non-nil means adapt indentation to outline node level.
  1259. When set to t, Org assumes that you write outlines by indenting
  1260. text in each node to align with the headline, after the stars.
  1261. When this variable is set to `headline-data', Org only adapts the
  1262. indentation of the data lines right below the headline, such as
  1263. planning/clock lines and property/logbook drawers.
  1264. The following issues are influenced by this variable:
  1265. - The indentation is increased by one space in a demotion
  1266. command, and decreased by one in a promotion command. However,
  1267. in the latter case, if shifting some line in the entry body
  1268. would alter document structure (e.g., insert a new headline),
  1269. indentation is not changed at all.
  1270. - Property drawers and planning information is inserted indented
  1271. when this variable is set. When nil, they will not be indented.
  1272. - TAB indents a line relative to current level. The lines below
  1273. a headline will be indented when this variable is set to t.
  1274. Note that this is all about true indentation, by adding and
  1275. removing space characters. See also \"org-indent.el\" which does
  1276. level-dependent indentation in a virtual way, i.e. at display
  1277. time in Emacs."
  1278. :group 'org-edit-structure
  1279. :type '(choice
  1280. (const :tag "Adapt indentation for all lines" t)
  1281. (const :tag "Adapt indentation for headline data lines"
  1282. headline-data)
  1283. (const :tag "Do not adapt indentation at all" nil))
  1284. :safe (lambda (x) (memq x '(t nil headline-data))))
  1285. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1286. (defcustom org-special-ctrl-a/e nil
  1287. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1288. When t, `C-a' will bring back the cursor to the beginning of the
  1289. headline text, i.e. after the stars and after a possible TODO
  1290. keyword. In an item, this will be the position after bullet and
  1291. check-box, if any. When the cursor is already at that position,
  1292. another `C-a' will bring it to the beginning of the line.
  1293. `C-e' will jump to the end of the headline, ignoring the presence
  1294. of tags in the headline. A second `C-e' will then jump to the
  1295. true end of the line, after any tags. This also means that, when
  1296. this variable is non-nil, `C-e' also will never jump beyond the
  1297. end of the heading of a folded section, i.e. not after the
  1298. ellipses.
  1299. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1300. normally, going to the true line boundary first. Only a directly
  1301. following, identical keypress will bring the cursor to the
  1302. special positions.
  1303. This may also be a cons cell where the behavior for `C-a' and
  1304. `C-e' is set separately."
  1305. :group 'org-edit-structure
  1306. :type '(choice
  1307. (const :tag "off" nil)
  1308. (const :tag "on: after stars/bullet and before tags first" t)
  1309. (const :tag "reversed: true line boundary first" reversed)
  1310. (cons :tag "Set C-a and C-e separately"
  1311. (choice :tag "Special C-a"
  1312. (const :tag "off" nil)
  1313. (const :tag "on: after stars/bullet first" t)
  1314. (const :tag "reversed: before stars/bullet first" reversed))
  1315. (choice :tag "Special C-e"
  1316. (const :tag "off" nil)
  1317. (const :tag "on: before tags first" t)
  1318. (const :tag "reversed: after tags first" reversed)))))
  1319. (defcustom org-special-ctrl-k nil
  1320. "Non-nil means `C-k' will behave specially in headlines.
  1321. When nil, `C-k' will call the default `kill-line' command.
  1322. When t, the following will happen while the cursor is in the headline:
  1323. - When at the beginning of a headline, kill the entire subtree.
  1324. - When in the middle of the headline text, kill the text up to the tags.
  1325. - When after the headline text and before the tags, kill all the tags."
  1326. :group 'org-edit-structure
  1327. :type 'boolean)
  1328. (defcustom org-ctrl-k-protect-subtree nil
  1329. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1330. When set to the symbol `error', simply throw an error when `C-k' is
  1331. used to kill (part-of) a headline that has hidden text behind it.
  1332. Any other non-nil value will result in a query to the user, if it is
  1333. OK to kill that hidden subtree. When nil, kill without remorse."
  1334. :group 'org-edit-structure
  1335. :version "24.1"
  1336. :type '(choice
  1337. (const :tag "Do not protect hidden subtrees" nil)
  1338. (const :tag "Protect hidden subtrees with a security query" t)
  1339. (const :tag "Never kill a hidden subtree with C-k" error)))
  1340. (defcustom org-special-ctrl-o t
  1341. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1342. :group 'org-edit-structure
  1343. :type 'boolean)
  1344. (defcustom org-yank-folded-subtrees t
  1345. "Non-nil means when yanking subtrees, fold them.
  1346. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1347. it starts with a heading and all other headings in it are either children
  1348. or siblings, then fold all the subtrees. However, do this only if no
  1349. text after the yank would be swallowed into a folded tree by this action."
  1350. :group 'org-edit-structure
  1351. :type 'boolean)
  1352. (defcustom org-yank-adjusted-subtrees nil
  1353. "Non-nil means when yanking subtrees, adjust the level.
  1354. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1355. this function for details."
  1356. :group 'org-edit-structure
  1357. :type 'boolean)
  1358. (defcustom org-M-RET-may-split-line '((default . t))
  1359. "Non-nil means M-RET will split the line at the cursor position.
  1360. When nil, it will go to the end of the line before making a
  1361. new line.
  1362. You may also set this option in a different way for different
  1363. contexts. Valid contexts are:
  1364. headline when creating a new headline
  1365. item when creating a new item
  1366. table in a table field
  1367. default the value to be used for all contexts not explicitly
  1368. customized"
  1369. :group 'org-structure
  1370. :group 'org-table
  1371. :type '(choice
  1372. (const :tag "Always" t)
  1373. (const :tag "Never" nil)
  1374. (repeat :greedy t :tag "Individual contexts"
  1375. (cons
  1376. (choice :tag "Context"
  1377. (const headline)
  1378. (const item)
  1379. (const table)
  1380. (const default))
  1381. (boolean)))))
  1382. (defcustom org-insert-heading-respect-content nil
  1383. "Non-nil means insert new headings after the current subtree.
  1384. \\<org-mode-map>
  1385. When nil, the new heading is created directly after the current line.
  1386. The commands `\\[org-insert-heading-respect-content]' and \
  1387. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1388. for the duration of the command."
  1389. :group 'org-structure
  1390. :type 'boolean)
  1391. (defcustom org-blank-before-new-entry '((heading . auto)
  1392. (plain-list-item . auto))
  1393. "Should `org-insert-heading' leave a blank line before new heading/item?
  1394. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1395. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1396. which case Org will look at the surrounding headings/items and try to
  1397. make an intelligent decision whether to insert a blank line or not."
  1398. :group 'org-edit-structure
  1399. :type '(list
  1400. (cons (const heading)
  1401. (choice (const :tag "Never" nil)
  1402. (const :tag "Always" t)
  1403. (const :tag "Auto" auto)))
  1404. (cons (const plain-list-item)
  1405. (choice (const :tag "Never" nil)
  1406. (const :tag "Always" t)
  1407. (const :tag "Auto" auto)))))
  1408. (defcustom org-insert-heading-hook nil
  1409. "Hook being run after inserting a new heading."
  1410. :group 'org-edit-structure
  1411. :type 'hook)
  1412. (defgroup org-sparse-trees nil
  1413. "Options concerning sparse trees in Org mode."
  1414. :tag "Org Sparse Trees"
  1415. :group 'org-structure)
  1416. (defcustom org-highlight-sparse-tree-matches t
  1417. "Non-nil means highlight all matches that define a sparse tree.
  1418. The highlights will automatically disappear the next time the buffer is
  1419. changed by an edit command."
  1420. :group 'org-sparse-trees
  1421. :type 'boolean)
  1422. (defcustom org-remove-highlights-with-change t
  1423. "Non-nil means any change to the buffer will remove temporary highlights.
  1424. \\<org-mode-map>\
  1425. Such highlights are created by `org-occur' and `org-clock-display'.
  1426. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1427. to get rid of the highlights.
  1428. The highlights created by `org-latex-preview' always need
  1429. `\\[org-latex-preview]' to be removed."
  1430. :group 'org-sparse-trees
  1431. :group 'org-time
  1432. :type 'boolean)
  1433. (defcustom org-occur-case-fold-search t
  1434. "Non-nil means `org-occur' should be case-insensitive.
  1435. If set to `smart' the search will be case-insensitive only if it
  1436. doesn't specify any upper case character."
  1437. :group 'org-sparse-trees
  1438. :version "26.1"
  1439. :type '(choice
  1440. (const :tag "Case-sensitive" nil)
  1441. (const :tag "Case-insensitive" t)
  1442. (const :tag "Case-insensitive for lower case searches only" smart)))
  1443. (defcustom org-occur-hook '(org-first-headline-recenter)
  1444. "Hook that is run after `org-occur' has constructed a sparse tree.
  1445. This can be used to recenter the window to show as much of the structure
  1446. as possible."
  1447. :group 'org-sparse-trees
  1448. :type 'hook)
  1449. (defcustom org-self-insert-cluster-for-undo nil
  1450. "Non-nil means cluster self-insert commands for undo when possible.
  1451. If this is set, then, like in the Emacs command loop, 20 consecutive
  1452. characters will be undone together.
  1453. This is configurable, because there is some impact on typing performance."
  1454. :group 'org-table
  1455. :type 'boolean)
  1456. (defvaralias 'org-activate-links 'org-highlight-links)
  1457. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1458. "Types of links that should be highlighted in Org files.
  1459. This is a list of symbols, each one of them leading to the
  1460. highlighting of a certain link type.
  1461. You can still open links that are not highlighted.
  1462. In principle, it does not hurt to turn on highlighting for all
  1463. link types. There may be a small gain when turning off unused
  1464. link types. The types are:
  1465. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1466. angle Links in angular brackets that may contain whitespace like
  1467. <bbdb:Carsten Dominik>.
  1468. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1469. radio Text that is matched by a radio target, see manual for details.
  1470. tag Tag settings in a headline (link to tag search).
  1471. date Time stamps (link to calendar).
  1472. footnote Footnote labels.
  1473. If you set this variable during an Emacs session, use `org-mode-restart'
  1474. in the Org buffer so that the change takes effect."
  1475. :group 'org-appearance
  1476. :type '(set :greedy t
  1477. (const :tag "Double bracket links" bracket)
  1478. (const :tag "Angular bracket links" angle)
  1479. (const :tag "Plain text links" plain)
  1480. (const :tag "Radio target matches" radio)
  1481. (const :tag "Tags" tag)
  1482. (const :tag "Timestamps" date)
  1483. (const :tag "Footnotes" footnote)))
  1484. (defcustom org-mark-ring-length 4
  1485. "Number of different positions to be recorded in the ring.
  1486. Changing this requires a restart of Emacs to work correctly."
  1487. :group 'org-link-follow
  1488. :type 'integer)
  1489. (defgroup org-todo nil
  1490. "Options concerning TODO items in Org mode."
  1491. :tag "Org TODO"
  1492. :group 'org)
  1493. (defgroup org-progress nil
  1494. "Options concerning Progress logging in Org mode."
  1495. :tag "Org Progress"
  1496. :group 'org-time)
  1497. (defvar org-todo-interpretation-widgets
  1498. '((:tag "Sequence (cycling hits every state)" sequence)
  1499. (:tag "Type (cycling directly to DONE)" type))
  1500. "The available interpretation symbols for customizing `org-todo-keywords'.
  1501. Interested libraries should add to this list.")
  1502. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1503. "List of TODO entry keyword sequences and their interpretation.
  1504. \\<org-mode-map>This is a list of sequences.
  1505. Each sequence starts with a symbol, either `sequence' or `type',
  1506. indicating if the keywords should be interpreted as a sequence of
  1507. action steps, or as different types of TODO items. The first
  1508. keywords are states requiring action - these states will select a headline
  1509. for inclusion into the global TODO list Org produces. If one of the
  1510. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1511. signify that no further action is necessary. If \"|\" is not found,
  1512. the last keyword is treated as the only DONE state of the sequence.
  1513. The command `\\[org-todo]' cycles an entry through these states, and one
  1514. additional state where no keyword is present. For details about this
  1515. cycling, see the manual.
  1516. TODO keywords and interpretation can also be set on a per-file basis with
  1517. the special #+SEQ_TODO and #+TYP_TODO lines.
  1518. Each keyword can optionally specify a character for fast state selection
  1519. \(in combination with the variable `org-use-fast-todo-selection')
  1520. and specifiers for state change logging, using the same syntax that
  1521. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1522. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1523. indicates to record a time stamp each time this state is selected.
  1524. Each keyword may also specify if a timestamp or a note should be
  1525. recorded when entering or leaving the state, by adding additional
  1526. characters in the parenthesis after the keyword. This looks like this:
  1527. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1528. record only the time of the state change. With X and Y being either
  1529. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1530. Y when leaving the state if and only if the *target* state does not
  1531. define X. You may omit any of the fast-selection key or X or /Y,
  1532. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1533. For backward compatibility, this variable may also be just a list
  1534. of keywords. In this case the interpretation (sequence or type) will be
  1535. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1536. :group 'org-todo
  1537. :group 'org-keywords
  1538. :type '(choice
  1539. (repeat :tag "Old syntax, just keywords"
  1540. (string :tag "Keyword"))
  1541. (repeat :tag "New syntax"
  1542. (cons
  1543. (choice
  1544. :tag "Interpretation"
  1545. ;;Quick and dirty way to see
  1546. ;;`org-todo-interpretation'. This takes the
  1547. ;;place of item arguments
  1548. :convert-widget
  1549. (lambda (widget)
  1550. (widget-put widget
  1551. :args (mapcar
  1552. (lambda (x)
  1553. (widget-convert
  1554. (cons 'const x)))
  1555. org-todo-interpretation-widgets))
  1556. widget))
  1557. (repeat
  1558. (string :tag "Keyword"))))))
  1559. (defvar-local org-todo-keywords-1 nil
  1560. "All TODO and DONE keywords active in a buffer.")
  1561. (defvar org-todo-keywords-for-agenda nil)
  1562. (defvar org-done-keywords-for-agenda nil)
  1563. (defvar org-todo-keyword-alist-for-agenda nil)
  1564. (defvar org-tag-alist-for-agenda nil
  1565. "Alist of all tags from all agenda files.")
  1566. (defvar org-tag-groups-alist-for-agenda nil
  1567. "Alist of all groups tags from all current agenda files.")
  1568. (defvar-local org-tag-groups-alist nil)
  1569. (defvar org-agenda-contributing-files nil)
  1570. (defvar-local org-current-tag-alist nil
  1571. "Alist of all tag groups in current buffer.
  1572. This variable takes into consideration `org-tag-alist',
  1573. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1574. (defvar-local org-not-done-keywords nil)
  1575. (defvar-local org-done-keywords nil)
  1576. (defvar-local org-todo-heads nil)
  1577. (defvar-local org-todo-sets nil)
  1578. (defvar-local org-todo-log-states nil)
  1579. (defvar-local org-todo-kwd-alist nil)
  1580. (defvar-local org-todo-key-alist nil)
  1581. (defvar-local org-todo-key-trigger nil)
  1582. (defcustom org-todo-interpretation 'sequence
  1583. "Controls how TODO keywords are interpreted.
  1584. This variable is in principle obsolete and is only used for
  1585. backward compatibility, if the interpretation of todo keywords is
  1586. not given already in `org-todo-keywords'. See that variable for
  1587. more information."
  1588. :group 'org-todo
  1589. :group 'org-keywords
  1590. :type '(choice (const sequence)
  1591. (const type)))
  1592. (defcustom org-use-fast-todo-selection 'auto
  1593. "\\<org-mode-map>\
  1594. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1595. This variable describes if and under what circumstances the cycling
  1596. mechanism for TODO keywords will be replaced by a single-key, direct
  1597. selection scheme, where the choices are displayed in a little window.
  1598. When nil, fast selection is never used. This means that the command
  1599. will always switch to the next state.
  1600. When it is the symbol `auto', fast selection is whenever selection
  1601. keys have been defined.
  1602. `expert' is like `auto', but no special window with the keyword
  1603. will be shown, choices will only be listed in the prompt.
  1604. In all cases, the special interface is only used if access keys have
  1605. actually been assigned by the user, i.e. if keywords in the configuration
  1606. are followed by a letter in parenthesis, like TODO(t)."
  1607. :group 'org-todo
  1608. :set (lambda (var val)
  1609. (cond
  1610. ((eq var t) (set-default-toplevel-value var 'auto))
  1611. ((eq var 'prefix) (set-default-toplevel-value var nil))
  1612. (t (set-default-toplevel-value var val))))
  1613. :type '(choice
  1614. (const :tag "Never" nil)
  1615. (const :tag "Automatically, when key letter have been defined" auto)
  1616. (const :tag "Automatically, but don't show the selection window" expert)))
  1617. (defcustom org-provide-todo-statistics t
  1618. "Non-nil means update todo statistics after insert and toggle.
  1619. ALL-HEADLINES means update todo statistics by including headlines
  1620. with no TODO keyword as well, counting them as not done.
  1621. A list of TODO keywords means the same, but skip keywords that are
  1622. not in this list.
  1623. When set to a list of two lists, the first list contains keywords
  1624. to consider as TODO keywords, the second list contains keywords
  1625. to consider as DONE keywords.
  1626. When this is set, todo statistics is updated in the parent of the
  1627. current entry each time a todo state is changed."
  1628. :group 'org-todo
  1629. :type '(choice
  1630. (const :tag "Yes, only for TODO entries" t)
  1631. (const :tag "Yes, including all entries" all-headlines)
  1632. (repeat :tag "Yes, for TODOs in this list"
  1633. (string :tag "TODO keyword"))
  1634. (list :tag "Yes, for TODOs and DONEs in these lists"
  1635. (repeat (string :tag "TODO keyword"))
  1636. (repeat (string :tag "DONE keyword")))
  1637. (other :tag "No TODO statistics" nil)))
  1638. (defcustom org-hierarchical-todo-statistics t
  1639. "Non-nil means TODO statistics covers just direct children.
  1640. When nil, all entries in the subtree are considered.
  1641. This has only an effect if `org-provide-todo-statistics' is set.
  1642. To set this to nil for only a single subtree, use a COOKIE_DATA
  1643. property and include the word \"recursive\" into the value."
  1644. :group 'org-todo
  1645. :type 'boolean)
  1646. (defcustom org-after-todo-state-change-hook nil
  1647. "Hook which is run after the state of a TODO item was changed.
  1648. The new state (a string with a TODO keyword, or nil) is available in the
  1649. Lisp variable `org-state'."
  1650. :group 'org-todo
  1651. :type 'hook)
  1652. (defvar org-blocker-hook nil
  1653. "Hook for functions that are allowed to block a state change.
  1654. Functions in this hook should not modify the buffer.
  1655. Each function gets as its single argument a property list,
  1656. see `org-trigger-hook' for more information about this list.
  1657. If any of the functions in this hook returns nil, the state change
  1658. is blocked.")
  1659. (defvar org-trigger-hook nil
  1660. "Hook for functions that are triggered by a state change.
  1661. Each function gets as its single argument a property list with at
  1662. least the following elements:
  1663. (:type type-of-change :position pos-at-entry-start
  1664. :from old-state :to new-state)
  1665. Depending on the type, more properties may be present.
  1666. This mechanism is currently implemented for:
  1667. TODO state changes
  1668. ------------------
  1669. :type todo-state-change
  1670. :from previous state (keyword as a string), or nil, or a symbol
  1671. `todo' or `done', to indicate the general type of state.
  1672. :to new state, like in :from")
  1673. (defcustom org-enforce-todo-dependencies nil
  1674. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1675. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1676. be blocked if any prior sibling is not yet done.
  1677. Finally, if the parent is blocked because of ordered siblings of its own,
  1678. the child will also be blocked."
  1679. :set (lambda (var val)
  1680. (set-default-toplevel-value var val)
  1681. (if val
  1682. (add-hook 'org-blocker-hook
  1683. 'org-block-todo-from-children-or-siblings-or-parent)
  1684. (remove-hook 'org-blocker-hook
  1685. 'org-block-todo-from-children-or-siblings-or-parent)))
  1686. :group 'org-todo
  1687. :type 'boolean)
  1688. (defcustom org-enforce-todo-checkbox-dependencies nil
  1689. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1690. When this is nil, checkboxes have no influence on switching TODO states.
  1691. When non-nil, you first need to check off all check boxes before the TODO
  1692. entry can be switched to DONE.
  1693. This variable needs to be set before org.el is loaded, and you need to
  1694. restart Emacs after a change to make the change effective. The only way
  1695. to change it while Emacs is running is through the customize interface."
  1696. :set (lambda (var val)
  1697. (set-default-toplevel-value var val)
  1698. (if val
  1699. (add-hook 'org-blocker-hook
  1700. 'org-block-todo-from-checkboxes)
  1701. (remove-hook 'org-blocker-hook
  1702. 'org-block-todo-from-checkboxes)))
  1703. :group 'org-todo
  1704. :type 'boolean)
  1705. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1706. "Non-nil means inserting a TODO heading is treated as state change.
  1707. So when the command `\\[org-insert-todo-heading]' is used, state change
  1708. logging will apply if appropriate. When nil, the new TODO item will
  1709. be inserted directly, and no logging will take place."
  1710. :group 'org-todo
  1711. :type 'boolean)
  1712. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1713. "Non-nil means switching TODO states with S-cursor counts as state change.
  1714. This is the default behavior. However, setting this to nil allows a
  1715. convenient way to select a TODO state and bypass any logging associated
  1716. with that."
  1717. :group 'org-todo
  1718. :type 'boolean)
  1719. (defcustom org-todo-state-tags-triggers nil
  1720. "Tag changes that should be triggered by TODO state changes.
  1721. This is a list. Each entry is
  1722. (state-change (tag . flag) .......)
  1723. State-change can be a string with a state, and empty string to indicate the
  1724. state that has no TODO keyword, or it can be one of the symbols `todo'
  1725. or `done', meaning any not-done or done state, respectively."
  1726. :group 'org-todo
  1727. :group 'org-tags
  1728. :type '(repeat
  1729. (cons (choice :tag "When changing to"
  1730. (const :tag "Not-done state" todo)
  1731. (const :tag "Done state" done)
  1732. (string :tag "State"))
  1733. (repeat
  1734. (cons :tag "Tag action"
  1735. (string :tag "Tag")
  1736. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1737. (defcustom org-log-done nil
  1738. "Information to record when a task moves to the DONE state.
  1739. Possible values are:
  1740. nil Don't add anything, just change the keyword
  1741. time Add a time stamp to the task
  1742. note Prompt for a note and add it with template `org-log-note-headings'
  1743. This option can also be set with on a per-file-basis with
  1744. #+STARTUP: nologdone
  1745. #+STARTUP: logdone
  1746. #+STARTUP: lognotedone
  1747. You can have local logging settings for a subtree by setting the LOGGING
  1748. property to one or more of these keywords."
  1749. :group 'org-todo
  1750. :group 'org-progress
  1751. :type '(choice
  1752. (const :tag "No logging" nil)
  1753. (const :tag "Record CLOSED timestamp" time)
  1754. (const :tag "Record CLOSED timestamp with note." note)))
  1755. ;; Normalize old uses of org-log-done.
  1756. (cond
  1757. ((eq org-log-done t) (setq org-log-done 'time))
  1758. ((and (listp org-log-done) (memq 'done org-log-done))
  1759. (setq org-log-done 'note)))
  1760. (defcustom org-log-reschedule nil
  1761. "Information to record when the scheduling date of a task is modified.
  1762. Possible values are:
  1763. nil Don't add anything, just change the date
  1764. time Add a time stamp to the task
  1765. note Prompt for a note and add it with template `org-log-note-headings'
  1766. This option can also be set with on a per-file-basis with
  1767. #+STARTUP: nologreschedule
  1768. #+STARTUP: logreschedule
  1769. #+STARTUP: lognotereschedule
  1770. You can have local logging settings for a subtree by setting the LOGGING
  1771. property to one or more of these keywords.
  1772. This variable has an effect when calling `org-schedule' or
  1773. `org-agenda-schedule' only."
  1774. :group 'org-todo
  1775. :group 'org-progress
  1776. :type '(choice
  1777. (const :tag "No logging" nil)
  1778. (const :tag "Record timestamp" time)
  1779. (const :tag "Record timestamp with note" note)))
  1780. (defcustom org-log-redeadline nil
  1781. "Information to record when the deadline date of a task is modified.
  1782. Possible values are:
  1783. nil Don't add anything, just change the date
  1784. time Add a time stamp to the task
  1785. note Prompt for a note and add it with template `org-log-note-headings'
  1786. This option can also be set with on a per-file-basis with
  1787. #+STARTUP: nologredeadline
  1788. #+STARTUP: logredeadline
  1789. #+STARTUP: lognoteredeadline
  1790. You can have local logging settings for a subtree by setting the LOGGING
  1791. property to one or more of these keywords.
  1792. This variable has an effect when calling `org-deadline' or
  1793. `org-agenda-deadline' only."
  1794. :group 'org-todo
  1795. :group 'org-progress
  1796. :type '(choice
  1797. (const :tag "No logging" nil)
  1798. (const :tag "Record timestamp" time)
  1799. (const :tag "Record timestamp with note." note)))
  1800. (defcustom org-log-note-clock-out nil
  1801. "Non-nil means record a note when clocking out of an item.
  1802. This can also be configured on a per-file basis by adding one of
  1803. the following lines anywhere in the buffer:
  1804. #+STARTUP: lognoteclock-out
  1805. #+STARTUP: nolognoteclock-out"
  1806. :group 'org-todo
  1807. :group 'org-progress
  1808. :type 'boolean)
  1809. (defcustom org-log-done-with-time t
  1810. "Non-nil means the CLOSED time stamp will contain date and time.
  1811. When nil, only the date will be recorded."
  1812. :group 'org-progress
  1813. :type 'boolean)
  1814. (defcustom org-log-note-headings
  1815. '((done . "CLOSING NOTE %t")
  1816. (state . "State %-12s from %-12S %t")
  1817. (note . "Note taken on %t")
  1818. (reschedule . "Rescheduled from %S on %t")
  1819. (delschedule . "Not scheduled, was %S on %t")
  1820. (redeadline . "New deadline from %S on %t")
  1821. (deldeadline . "Removed deadline, was %S on %t")
  1822. (refile . "Refiled on %t")
  1823. (clock-out . ""))
  1824. "Headings for notes added to entries.
  1825. The value is an alist, with the car being a symbol indicating the
  1826. note context, and the cdr is the heading to be used. The heading
  1827. may also be the empty string. The following placeholders can be
  1828. used:
  1829. %t a time stamp.
  1830. %T an active time stamp instead the default inactive one
  1831. %d a short-format time stamp.
  1832. %D an active short-format time stamp.
  1833. %s the new TODO state or time stamp (inactive), in double quotes.
  1834. %S the old TODO state or time stamp (inactive), in double quotes.
  1835. %u the user name.
  1836. %U full user name.
  1837. In fact, it is not a good idea to change the `state' entry,
  1838. because Agenda Log mode depends on the format of these entries."
  1839. :group 'org-todo
  1840. :group 'org-progress
  1841. :type '(list :greedy t
  1842. (cons (const :tag "Heading when closing an item" done) string)
  1843. (cons (const :tag
  1844. "Heading when changing todo state (todo sequence only)"
  1845. state) string)
  1846. (cons (const :tag "Heading when just taking a note" note) string)
  1847. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1848. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1849. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1850. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1851. (cons (const :tag "Heading when refiling" refile) string)
  1852. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1853. (unless (assq 'note org-log-note-headings)
  1854. (push '(note . "%t") org-log-note-headings))
  1855. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1856. (defcustom org-log-into-drawer nil
  1857. "Non-nil means insert state change notes and time stamps into a drawer.
  1858. When nil, state changes notes will be inserted after the headline and
  1859. any scheduling and clock lines, but not inside a drawer.
  1860. The value of this variable should be the name of the drawer to use.
  1861. LOGBOOK is proposed as the default drawer for this purpose, you can
  1862. also set this to a string to define the drawer of your choice.
  1863. A value of t is also allowed, representing \"LOGBOOK\".
  1864. A value of t or nil can also be set with on a per-file-basis with
  1865. #+STARTUP: logdrawer
  1866. #+STARTUP: nologdrawer
  1867. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1868. will be ignored.
  1869. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1870. a subtree.
  1871. Do not check directly this variable in a Lisp program. Call
  1872. function `org-log-into-drawer' instead."
  1873. :group 'org-todo
  1874. :group 'org-progress
  1875. :type '(choice
  1876. (const :tag "Not into a drawer" nil)
  1877. (const :tag "LOGBOOK" t)
  1878. (string :tag "Other")))
  1879. (defun org-log-into-drawer ()
  1880. "Name of the log drawer, as a string, or nil.
  1881. This is the value of `org-log-into-drawer'. However, if the
  1882. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1883. be used instead of the default value."
  1884. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1885. (cond ((equal p "nil") nil)
  1886. ((equal p "t") "LOGBOOK")
  1887. ((stringp p) p)
  1888. (p "LOGBOOK")
  1889. ((stringp org-log-into-drawer) org-log-into-drawer)
  1890. (org-log-into-drawer "LOGBOOK"))))
  1891. (defcustom org-log-state-notes-insert-after-drawers nil
  1892. "Non-nil means insert state change notes after any drawers in entry.
  1893. Only the drawers that *immediately* follow the headline and the
  1894. deadline/scheduled line are skipped.
  1895. When nil, insert notes right after the heading and perhaps the line
  1896. with deadline/scheduling if present.
  1897. This variable will have no effect if `org-log-into-drawer' is
  1898. set."
  1899. :group 'org-todo
  1900. :group 'org-progress
  1901. :type 'boolean)
  1902. (defcustom org-log-states-order-reversed t
  1903. "Non-nil means the latest state note will be directly after heading.
  1904. When nil, the state change notes will be ordered according to time.
  1905. This option can also be set with on a per-file-basis with
  1906. #+STARTUP: logstatesreversed
  1907. #+STARTUP: nologstatesreversed"
  1908. :group 'org-todo
  1909. :group 'org-progress
  1910. :type 'boolean)
  1911. (defcustom org-todo-repeat-to-state nil
  1912. "The TODO state to which a repeater should return the repeating task.
  1913. By default this is the first task of a TODO sequence or the
  1914. previous state of a TYPE_TODO set. But you can specify to use
  1915. the previous state in a TODO sequence or a string.
  1916. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1917. entry, which has precedence over this option."
  1918. :group 'org-todo
  1919. :version "24.1"
  1920. :type '(choice (const :tag "Use the previous TODO state" t)
  1921. (const :tag "Use the head of the TODO sequence" nil)
  1922. (string :tag "Use a specific TODO state")))
  1923. (defcustom org-log-repeat 'time
  1924. "Non-nil means record moving through the DONE state when triggering repeat.
  1925. An auto-repeating task is immediately switched back to TODO when
  1926. marked DONE. If you are not logging state changes (by adding \"@\"
  1927. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1928. record a closing note, there will be no record of the task moving
  1929. through DONE. This variable forces taking a note anyway.
  1930. nil Don't force a record
  1931. time Record a time stamp
  1932. note Prompt for a note and add it with template `org-log-note-headings'
  1933. This option can also be set with on a per-file-basis with
  1934. #+STARTUP: nologrepeat
  1935. #+STARTUP: logrepeat
  1936. #+STARTUP: lognoterepeat
  1937. You can have local logging settings for a subtree by setting the LOGGING
  1938. property to one or more of these keywords."
  1939. :group 'org-todo
  1940. :group 'org-progress
  1941. :type '(choice
  1942. (const :tag "Don't force a record" nil)
  1943. (const :tag "Force recording the DONE state" time)
  1944. (const :tag "Force recording a note with the DONE state" note)))
  1945. (defcustom org-todo-repeat-hook nil
  1946. "Hook that is run after a task has been repeated."
  1947. :package-version '(Org . "9.2")
  1948. :group 'org-todo
  1949. :type 'hook)
  1950. (defgroup org-priorities nil
  1951. "Priorities in Org mode."
  1952. :tag "Org Priorities"
  1953. :group 'org-todo)
  1954. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1955. (defcustom org-priority-enable-commands t
  1956. "Non-nil means priority commands are active.
  1957. When nil, these commands will be disabled, so that you never accidentally
  1958. set a priority."
  1959. :group 'org-priorities
  1960. :type 'boolean)
  1961. (defvaralias 'org-highest-priority 'org-priority-highest)
  1962. (defcustom org-priority-highest ?A
  1963. "The highest priority of TODO items.
  1964. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1965. The default is the character ?A, which is 65 as a numeric value.
  1966. If you set `org-priority-highest' to a numeric value inferior to
  1967. 65, Org assumes you want to use digits for the priority cookie.
  1968. If you set it to >=65, Org assumes you want to use alphabetical
  1969. characters.
  1970. In both cases, the value of `org-priority-highest' must be
  1971. smaller than `org-priority-lowest': for example, if \"A\" is the
  1972. highest priority, it is smaller than the lowest \"C\" priority:
  1973. 65 < 67."
  1974. :group 'org-priorities
  1975. :type '(choice
  1976. (character :tag "Character")
  1977. (integer :tag "Integer (< 65)")))
  1978. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1979. (defcustom org-priority-lowest ?C
  1980. "The lowest priority of TODO items.
  1981. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1982. The default is the character ?C, which is 67 as a numeric value.
  1983. If you set `org-priority-lowest' to a numeric value inferior to
  1984. 65, Org assumes you want to use digits for the priority cookie.
  1985. If you set it to >=65, Org assumes you want to use alphabetical
  1986. characters.
  1987. In both cases, the value of `org-priority-lowest' must be greater
  1988. than `org-priority-highest': for example, if \"C\" is the lowest
  1989. priority, it is greater than the highest \"A\" priority: 67 >
  1990. 65."
  1991. :group 'org-priorities
  1992. :type '(choice
  1993. (character :tag "Character")
  1994. (integer :tag "Integer (< 65)")))
  1995. (defvaralias 'org-default-priority 'org-priority-default)
  1996. (defcustom org-priority-default ?B
  1997. "The default priority of TODO items.
  1998. This is the priority an item gets if no explicit priority is given.
  1999. When starting to cycle on an empty priority the first step in the cycle
  2000. depends on `org-priority-start-cycle-with-default'. The resulting first
  2001. step priority must not exceed the range from `org-priority-highest' to
  2002. `org-priority-lowest' which means that `org-priority-default' has to be
  2003. in this range exclusive or inclusive to the range boundaries. Else the
  2004. first step refuses to set the default and the second will fall back on
  2005. \(depending on the command used) the highest or lowest priority."
  2006. :group 'org-priorities
  2007. :type '(choice
  2008. (character :tag "Character")
  2009. (integer :tag "Integer (< 65)")))
  2010. (defcustom org-priority-start-cycle-with-default t
  2011. "Non-nil means start with default priority when starting to cycle.
  2012. When this is nil, the first step in the cycle will be (depending on the
  2013. command used) one higher or lower than the default priority.
  2014. See also `org-priority-default'."
  2015. :group 'org-priorities
  2016. :type 'boolean)
  2017. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2018. (defcustom org-priority-get-priority-function nil
  2019. "Function to extract the priority from a string.
  2020. The string is normally the headline. If this is nil, Org
  2021. computes the priority from the priority cookie like [#A] in the
  2022. headline. It returns an integer, increasing by 1000 for each
  2023. priority level.
  2024. The user can set a different function here, which should take a
  2025. string as an argument and return the numeric priority."
  2026. :group 'org-priorities
  2027. :version "24.1"
  2028. :type '(choice
  2029. (const nil)
  2030. (function)))
  2031. (defgroup org-time nil
  2032. "Options concerning time stamps and deadlines in Org mode."
  2033. :tag "Org Time"
  2034. :group 'org)
  2035. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2036. "Number of minutes to round time stamps to.
  2037. \\<org-mode-map>\
  2038. These are two values, the first applies when first creating a time stamp.
  2039. The second applies when changing it with the commands `S-up' and `S-down'.
  2040. When changing the time stamp, this means that it will change in steps
  2041. of N minutes, as given by the second value.
  2042. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2043. numbers should be factors of 60, so for example 5, 10, 15.
  2044. When this is larger than 1, you can still force an exact time stamp by using
  2045. a double prefix argument to a time stamp command like \
  2046. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2047. and by using a prefix arg to `S-up/down' to specify the exact number
  2048. of minutes to shift."
  2049. :group 'org-time
  2050. :get (lambda (var) ; Make sure both elements are there
  2051. (if (integerp (default-value var))
  2052. (list (default-value var) 5)
  2053. (default-value var)))
  2054. :type '(list
  2055. (integer :tag "when inserting times")
  2056. (integer :tag "when modifying times")))
  2057. ;; Normalize old customizations of this variable.
  2058. (when (integerp org-time-stamp-rounding-minutes)
  2059. (setq org-time-stamp-rounding-minutes
  2060. (list org-time-stamp-rounding-minutes
  2061. org-time-stamp-rounding-minutes)))
  2062. (defcustom org-display-custom-times nil
  2063. "Non-nil means overlay custom formats over all time stamps.
  2064. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2065. To turn this on on a per-file basis, insert anywhere in the file:
  2066. #+STARTUP: customtime"
  2067. :group 'org-time
  2068. :type 'sexp)
  2069. (make-variable-buffer-local 'org-display-custom-times)
  2070. (defcustom org-time-stamp-custom-formats
  2071. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2072. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2073. These are overlaid over the default ISO format if the variable
  2074. `org-display-custom-times' is set. Time like %H:%M should be at the
  2075. end of the second format. The custom formats are also honored by export
  2076. commands, if custom time display is turned on at the time of export."
  2077. :group 'org-time
  2078. :type 'sexp)
  2079. (defun org-time-stamp-format (&optional long inactive)
  2080. "Get the right format for a time string."
  2081. (let ((f (if long (cdr org-time-stamp-formats)
  2082. (car org-time-stamp-formats))))
  2083. (if inactive
  2084. (concat "[" (substring f 1 -1) "]")
  2085. f)))
  2086. (defcustom org-deadline-warning-days 14
  2087. "Number of days before expiration during which a deadline becomes active.
  2088. This variable governs the display in sparse trees and in the agenda.
  2089. When 0 or negative, it means use this number (the absolute value of it)
  2090. even if a deadline has a different individual lead time specified.
  2091. Custom commands can set this variable in the options section."
  2092. :group 'org-time
  2093. :group 'org-agenda-daily/weekly
  2094. :type 'integer)
  2095. (defcustom org-scheduled-delay-days 0
  2096. "Number of days before a scheduled item becomes active.
  2097. This variable governs the display in sparse trees and in the agenda.
  2098. The default value (i.e. 0) means: don't delay scheduled item.
  2099. When negative, it means use this number (the absolute value of it)
  2100. even if a scheduled item has a different individual delay time
  2101. specified.
  2102. Custom commands can set this variable in the options section."
  2103. :group 'org-time
  2104. :group 'org-agenda-daily/weekly
  2105. :version "24.4"
  2106. :package-version '(Org . "8.0")
  2107. :type 'integer)
  2108. (defcustom org-read-date-prefer-future t
  2109. "Non-nil means assume future for incomplete date input from user.
  2110. This affects the following situations:
  2111. 1. The user gives a month but not a year.
  2112. For example, if it is April and you enter \"feb 2\", this will be read
  2113. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2114. 2. The user gives a day, but no month.
  2115. For example, if today is the 15th, and you enter \"3\", Org will read
  2116. this as the third of *next* month. However, if you enter \"17\",
  2117. it will be considered as *this* month.
  2118. If you set this variable to the symbol `time', then also the following
  2119. will work:
  2120. 3. If the user gives a time.
  2121. If the time is before now, it will be interpreted as tomorrow.
  2122. Currently none of this works for ISO week specifications.
  2123. When this option is nil, the current day, month and year will always be
  2124. used as defaults.
  2125. See also `org-agenda-jump-prefer-future'."
  2126. :group 'org-time
  2127. :type '(choice
  2128. (const :tag "Never" nil)
  2129. (const :tag "Check month and day" t)
  2130. (const :tag "Check month, day, and time" time)))
  2131. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2132. "Should the agenda jump command prefer the future for incomplete dates?
  2133. The default is to do the same as configured in `org-read-date-prefer-future'.
  2134. But you can also set a deviating value here.
  2135. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2136. :group 'org-agenda
  2137. :group 'org-time
  2138. :version "24.1"
  2139. :type '(choice
  2140. (const :tag "Use org-read-date-prefer-future"
  2141. org-read-date-prefer-future)
  2142. (const :tag "Never" nil)
  2143. (const :tag "Always" t)))
  2144. (defcustom org-read-date-force-compatible-dates t
  2145. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2146. Depending on the system Emacs is running on, certain dates cannot
  2147. be represented with the type used internally to represent time.
  2148. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2149. correctly. Some systems allow for earlier dates, some for later,
  2150. some for both. One way to find out is to insert any date into an
  2151. Org buffer, putting the cursor on the year and hitting S-up and
  2152. S-down to test the range.
  2153. When this variable is set to t, the date/time prompt will not let
  2154. you specify dates outside the 1970-2037 range, so it is certain that
  2155. these dates will work in whatever version of Emacs you are
  2156. running, and also that you can move a file from one Emacs implementation
  2157. to another. Whenever Org is forcing the year for you, it will display
  2158. a message and beep.
  2159. When this variable is nil, Org will check if the date is
  2160. representable in the specific Emacs implementation you are using.
  2161. If not, it will force a year, usually the current year, and beep
  2162. to remind you. Currently this setting is not recommended because
  2163. the likelihood that you will open your Org files in an Emacs that
  2164. has limited date range is not negligible.
  2165. A workaround for this problem is to use diary sexp dates for time
  2166. stamps outside of this range."
  2167. :group 'org-time
  2168. :version "24.1"
  2169. :type 'boolean)
  2170. (defcustom org-read-date-display-live t
  2171. "Non-nil means display current interpretation of date prompt live.
  2172. This display will be in an overlay, in the minibuffer. Note that
  2173. live display is only active when `org-read-date-popup-calendar'
  2174. is non-nil."
  2175. :group 'org-time
  2176. :type 'boolean)
  2177. (defvaralias 'org-popup-calendar-for-date-prompt
  2178. 'org-read-date-popup-calendar)
  2179. (defcustom org-read-date-popup-calendar t
  2180. "Non-nil means pop up a calendar when prompting for a date.
  2181. In the calendar, the date can be selected with mouse-1. However, the
  2182. minibuffer will also be active, and you can simply enter the date as well.
  2183. When nil, only the minibuffer will be available."
  2184. :group 'org-time
  2185. :type 'boolean)
  2186. (defcustom org-extend-today-until 0
  2187. "The hour when your day really ends. Must be an integer.
  2188. This has influence for the following applications:
  2189. - When switching the agenda to \"today\". If it is still earlier than
  2190. the time given here, the day recognized as TODAY is actually yesterday.
  2191. - When a date is read from the user and it is still before the time given
  2192. here, the current date and time will be assumed to be yesterday, 23:59.
  2193. Also, timestamps inserted in capture templates follow this rule.
  2194. IMPORTANT: This is a feature whose implementation is and likely will
  2195. remain incomplete. Really, it is only here because past midnight seems to
  2196. be the favorite working time of John Wiegley :-)"
  2197. :group 'org-time
  2198. :type 'integer)
  2199. (defcustom org-use-effective-time nil
  2200. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2201. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2202. \"effective time\" of any timestamps between midnight and 8am will be
  2203. 23:59 of the previous day."
  2204. :group 'org-time
  2205. :version "24.1"
  2206. :type 'boolean)
  2207. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2208. "When non-nil, use the last clock out time for `org-todo'.
  2209. Note that this option has precedence over the combined use of
  2210. `org-use-effective-time' and `org-extend-today-until'."
  2211. :group 'org-time
  2212. :version "24.4"
  2213. :package-version '(Org . "8.0")
  2214. :type 'boolean)
  2215. (defcustom org-edit-timestamp-down-means-later nil
  2216. "Non-nil means S-down will increase the time in a time stamp.
  2217. When nil, S-up will increase."
  2218. :group 'org-time
  2219. :type 'boolean)
  2220. (defcustom org-calendar-follow-timestamp-change t
  2221. "Non-nil means make the calendar window follow timestamp changes.
  2222. When a timestamp is modified and the calendar window is visible, it will be
  2223. moved to the new date."
  2224. :group 'org-time
  2225. :type 'boolean)
  2226. (defgroup org-tags nil
  2227. "Options concerning tags in Org mode."
  2228. :tag "Org Tags"
  2229. :group 'org)
  2230. (defcustom org-tag-alist nil
  2231. "Default tags available in Org files.
  2232. The value of this variable is an alist. Associations either:
  2233. (TAG)
  2234. (TAG . SELECT)
  2235. (SPECIAL)
  2236. where TAG is a tag as a string, SELECT is character, used to
  2237. select that tag through the fast tag selection interface, and
  2238. SPECIAL is one of the following keywords: `:startgroup',
  2239. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2240. `:newline'. These keywords are used to define a hierarchy of
  2241. tags. See manual for details.
  2242. When this variable is nil, Org mode bases tag input on what is
  2243. already in the buffer. The value can be overridden locally by
  2244. using a TAGS keyword, e.g.,
  2245. #+TAGS: tag1 tag2
  2246. See also `org-tag-persistent-alist' to sidestep this behavior."
  2247. :group 'org-tags
  2248. :type '(repeat
  2249. (choice
  2250. (cons :tag "Tag with key"
  2251. (string :tag "Tag name")
  2252. (character :tag "Access char"))
  2253. (list :tag "Tag" (string :tag "Tag name"))
  2254. (const :tag "Start radio group" (:startgroup))
  2255. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2256. (const :tag "Group tags delimiter" (:grouptags))
  2257. (const :tag "End radio group" (:endgroup))
  2258. (const :tag "End tag group, non distinct" (:endgrouptag))
  2259. (const :tag "New line" (:newline)))))
  2260. (defcustom org-tag-persistent-alist nil
  2261. "Tags always available in Org files.
  2262. The value of this variable is an alist. Associations either:
  2263. (TAG)
  2264. (TAG . SELECT)
  2265. (SPECIAL)
  2266. where TAG is a tag as a string, SELECT is a character, used to
  2267. select that tag through the fast tag selection interface, and
  2268. SPECIAL is one of the following keywords: `:startgroup',
  2269. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2270. `:newline'. These keywords are used to define a hierarchy of
  2271. tags. See manual for details.
  2272. Unlike to `org-tag-alist', tags defined in this variable do not
  2273. depend on a local TAGS keyword. Instead, to disable these tags
  2274. on a per-file basis, insert anywhere in the file:
  2275. #+STARTUP: noptag"
  2276. :group 'org-tags
  2277. :type '(repeat
  2278. (choice
  2279. (cons :tag "Tag with key"
  2280. (string :tag "Tag name")
  2281. (character :tag "Access char"))
  2282. (list :tag "Tag" (string :tag "Tag name"))
  2283. (const :tag "Start radio group" (:startgroup))
  2284. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2285. (const :tag "Group tags delimiter" (:grouptags))
  2286. (const :tag "End radio group" (:endgroup))
  2287. (const :tag "End tag group, non distinct" (:endgrouptag))
  2288. (const :tag "New line" (:newline)))))
  2289. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2290. "If non-nil, always offer completion for all tags of all agenda files.
  2291. Setting this variable locally allows for dynamic generation of tag
  2292. completions in capture buffers.
  2293. (add-hook \\='org-capture-mode-hook
  2294. (lambda ()
  2295. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2296. :group 'org-tags
  2297. :version "24.1"
  2298. :type 'boolean)
  2299. (defvar org-file-tags nil
  2300. "List of tags that can be inherited by all entries in the file.
  2301. The tags will be inherited if the variable `org-use-tag-inheritance'
  2302. says they should be.
  2303. This variable is populated from #+FILETAGS lines.")
  2304. (defcustom org-use-fast-tag-selection 'auto
  2305. "Non-nil means use fast tag selection scheme.
  2306. This is a special interface to select and deselect tags with single keys.
  2307. When nil, fast selection is never used.
  2308. When the symbol `auto', fast selection is used if and only if selection
  2309. characters for tags have been configured, either through the variable
  2310. `org-tag-alist' or through a #+TAGS line in the buffer.
  2311. When t, fast selection is always used and selection keys are assigned
  2312. automatically if necessary."
  2313. :group 'org-tags
  2314. :type '(choice
  2315. (const :tag "Always" t)
  2316. (const :tag "Never" nil)
  2317. (const :tag "When selection characters are configured" auto)))
  2318. (defcustom org-fast-tag-selection-single-key nil
  2319. "Non-nil means fast tag selection exits after first change.
  2320. When nil, you have to press RET to exit it.
  2321. During fast tag selection, you can toggle this flag with `C-c'.
  2322. This variable can also have the value `expert'. In this case, the window
  2323. displaying the tags menu is not even shown, until you press `C-c' again."
  2324. :group 'org-tags
  2325. :type '(choice
  2326. (const :tag "No" nil)
  2327. (const :tag "Yes" t)
  2328. (const :tag "Expert" expert)))
  2329. (defvar org-fast-tag-selection-include-todo nil
  2330. "Non-nil means fast tags selection interface will also offer TODO states.
  2331. This is an undocumented feature, you should not rely on it.")
  2332. (defcustom org-tags-column -77
  2333. "The column to which tags should be indented in a headline.
  2334. If this number is positive, it specifies the column. If it is negative,
  2335. it means that the tags should be flushright to that column. For example,
  2336. -80 works well for a normal 80 character screen.
  2337. When 0, place tags directly after headline text, with only one space in
  2338. between."
  2339. :group 'org-tags
  2340. :type 'integer)
  2341. (defcustom org-auto-align-tags t
  2342. "Non-nil keeps tags aligned when modifying headlines.
  2343. Some operations (i.e. demoting) change the length of a headline and
  2344. therefore shift the tags around. With this option turned on, after
  2345. each such operation the tags are again aligned to `org-tags-column'."
  2346. :group 'org-tags
  2347. :type 'boolean)
  2348. (defcustom org-use-tag-inheritance t
  2349. "Non-nil means tags in levels apply also for sublevels.
  2350. When nil, only the tags directly given in a specific line apply there.
  2351. This may also be a list of tags that should be inherited, or a regexp that
  2352. matches tags that should be inherited. Additional control is possible
  2353. with the variable `org-tags-exclude-from-inheritance' which gives an
  2354. explicit list of tags to be excluded from inheritance, even if the value of
  2355. `org-use-tag-inheritance' would select it for inheritance.
  2356. If this option is t, a match early-on in a tree can lead to a large
  2357. number of matches in the subtree when constructing the agenda or creating
  2358. a sparse tree. If you only want to see the first match in a tree during
  2359. a search, check out the variable `org-tags-match-list-sublevels'."
  2360. :group 'org-tags
  2361. :type '(choice
  2362. (const :tag "Not" nil)
  2363. (const :tag "Always" t)
  2364. (repeat :tag "Specific tags" (string :tag "Tag"))
  2365. (regexp :tag "Tags matched by regexp")))
  2366. (defcustom org-tags-exclude-from-inheritance nil
  2367. "List of tags that should never be inherited.
  2368. This is a way to exclude a few tags from inheritance. For way to do
  2369. the opposite, to actively allow inheritance for selected tags,
  2370. see the variable `org-use-tag-inheritance'."
  2371. :group 'org-tags
  2372. :type '(repeat (string :tag "Tag")))
  2373. (defun org-tag-inherit-p (tag)
  2374. "Check if TAG is one that should be inherited."
  2375. (cond
  2376. ((member tag org-tags-exclude-from-inheritance) nil)
  2377. ((eq org-use-tag-inheritance t) t)
  2378. ((not org-use-tag-inheritance) nil)
  2379. ((stringp org-use-tag-inheritance)
  2380. (string-match org-use-tag-inheritance tag))
  2381. ((listp org-use-tag-inheritance)
  2382. (member tag org-use-tag-inheritance))
  2383. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2384. (defcustom org-tags-match-list-sublevels t
  2385. "Non-nil means list also sublevels of headlines matching a search.
  2386. This variable applies to tags/property searches, and also to stuck
  2387. projects because this search is based on a tags match as well.
  2388. When set to the symbol `indented', sublevels are indented with
  2389. leading dots.
  2390. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2391. the sublevels of a headline matching a tag search often also match
  2392. the same search. Listing all of them can create very long lists.
  2393. Setting this variable to nil causes subtrees of a match to be skipped.
  2394. This variable is semi-obsolete and probably should always be true. It
  2395. is better to limit inheritance to certain tags using the variables
  2396. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2397. :group 'org-tags
  2398. :type '(choice
  2399. (const :tag "No, don't list them" nil)
  2400. (const :tag "Yes, do list them" t)
  2401. (const :tag "List them, indented with leading dots" indented)))
  2402. (defcustom org-tags-sort-function nil
  2403. "When set, tags are sorted using this function as a comparator."
  2404. :group 'org-tags
  2405. :type '(choice
  2406. (const :tag "No sorting" nil)
  2407. (const :tag "Alphabetical" string-collate-lessp)
  2408. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2409. (function :tag "Custom function" nil)))
  2410. (defvar org-tags-history nil
  2411. "History of minibuffer reads for tags.")
  2412. (defvar org-last-tags-completion-table nil
  2413. "The last used completion table for tags.")
  2414. (defvar org-after-tags-change-hook nil
  2415. "Hook that is run after the tags in a line have changed.")
  2416. (defgroup org-properties nil
  2417. "Options concerning properties in Org mode."
  2418. :tag "Org Properties"
  2419. :group 'org)
  2420. (defcustom org-property-format "%-10s %s"
  2421. "How property key/value pairs should be formatted by `indent-line'.
  2422. When `indent-line' hits a property definition, it will format the line
  2423. according to this format, mainly to make sure that the values are
  2424. lined-up with respect to each other."
  2425. :group 'org-properties
  2426. :type 'string)
  2427. (defcustom org-properties-postprocess-alist nil
  2428. "Alist of properties and functions to adjust inserted values.
  2429. Elements of this alist must be of the form
  2430. ([string] [function])
  2431. where [string] must be a property name and [function] must be a
  2432. lambda expression: this lambda expression must take one argument,
  2433. the value to adjust, and return the new value as a string.
  2434. For example, this element will allow the property \"Remaining\"
  2435. to be updated wrt the relation between the \"Effort\" property
  2436. and the clock summary:
  2437. ((\"Remaining\" (lambda(value)
  2438. (let ((clocksum (org-clock-sum-current-item))
  2439. (effort (org-duration-to-minutes
  2440. (org-entry-get (point) \"Effort\"))))
  2441. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2442. :group 'org-properties
  2443. :version "24.1"
  2444. :type '(alist :key-type (string :tag "Property")
  2445. :value-type (function :tag "Function")))
  2446. (defcustom org-use-property-inheritance nil
  2447. "Non-nil means properties apply also for sublevels.
  2448. This setting is chiefly used during property searches. Turning it on can
  2449. cause significant overhead when doing a search, which is why it is not
  2450. on by default.
  2451. When nil, only the properties directly given in the current entry count.
  2452. When t, every property is inherited. The value may also be a list of
  2453. properties that should have inheritance, or a regular expression matching
  2454. properties that should be inherited.
  2455. However, note that some special properties use inheritance under special
  2456. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2457. and the properties ending in \"_ALL\" when they are used as descriptor
  2458. for valid values of a property.
  2459. Note for programmers:
  2460. When querying an entry with `org-entry-get', you can control if inheritance
  2461. should be used. By default, `org-entry-get' looks only at the local
  2462. properties. You can request inheritance by setting the inherit argument
  2463. to t (to force inheritance) or to `selective' (to respect the setting
  2464. in this variable)."
  2465. :group 'org-properties
  2466. :type '(choice
  2467. (const :tag "Not" nil)
  2468. (const :tag "Always" t)
  2469. (repeat :tag "Specific properties" (string :tag "Property"))
  2470. (regexp :tag "Properties matched by regexp")))
  2471. (defun org-property-inherit-p (property)
  2472. "Return a non-nil value if PROPERTY should be inherited."
  2473. (cond
  2474. ((eq org-use-property-inheritance t) t)
  2475. ((not org-use-property-inheritance) nil)
  2476. ((stringp org-use-property-inheritance)
  2477. (string-match org-use-property-inheritance property))
  2478. ((listp org-use-property-inheritance)
  2479. (member-ignore-case property org-use-property-inheritance))
  2480. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2481. (defcustom org-property-separators nil
  2482. "An alist to control how properties are combined.
  2483. The car of each item should be either a list of property names or
  2484. a regular expression, while the cdr should be the separator to
  2485. use when combining that property.
  2486. If an alist item cannot be found that matches a given property, a
  2487. single space will be used as the separator."
  2488. :group 'org-properties
  2489. :type '(alist :key-type (choice (repeat :tag "Properties" string)
  2490. (string :tag "Regular Expression"))
  2491. :value-type (restricted-sexp :tag "Separator"
  2492. :match-alternatives (stringp)
  2493. :value " ")))
  2494. (defun org--property-get-separator (property)
  2495. "Get the separator to use for combining PROPERTY."
  2496. (or
  2497. (catch 'separator
  2498. (dolist (spec org-property-separators)
  2499. (if (listp (car spec))
  2500. (if (member property (car spec))
  2501. (throw 'separator (cdr spec)))
  2502. (if (string-match-p (car spec) property)
  2503. (throw 'separator (cdr spec))))))
  2504. " "))
  2505. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2506. "The default column format, if no other format has been defined.
  2507. This variable can be set on the per-file basis by inserting a line
  2508. #+COLUMNS: %25ITEM ....."
  2509. :group 'org-properties
  2510. :type 'string)
  2511. (defcustom org-columns-default-format-for-agenda nil
  2512. "The default column format in an agenda buffer.
  2513. This will be used for column view in the agenda unless a format has
  2514. been set by adding `org-overriding-columns-format' to the local
  2515. settings list of a custom agenda view. When nil, the columns format
  2516. for the first item in the agenda list will be used, or as a fall-back,
  2517. `org-columns-default-format'."
  2518. :group 'org-properties
  2519. :type '(choice
  2520. (const :tag "No default" nil)
  2521. (string :tag "Format string")))
  2522. (defcustom org-columns-ellipses ".."
  2523. "The ellipses to be used when a field in column view is truncated.
  2524. When this is the empty string, as many characters as possible are shown,
  2525. but then there will be no visual indication that the field has been truncated.
  2526. When this is a string of length N, the last N characters of a truncated
  2527. field are replaced by this string. If the column is narrower than the
  2528. ellipses string, only part of the ellipses string will be shown."
  2529. :group 'org-properties
  2530. :type 'string)
  2531. (defconst org-global-properties-fixed
  2532. '(("VISIBILITY_ALL" . "folded children content all")
  2533. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2534. "List of property/value pairs that can be inherited by any entry.
  2535. These are fixed values, for the preset properties. The user variable
  2536. that can be used to add to this list is `org-global-properties'.
  2537. The entries in this list are cons cells where the car is a property
  2538. name and cdr is a string with the value. If the value represents
  2539. multiple items like an \"_ALL\" property, separate the items by
  2540. spaces.")
  2541. (defcustom org-global-properties nil
  2542. "List of property/value pairs that can be inherited by any entry.
  2543. This list will be combined with the constant `org-global-properties-fixed'.
  2544. The entries in this list are cons cells where the car is a property
  2545. name and cdr is a string with the value.
  2546. Buffer local properties are added either by a document property drawer
  2547. :PROPERTIES:
  2548. :NAME: VALUE
  2549. :END:
  2550. or by adding lines like
  2551. #+PROPERTY: NAME VALUE"
  2552. :group 'org-properties
  2553. :type '(repeat
  2554. (cons (string :tag "Property")
  2555. (string :tag "Value"))))
  2556. (defvar-local org-keyword-properties nil
  2557. "List of property/value pairs inherited by any entry.
  2558. Valid for the current buffer. This variable is populated from
  2559. PROPERTY keywords.
  2560. Note that properties are defined also in property drawers.
  2561. Properties defined there take precedence over properties defined
  2562. as keywords.")
  2563. (defgroup org-agenda nil
  2564. "Options concerning agenda views in Org mode."
  2565. :tag "Org Agenda"
  2566. :group 'org)
  2567. (defvar-local org-category nil
  2568. "Variable used by Org files to set a category for agenda display.
  2569. There are multiple ways to set the category. One way is to set
  2570. it in the document property drawer. For example:
  2571. :PROPERTIES:
  2572. :CATEGORY: ELisp
  2573. :END:
  2574. Other ways to define it is as an Emacs file variable, for example
  2575. # -*- mode: org; org-category: \"ELisp\"
  2576. or for the file to contain a special line:
  2577. #+CATEGORY: ELisp
  2578. If the file does not specify a category, then file's base name
  2579. is used instead.")
  2580. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2581. (defcustom org-agenda-files nil
  2582. "The files to be used for agenda display.
  2583. If an entry is a directory, all files in that directory that are matched
  2584. by `org-agenda-file-regexp' will be part of the file list.
  2585. If the value of the variable is not a list but a single file name, then
  2586. the list of agenda files is actually stored and maintained in that file,
  2587. one agenda file per line. In this file paths can be given relative to
  2588. `org-directory'. Tilde expansion and environment variable substitution
  2589. are also made.
  2590. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2591. and removed with `\\[org-remove-file]'."
  2592. :group 'org-agenda
  2593. :type '(choice
  2594. (repeat :tag "List of files and directories" file)
  2595. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2596. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2597. "Regular expression to match files for `org-agenda-files'.
  2598. If any element in the list in that variable contains a directory instead
  2599. of a normal file, all files in that directory that are matched by this
  2600. regular expression will be included."
  2601. :group 'org-agenda
  2602. :type 'regexp)
  2603. (defvaralias 'org-agenda-multi-occur-extra-files
  2604. 'org-agenda-text-search-extra-files)
  2605. (defcustom org-agenda-text-search-extra-files nil
  2606. "List of extra files to be searched by text search commands.
  2607. These files will be searched in addition to the agenda files by the
  2608. commands `org-search-view' (`\\[org-agenda] s') \
  2609. and `org-occur-in-agenda-files'.
  2610. Note that these files will only be searched for text search commands,
  2611. not for the other agenda views like todo lists, tag searches or the weekly
  2612. agenda. This variable is intended to list notes and possibly archive files
  2613. that should also be searched by these two commands.
  2614. In fact, if the first element in the list is the symbol `agenda-archives',
  2615. then all archive files of all agenda files will be added to the search
  2616. scope."
  2617. :group 'org-agenda
  2618. :type '(set :greedy t
  2619. (const :tag "Agenda Archives" agenda-archives)
  2620. (repeat :inline t (file))))
  2621. (defcustom org-agenda-skip-unavailable-files nil
  2622. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2623. A nil value means to remove them, after a query, from the list."
  2624. :group 'org-agenda
  2625. :type 'boolean)
  2626. (defgroup org-latex nil
  2627. "Options for embedding LaTeX code into Org mode."
  2628. :tag "Org LaTeX"
  2629. :group 'org)
  2630. (defcustom org-format-latex-options
  2631. '(:foreground default :background default :scale 1.0
  2632. :html-foreground "Black" :html-background "Transparent"
  2633. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2634. "Options for creating images from LaTeX fragments.
  2635. This is a property list with the following properties:
  2636. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2637. `default' means use the foreground of the default face.
  2638. `auto' means use the foreground from the text face.
  2639. :background the background color, or \"Transparent\".
  2640. `default' means use the background of the default face.
  2641. `auto' means use the background from the text face.
  2642. :scale a scaling factor for the size of the images, to get more pixels
  2643. :html-foreground, :html-background, :html-scale
  2644. the same numbers for HTML export.
  2645. :matchers a list indicating which matchers should be used to
  2646. find LaTeX fragments. Valid members of this list are:
  2647. \"begin\" find environments
  2648. \"$1\" find single characters surrounded by $.$
  2649. \"$\" find math expressions surrounded by $...$
  2650. \"$$\" find math expressions surrounded by $$....$$
  2651. \"\\(\" find math expressions surrounded by \\(...\\)
  2652. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2653. :group 'org-latex
  2654. :type 'plist)
  2655. (defcustom org-format-latex-signal-error t
  2656. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2657. When nil, just push out a message."
  2658. :group 'org-latex
  2659. :version "24.1"
  2660. :type 'boolean)
  2661. (defcustom org-latex-to-mathml-jar-file nil
  2662. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2663. Use this to specify additional executable file say a jar file.
  2664. When using MathToWeb as the converter, specify the full-path to
  2665. your mathtoweb.jar file."
  2666. :group 'org-latex
  2667. :version "24.1"
  2668. :type '(choice
  2669. (const :tag "None" nil)
  2670. (file :tag "JAR file" :must-match t)))
  2671. (defcustom org-latex-to-mathml-convert-command nil
  2672. "Command to convert LaTeX fragments to MathML.
  2673. Replace format-specifiers in the command as noted below and use
  2674. `shell-command' to convert LaTeX to MathML.
  2675. %j: Executable file in fully expanded form as specified by
  2676. `org-latex-to-mathml-jar-file'.
  2677. %I: Input LaTeX file in fully expanded form.
  2678. %i: The latex fragment to be converted.
  2679. %o: Output MathML file.
  2680. This command is used by `org-create-math-formula'.
  2681. When using MathToWeb as the converter, set this option to
  2682. \"java -jar %j -unicode -force -df %o %I\".
  2683. When using LaTeXML set this option to
  2684. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2685. :group 'org-latex
  2686. :version "24.1"
  2687. :type '(choice
  2688. (const :tag "None" nil)
  2689. (string :tag "\nShell command")))
  2690. (defcustom org-latex-to-html-convert-command nil
  2691. "Command to convert LaTeX fragments to HTML.
  2692. This command is very open-ended: the output of the command will
  2693. directly replace the LaTeX fragment in the resulting HTML.
  2694. Replace format-specifiers in the command as noted below and use
  2695. `shell-command' to convert LaTeX to HTML.
  2696. %i: The LaTeX fragment to be converted.
  2697. For example, this could be used with LaTeXML as
  2698. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2699. :group 'org-latex
  2700. :package-version '(Org . "9.4")
  2701. :type '(choice
  2702. (const :tag "None" nil)
  2703. (string :tag "Shell command")))
  2704. (defcustom org-preview-latex-default-process 'dvipng
  2705. "The default process to convert LaTeX fragments to image files.
  2706. All available processes and theirs documents can be found in
  2707. `org-preview-latex-process-alist', which see."
  2708. :group 'org-latex
  2709. :version "26.1"
  2710. :package-version '(Org . "9.0")
  2711. :type 'symbol)
  2712. (defcustom org-preview-latex-process-alist
  2713. '((dvipng
  2714. :programs ("latex" "dvipng")
  2715. :description "dvi > png"
  2716. :message "you need to install the programs: latex and dvipng."
  2717. :image-input-type "dvi"
  2718. :image-output-type "png"
  2719. :image-size-adjust (1.0 . 1.0)
  2720. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2721. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2722. :transparent-image-converter
  2723. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2724. (dvisvgm
  2725. :programs ("latex" "dvisvgm")
  2726. :description "dvi > svg"
  2727. :message "you need to install the programs: latex and dvisvgm."
  2728. :image-input-type "dvi"
  2729. :image-output-type "svg"
  2730. :image-size-adjust (1.7 . 1.5)
  2731. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2732. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2733. (imagemagick
  2734. :programs ("latex" "convert")
  2735. :description "pdf > png"
  2736. :message "you need to install the programs: latex and imagemagick."
  2737. :image-input-type "pdf"
  2738. :image-output-type "png"
  2739. :image-size-adjust (1.0 . 1.0)
  2740. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2741. :image-converter
  2742. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2743. "Definitions of external processes for LaTeX previewing.
  2744. Org mode can use some external commands to generate TeX snippet's images for
  2745. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2746. `org-create-formula-image' how to call them.
  2747. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2748. PROPERTIES accepts the following attributes:
  2749. :programs list of strings, required programs.
  2750. :description string, describe the process.
  2751. :message string, message it when required programs cannot be found.
  2752. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2753. :image-output-type string, output file type of image converter (e.g., \"png\").
  2754. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2755. image size showed in buffer and the cdr element is for
  2756. HTML file. This option is only useful for process
  2757. developers, users should use variable
  2758. `org-format-latex-options' instead.
  2759. :post-clean list of strings, files matched are to be cleaned up once
  2760. the image is generated. When nil, the files with \".dvi\",
  2761. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2762. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2763. be cleaned up.
  2764. :latex-header list of strings, the LaTeX header of the snippet file.
  2765. When nil, the fallback value is used instead, which is
  2766. controlled by `org-format-latex-header',
  2767. `org-latex-default-packages-alist' and
  2768. `org-latex-packages-alist', which see.
  2769. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2770. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2771. replaced with values defined below.
  2772. :image-converter list of image converter commands strings. Each of them is
  2773. given to the shell and supports any of the following
  2774. place-holders defined below.
  2775. If set, :transparent-image-converter is used instead of :image-converter to
  2776. convert an image when the background color is nil or \"Transparent\".
  2777. Place-holders used by `:image-converter' and `:latex-compiler':
  2778. %f input file name
  2779. %b base name of input file
  2780. %o base directory of input file
  2781. %O absolute output file name
  2782. Place-holders only used by `:image-converter':
  2783. %D dpi, which is used to adjust image size by some processing commands.
  2784. %S the image size scale ratio, which is used to adjust image size by some
  2785. processing commands."
  2786. :group 'org-latex
  2787. :version "26.1"
  2788. :package-version '(Org . "9.0")
  2789. :type '(alist :tag "LaTeX to image backends"
  2790. :value-type (plist)))
  2791. (defcustom org-preview-latex-image-directory "ltximg/"
  2792. "Path to store latex preview images.
  2793. A relative path here creates many directories relative to the
  2794. processed Org files paths. An absolute path puts all preview
  2795. images at the same place."
  2796. :group 'org-latex
  2797. :version "26.1"
  2798. :package-version '(Org . "9.0")
  2799. :type 'string)
  2800. (defun org-format-latex-mathml-available-p ()
  2801. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2802. (save-match-data
  2803. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2804. org-latex-to-mathml-convert-command)
  2805. (let ((executable (car (split-string
  2806. org-latex-to-mathml-convert-command))))
  2807. (when (executable-find executable)
  2808. (if (string-match
  2809. "%j" org-latex-to-mathml-convert-command)
  2810. (file-readable-p org-latex-to-mathml-jar-file)
  2811. t))))))
  2812. (defcustom org-format-latex-header "\\documentclass{article}
  2813. \\usepackage[usenames]{color}
  2814. \[DEFAULT-PACKAGES]
  2815. \[PACKAGES]
  2816. \\pagestyle{empty} % do not remove
  2817. % The settings below are copied from fullpage.sty
  2818. \\setlength{\\textwidth}{\\paperwidth}
  2819. \\addtolength{\\textwidth}{-3cm}
  2820. \\setlength{\\oddsidemargin}{1.5cm}
  2821. \\addtolength{\\oddsidemargin}{-2.54cm}
  2822. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2823. \\setlength{\\textheight}{\\paperheight}
  2824. \\addtolength{\\textheight}{-\\headheight}
  2825. \\addtolength{\\textheight}{-\\headsep}
  2826. \\addtolength{\\textheight}{-\\footskip}
  2827. \\addtolength{\\textheight}{-3cm}
  2828. \\setlength{\\topmargin}{1.5cm}
  2829. \\addtolength{\\topmargin}{-2.54cm}"
  2830. "The document header used for processing LaTeX fragments.
  2831. It is imperative that this header make sure that no page number
  2832. appears on the page. The package defined in the variables
  2833. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2834. will either replace the placeholder \"[PACKAGES]\" in this
  2835. header, or they will be appended."
  2836. :group 'org-latex
  2837. :type 'string)
  2838. (defun org-set-packages-alist (var val)
  2839. "Set the packages alist and make sure it has 3 elements per entry."
  2840. (set-default-toplevel-value var (mapcar (lambda (x)
  2841. (if (and (consp x) (= (length x) 2))
  2842. (list (car x) (nth 1 x) t)
  2843. x))
  2844. val)))
  2845. (defun org-get-packages-alist (var)
  2846. "Get the packages alist and make sure it has 3 elements per entry."
  2847. (mapcar (lambda (x)
  2848. (if (and (consp x) (= (length x) 2))
  2849. (list (car x) (nth 1 x) t)
  2850. x))
  2851. (default-value var)))
  2852. (defcustom org-latex-default-packages-alist
  2853. '(("AUTO" "inputenc" t ("pdflatex"))
  2854. ("T1" "fontenc" t ("pdflatex"))
  2855. ("" "graphicx" t)
  2856. ("" "longtable" nil)
  2857. ("" "wrapfig" nil)
  2858. ("" "rotating" nil)
  2859. ("normalem" "ulem" t)
  2860. ("" "amsmath" t)
  2861. ("" "amssymb" t)
  2862. ("" "capt-of" nil)
  2863. ("" "hyperref" nil))
  2864. "Alist of default packages to be inserted in the header.
  2865. Change this only if one of the packages here causes an
  2866. incompatibility with another package you are using.
  2867. The packages in this list are needed by one part or another of
  2868. Org mode to function properly:
  2869. - inputenc, fontenc: for basic font and character selection
  2870. - graphicx: for including images
  2871. - longtable: For multipage tables
  2872. - wrapfig: for figure placement
  2873. - rotating: for sideways figures and tables
  2874. - ulem: for underline and strike-through
  2875. - amsmath: for subscript and superscript and math environments
  2876. - amssymb: for various symbols used for interpreting the entities
  2877. in `org-entities'. You can skip some of this package if you don't
  2878. use any of the symbols.
  2879. - capt-of: for captions outside of floats
  2880. - hyperref: for cross references
  2881. Therefore you should not modify this variable unless you know
  2882. what you are doing. The one reason to change it anyway is that
  2883. you might be loading some other package that conflicts with one
  2884. of the default packages. Each element is either a cell or
  2885. a string.
  2886. A cell is of the format
  2887. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2888. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2889. when compiling LaTeX snippets into images for inclusion into
  2890. non-LaTeX output.
  2891. COMPILERS is a list of compilers that should include the package,
  2892. see `org-latex-compiler'. If the document compiler is not in the
  2893. list, and the list is non-nil, the package will not be inserted
  2894. in the final document.
  2895. A string will be inserted as-is in the header of the document."
  2896. :group 'org-latex
  2897. :group 'org-export-latex
  2898. :set 'org-set-packages-alist
  2899. :get 'org-get-packages-alist
  2900. :version "26.1"
  2901. :package-version '(Org . "8.3")
  2902. :type '(repeat
  2903. (choice
  2904. (list :tag "options/package pair"
  2905. (string :tag "options")
  2906. (string :tag "package")
  2907. (boolean :tag "Snippet")
  2908. (choice
  2909. (const :tag "For all compilers" nil)
  2910. (repeat :tag "Allowed compiler" string)))
  2911. (string :tag "A line of LaTeX"))))
  2912. (defcustom org-latex-packages-alist nil
  2913. "Alist of packages to be inserted in every LaTeX header.
  2914. These will be inserted after `org-latex-default-packages-alist'.
  2915. Each element is either a cell or a string.
  2916. A cell is of the format:
  2917. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2918. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2919. needed when turning LaTeX snippets into images for inclusion into
  2920. non-LaTeX output.
  2921. COMPILERS is a list of compilers that should include the package,
  2922. see `org-latex-compiler'. If the document compiler is not in the
  2923. list, and the list is non-nil, the package will not be inserted
  2924. in the final document.
  2925. A string will be inserted as-is in the header of the document.
  2926. Make sure that you only list packages here which:
  2927. - you want in every file;
  2928. - do not conflict with the setup in `org-format-latex-header';
  2929. - do not conflict with the default packages in
  2930. `org-latex-default-packages-alist'."
  2931. :group 'org-latex
  2932. :group 'org-export-latex
  2933. :set 'org-set-packages-alist
  2934. :get 'org-get-packages-alist
  2935. :type '(repeat
  2936. (choice
  2937. (list :tag "options/package pair"
  2938. (string :tag "options")
  2939. (string :tag "package")
  2940. (boolean :tag "Snippet"))
  2941. (string :tag "A line of LaTeX"))))
  2942. (defgroup org-appearance nil
  2943. "Settings for Org mode appearance."
  2944. :tag "Org Appearance"
  2945. :group 'org)
  2946. (defcustom org-level-color-stars-only nil
  2947. "Non-nil means fontify only the stars in each headline.
  2948. When nil, the entire headline is fontified.
  2949. Changing it requires restart of `font-lock-mode' to become effective
  2950. also in regions already fontified."
  2951. :group 'org-appearance
  2952. :type 'boolean)
  2953. (defcustom org-hide-leading-stars nil
  2954. "Non-nil means hide the first N-1 stars in a headline.
  2955. This works by using the face `org-hide' for these stars. This
  2956. face is white for a light background, and black for a dark
  2957. background. You may have to customize the face `org-hide' to
  2958. make this work.
  2959. Changing it requires restart of `font-lock-mode' to become effective
  2960. also in regions already fontified.
  2961. You may also set this on a per-file basis by adding one of the following
  2962. lines to the buffer:
  2963. #+STARTUP: hidestars
  2964. #+STARTUP: showstars"
  2965. :group 'org-appearance
  2966. :type 'boolean)
  2967. (defcustom org-hidden-keywords nil
  2968. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2969. For example, a value (title) for this list makes the document's title
  2970. appear in the buffer without the initial \"#+TITLE:\" part."
  2971. :group 'org-appearance
  2972. :package-version '(Org . "9.5")
  2973. :type '(set (const :tag "#+AUTHOR" author)
  2974. (const :tag "#+DATE" date)
  2975. (const :tag "#+EMAIL" email)
  2976. (const :tag "#+SUBTITLE" subtitle)
  2977. (const :tag "#+TITLE" title)))
  2978. (defcustom org-custom-properties nil
  2979. "List of properties (as strings) with a special meaning.
  2980. The default use of these custom properties is to let the user
  2981. hide them with `org-toggle-custom-properties-visibility'."
  2982. :group 'org-properties
  2983. :group 'org-appearance
  2984. :version "24.3"
  2985. :type '(repeat (string :tag "Property Name")))
  2986. (defcustom org-fontify-todo-headline nil
  2987. "Non-nil means change the face of a headline if it is marked as TODO.
  2988. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2989. When this is non-nil, the headline after the keyword is set to the
  2990. `org-headline-todo' as an additional indication."
  2991. :group 'org-appearance
  2992. :package-version '(Org . "9.4")
  2993. :type 'boolean
  2994. :safe #'booleanp)
  2995. (defcustom org-fontify-done-headline t
  2996. "Non-nil means change the face of a headline if it is marked DONE.
  2997. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2998. When this is non-nil, the headline after the keyword is set to the
  2999. `org-headline-done' as an additional indication."
  3000. :group 'org-appearance
  3001. :package-version '(Org . "9.4")
  3002. :type 'boolean)
  3003. (defcustom org-fontify-emphasized-text t
  3004. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3005. Changing this variable requires a restart of Emacs to take effect."
  3006. :group 'org-appearance
  3007. :type 'boolean)
  3008. (defcustom org-fontify-whole-heading-line nil
  3009. "Non-nil means fontify the whole line for headings.
  3010. This is useful when setting a background color for the
  3011. org-level-* faces."
  3012. :group 'org-appearance
  3013. :type 'boolean)
  3014. (defcustom org-fontify-whole-block-delimiter-line t
  3015. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3016. This is useful when setting a background color for the
  3017. org-block-begin-line and org-block-end-line faces."
  3018. :group 'org-appearance
  3019. :type 'boolean)
  3020. (defcustom org-highlight-latex-and-related nil
  3021. "Non-nil means highlight LaTeX related syntax in the buffer.
  3022. When non-nil, the value should be a list containing any of the
  3023. following symbols:
  3024. `native' Highlight LaTeX snippets and environments natively.
  3025. `latex' Highlight LaTeX snippets and environments.
  3026. `script' Highlight subscript and superscript.
  3027. `entities' Highlight entities."
  3028. :group 'org-appearance
  3029. :version "24.4"
  3030. :package-version '(Org . "8.0")
  3031. :type '(choice
  3032. (const :tag "No highlighting" nil)
  3033. (set :greedy t :tag "Highlight"
  3034. (const :tag "LaTeX snippets and environments (native)" native)
  3035. (const :tag "LaTeX snippets and environments" latex)
  3036. (const :tag "Subscript and superscript" script)
  3037. (const :tag "Entities" entities))))
  3038. (defcustom org-hide-emphasis-markers nil
  3039. "Non-nil mean font-lock should hide the emphasis marker characters."
  3040. :group 'org-appearance
  3041. :type 'boolean
  3042. :safe #'booleanp)
  3043. (defcustom org-hide-macro-markers nil
  3044. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3045. :group 'org-appearance
  3046. :type 'boolean)
  3047. (defcustom org-pretty-entities nil
  3048. "Non-nil means show entities as UTF8 characters.
  3049. When nil, the \\name form remains in the buffer."
  3050. :group 'org-appearance
  3051. :version "24.1"
  3052. :type 'boolean)
  3053. (defcustom org-pretty-entities-include-sub-superscripts t
  3054. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3055. :group 'org-appearance
  3056. :version "24.1"
  3057. :type 'boolean)
  3058. (defvar org-emph-re nil
  3059. "Regular expression for matching emphasis.
  3060. After a match, the match groups contain these elements:
  3061. 0 The match of the full regular expression, including the characters
  3062. before and after the proper match
  3063. 1 The character before the proper match, or empty at beginning of line
  3064. 2 The proper match, including the leading and trailing markers
  3065. 3 The leading marker like * or /, indicating the type of highlighting
  3066. 4 The text between the emphasis markers, not including the markers
  3067. 5 The character after the match, empty at the end of a line")
  3068. (defvar org-verbatim-re nil
  3069. "Regular expression for matching verbatim text.")
  3070. (defvar org-emphasis-regexp-components) ; defined just below
  3071. (defvar org-emphasis-alist) ; defined just below
  3072. (defun org-set-emph-re (var val)
  3073. "Set variable and compute the emphasis regular expression."
  3074. (set-default-toplevel-value var val)
  3075. (when (and (boundp 'org-emphasis-alist)
  3076. (boundp 'org-emphasis-regexp-components)
  3077. org-emphasis-alist org-emphasis-regexp-components)
  3078. (pcase-let*
  3079. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3080. (body (if (<= nl 0) body
  3081. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3082. (template
  3083. (format (concat "\\([%s]\\|^\\)" ;before markers
  3084. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3085. "\\([%s]\\|$\\)") ;after markers
  3086. pre border border body border post)))
  3087. (setq org-emph-re (format template "*/_+"))
  3088. (setq org-verbatim-re (format template "=~")))))
  3089. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3090. ;; set this option proved cumbersome. See this message/thread:
  3091. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3092. (defvar org-emphasis-regexp-components
  3093. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3094. "Components used to build the regular expression for emphasis.
  3095. This is a list with five entries. Terminology: In an emphasis string
  3096. like \" *strong word* \", we call the initial space PREMATCH, the final
  3097. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3098. and \"trong wor\" is the body. The different components in this variable
  3099. specify what is allowed/forbidden in each part:
  3100. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3101. post Chars allowed as postmatch. End of line will be allowed too.
  3102. border The chars *forbidden* as border characters.
  3103. body-regexp A regexp like \".\" to match a body character. Don't use
  3104. non-shy groups here, and don't allow newline here.
  3105. newline The maximum number of newlines allowed in an emphasis exp.
  3106. You need to reload Org or to restart Emacs after setting this.")
  3107. (defcustom org-emphasis-alist
  3108. '(("*" bold)
  3109. ("/" italic)
  3110. ("_" underline)
  3111. ("=" org-verbatim verbatim)
  3112. ("~" org-code verbatim)
  3113. ("+" (:strike-through t)))
  3114. "Alist of characters and faces to emphasize text.
  3115. Text starting and ending with a special character will be emphasized,
  3116. for example *bold*, _underlined_ and /italic/. This variable sets the
  3117. marker characters and the face to be used by font-lock for highlighting
  3118. in Org buffers.
  3119. You need to reload Org or to restart Emacs after customizing this."
  3120. :group 'org-appearance
  3121. :set 'org-set-emph-re
  3122. :version "24.4"
  3123. :package-version '(Org . "8.0")
  3124. :type '(repeat
  3125. (list
  3126. (string :tag "Marker character")
  3127. (choice
  3128. (face :tag "Font-lock-face")
  3129. (plist :tag "Face property list"))
  3130. (option (const verbatim)))))
  3131. (defvar org-protecting-blocks '("src" "example" "export")
  3132. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3133. This is needed for font-lock setup.")
  3134. ;;; Functions and variables from their packages
  3135. ;; Declared here to avoid compiler warnings
  3136. (defvar mark-active)
  3137. ;; Various packages
  3138. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3139. (declare-function calendar-forward-day "cal-move" (arg))
  3140. (declare-function calendar-goto-date "cal-move" (date))
  3141. (declare-function calendar-goto-today "cal-move" ())
  3142. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3143. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3144. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3145. (declare-function cdlatex-tab "ext:cdlatex" ())
  3146. (declare-function dired-get-filename
  3147. "dired"
  3148. (&optional localp no-error-if-not-filep))
  3149. (declare-function iswitchb-read-buffer
  3150. "iswitchb"
  3151. (prompt &optional
  3152. default require-match _predicate start matches-set))
  3153. (declare-function org-agenda-change-all-lines
  3154. "org-agenda"
  3155. (newhead hdmarker &optional fixface just-this))
  3156. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3157. "org-agenda"
  3158. (&optional end))
  3159. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3160. (declare-function org-agenda-format-item
  3161. "org-agenda"
  3162. (extra txt &optional level category tags dotime
  3163. remove-re habitp))
  3164. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3165. (declare-function org-agenda-save-markers-for-cut-and-paste
  3166. "org-agenda"
  3167. (beg end))
  3168. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3169. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3170. (declare-function org-attach-expand "org-attach" (file))
  3171. (declare-function org-attach-reveal "org-attach" ())
  3172. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3173. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3174. (declare-function org-indent-mode "org-indent" (&optional arg))
  3175. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3176. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3177. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3178. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3179. (declare-function parse-time-string "parse-time" (string))
  3180. (defvar align-mode-rules-list)
  3181. (defvar calc-embedded-close-formula)
  3182. (defvar calc-embedded-open-formula)
  3183. (defvar calc-embedded-open-mode)
  3184. (defvar font-lock-unfontify-region-function)
  3185. (defvar iswitchb-temp-buflist)
  3186. (defvar org-agenda-tags-todo-honor-ignore-options)
  3187. (defvar remember-data-file)
  3188. (defvar texmathp-why)
  3189. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3190. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3191. (declare-function org-resolve-clocks "org-clock"
  3192. (&optional also-non-dangling-p prompt last-valid))
  3193. (defvar org-clock-start-time)
  3194. (defvar org-clock-marker (make-marker)
  3195. "Marker recording the last clock-in.")
  3196. (defvar org-clock-hd-marker (make-marker)
  3197. "Marker recording the last clock-in, but the headline position.")
  3198. (defvar org-clock-heading ""
  3199. "The heading of the current clock entry.")
  3200. (defun org-clocking-buffer ()
  3201. "Return the buffer where the clock is currently running.
  3202. Return nil if no clock is running."
  3203. (marker-buffer org-clock-marker))
  3204. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3205. (defun org-check-running-clock ()
  3206. "Check if the current buffer contains the running clock.
  3207. If yes, offer to stop it and to save the buffer with the changes."
  3208. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3209. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3210. (buffer-name))))
  3211. (org-clock-out)
  3212. (when (y-or-n-p "Save changed buffer?")
  3213. (save-buffer))))
  3214. (defun org-clocktable-try-shift (dir n)
  3215. "Check if this line starts a clock table, if yes, shift the time block."
  3216. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3217. (org-clocktable-shift dir n)))
  3218. ;;;###autoload
  3219. (defun org-clock-persistence-insinuate ()
  3220. "Set up hooks for clock persistence."
  3221. (require 'org-clock)
  3222. (add-hook 'org-mode-hook 'org-clock-load)
  3223. (add-hook 'kill-emacs-hook 'org-clock-save))
  3224. (defun org-clock-auto-clockout-insinuate ()
  3225. "Set up hook for auto clocking out when Emacs is idle.
  3226. See `org-clock-auto-clockout-timer'.
  3227. This function is meant to be added to the user configuration."
  3228. (require 'org-clock)
  3229. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3230. (defgroup org-archive nil
  3231. "Options concerning archiving in Org mode."
  3232. :tag "Org Archive"
  3233. :group 'org-structure)
  3234. (defcustom org-archive-location "%s_archive::"
  3235. "The location where subtrees should be archived.
  3236. The value of this variable is a string, consisting of two parts,
  3237. separated by a double-colon. The first part is a filename and
  3238. the second part is a headline.
  3239. When the filename is omitted, archiving happens in the same file.
  3240. %s in the filename will be replaced by the current file
  3241. name (without the directory part). Archiving to a different file
  3242. is useful to keep archived entries from contributing to the
  3243. Org Agenda.
  3244. The archived entries will be filed as subtrees of the specified
  3245. headline. When the headline is omitted, the subtrees are simply
  3246. filed away at the end of the file, as top-level entries. Also in
  3247. the heading you can use %s to represent the file name, this can be
  3248. useful when using the same archive for a number of different files.
  3249. Here are a few examples:
  3250. \"%s_archive::\"
  3251. If the current file is Projects.org, archive in file
  3252. Projects.org_archive, as top-level trees. This is the default.
  3253. \"::* Archived Tasks\"
  3254. Archive in the current file, under the top-level headline
  3255. \"* Archived Tasks\".
  3256. \"~/org/archive.org::\"
  3257. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3258. \"~/org/archive.org::* From %s\"
  3259. Archive in file ~/org/archive.org (absolute path), under headlines
  3260. \"From FILENAME\" where file name is the current file name.
  3261. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3262. The \"datetree/\" string is special, signifying to archive
  3263. items to the datetree. Items are placed in either the CLOSED
  3264. date of the item, or the current date if there is no CLOSED date.
  3265. The heading will be a subentry to the current date. There doesn't
  3266. need to be a heading, but there always needs to be a slash after
  3267. datetree. For example, to store archived items directly in the
  3268. datetree, use \"~/org/datetree.org::datetree/\".
  3269. \"basement::** Finished Tasks\"
  3270. Archive in file ./basement (relative path), as level 3 trees
  3271. below the level 2 heading \"** Finished Tasks\".
  3272. You may define it locally by setting an ARCHIVE property. If
  3273. such a property is found in the file or in an entry, and anywhere
  3274. up the hierarchy, it will be used.
  3275. You can also set it for the whole file using the keyword-syntax:
  3276. #+ARCHIVE: basement::** Finished Tasks"
  3277. :group 'org-archive
  3278. :type 'string)
  3279. (defcustom org-agenda-skip-archived-trees t
  3280. "Non-nil means the agenda will skip any items located in archived trees.
  3281. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3282. variable is no longer recommended, you should leave it at the value t.
  3283. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3284. :group 'org-archive
  3285. :group 'org-agenda-skip
  3286. :type 'boolean)
  3287. (defcustom org-columns-skip-archived-trees t
  3288. "Non-nil means ignore archived trees when creating column view."
  3289. :group 'org-archive
  3290. :group 'org-properties
  3291. :type 'boolean)
  3292. (defcustom org-sparse-tree-open-archived-trees nil
  3293. "Non-nil means sparse tree construction shows matches in archived trees.
  3294. When nil, matches in these trees are highlighted, but the trees are kept in
  3295. collapsed state."
  3296. :group 'org-archive
  3297. :group 'org-sparse-trees
  3298. :type 'boolean)
  3299. (defcustom org-sparse-tree-default-date-type nil
  3300. "The default date type when building a sparse tree.
  3301. When this is nil, a date is a scheduled or a deadline timestamp.
  3302. Otherwise, these types are allowed:
  3303. all: all timestamps
  3304. active: only active timestamps (<...>)
  3305. inactive: only inactive timestamps ([...])
  3306. scheduled: only scheduled timestamps
  3307. deadline: only deadline timestamps"
  3308. :type '(choice (const :tag "Scheduled or deadline" nil)
  3309. (const :tag "All timestamps" all)
  3310. (const :tag "Only active timestamps" active)
  3311. (const :tag "Only inactive timestamps" inactive)
  3312. (const :tag "Only scheduled timestamps" scheduled)
  3313. (const :tag "Only deadline timestamps" deadline)
  3314. (const :tag "Only closed timestamps" closed))
  3315. :version "26.1"
  3316. :package-version '(Org . "8.3")
  3317. :group 'org-sparse-trees)
  3318. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3319. ;; Declare Column View Code
  3320. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3321. (declare-function org-columns-compute "org-colview" (property))
  3322. ;; Declare ID code
  3323. (declare-function org-id-store-link "org-id")
  3324. (declare-function org-id-locations-load "org-id")
  3325. (declare-function org-id-locations-save "org-id")
  3326. (defvar org-id-track-globally)
  3327. ;;; Variables for pre-computed regular expressions, all buffer local
  3328. (defvar-local org-todo-regexp nil
  3329. "Matches any of the TODO state keywords.
  3330. Since TODO keywords are case-sensitive, `case-fold-search' is
  3331. expected to be bound to nil when matching against this regexp.")
  3332. (defvar-local org-not-done-regexp nil
  3333. "Matches any of the TODO state keywords except the last one.
  3334. Since TODO keywords are case-sensitive, `case-fold-search' is
  3335. expected to be bound to nil when matching against this regexp.")
  3336. (defvar-local org-not-done-heading-regexp nil
  3337. "Matches a TODO headline that is not done.
  3338. Since TODO keywords are case-sensitive, `case-fold-search' is
  3339. expected to be bound to nil when matching against this regexp.")
  3340. (defvar-local org-todo-line-regexp nil
  3341. "Matches a headline and puts TODO state into group 2 if present.
  3342. Since TODO keywords are case-sensitive, `case-fold-search' is
  3343. expected to be bound to nil when matching against this regexp.")
  3344. (defvar-local org-complex-heading-regexp nil
  3345. "Matches a headline and puts everything into groups:
  3346. group 1: Stars
  3347. group 2: The TODO keyword, maybe
  3348. group 3: Priority cookie
  3349. group 4: True headline
  3350. group 5: Tags
  3351. Since TODO keywords are case-sensitive, `case-fold-search' is
  3352. expected to be bound to nil when matching against this regexp.")
  3353. (defvar-local org-complex-heading-regexp-format nil
  3354. "Printf format to make regexp to match an exact headline.
  3355. This regexp will match the headline of any node which has the
  3356. exact headline text that is put into the format, but may have any
  3357. TODO state, priority, tags, statistics cookies (at the beginning
  3358. or end of the headline title), or COMMENT keyword.")
  3359. (defvar-local org-todo-line-tags-regexp nil
  3360. "Matches a headline and puts TODO state into group 2 if present.
  3361. Also put tags into group 4 if tags are present.")
  3362. (defconst org-plain-time-of-day-regexp
  3363. (concat
  3364. "\\(\\<[012]?[0-9]"
  3365. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3366. "\\(--?"
  3367. "\\(\\<[012]?[0-9]"
  3368. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3369. "\\)?")
  3370. "Regular expression to match a plain time or time range.
  3371. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3372. groups carry important information:
  3373. 0 the full match
  3374. 1 the first time, range or not
  3375. 8 the second time, if it is a range.")
  3376. (defconst org-plain-time-extension-regexp
  3377. (concat
  3378. "\\(\\<[012]?[0-9]"
  3379. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3380. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3381. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3382. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3383. groups carry important information:
  3384. 0 the full match
  3385. 7 hours of duration
  3386. 9 minutes of duration")
  3387. (defconst org-stamp-time-of-day-regexp
  3388. (concat
  3389. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3390. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3391. "\\(--?"
  3392. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3393. "Regular expression to match a timestamp time or time range.
  3394. After a match, the following groups carry important information:
  3395. 0 the full match
  3396. 1 date plus weekday, for back referencing to make sure
  3397. both times are on the same day
  3398. 2 the first time, range or not
  3399. 4 the second time, if it is a range.")
  3400. (defconst org-startup-options
  3401. '(("fold" org-startup-folded t)
  3402. ("overview" org-startup-folded t)
  3403. ("nofold" org-startup-folded nil)
  3404. ("showall" org-startup-folded nil)
  3405. ("show2levels" org-startup-folded show2levels)
  3406. ("show3levels" org-startup-folded show3levels)
  3407. ("show4levels" org-startup-folded show4levels)
  3408. ("show5levels" org-startup-folded show5levels)
  3409. ("showeverything" org-startup-folded showeverything)
  3410. ("content" org-startup-folded content)
  3411. ("indent" org-startup-indented t)
  3412. ("noindent" org-startup-indented nil)
  3413. ("num" org-startup-numerated t)
  3414. ("nonum" org-startup-numerated nil)
  3415. ("hidestars" org-hide-leading-stars t)
  3416. ("showstars" org-hide-leading-stars nil)
  3417. ("odd" org-odd-levels-only t)
  3418. ("oddeven" org-odd-levels-only nil)
  3419. ("align" org-startup-align-all-tables t)
  3420. ("noalign" org-startup-align-all-tables nil)
  3421. ("shrink" org-startup-shrink-all-tables t)
  3422. ("inlineimages" org-startup-with-inline-images t)
  3423. ("noinlineimages" org-startup-with-inline-images nil)
  3424. ("latexpreview" org-startup-with-latex-preview t)
  3425. ("nolatexpreview" org-startup-with-latex-preview nil)
  3426. ("customtime" org-display-custom-times t)
  3427. ("logdone" org-log-done time)
  3428. ("lognotedone" org-log-done note)
  3429. ("nologdone" org-log-done nil)
  3430. ("lognoteclock-out" org-log-note-clock-out t)
  3431. ("nolognoteclock-out" org-log-note-clock-out nil)
  3432. ("logrepeat" org-log-repeat state)
  3433. ("lognoterepeat" org-log-repeat note)
  3434. ("logdrawer" org-log-into-drawer t)
  3435. ("nologdrawer" org-log-into-drawer nil)
  3436. ("logstatesreversed" org-log-states-order-reversed t)
  3437. ("nologstatesreversed" org-log-states-order-reversed nil)
  3438. ("nologrepeat" org-log-repeat nil)
  3439. ("logreschedule" org-log-reschedule time)
  3440. ("lognotereschedule" org-log-reschedule note)
  3441. ("nologreschedule" org-log-reschedule nil)
  3442. ("logredeadline" org-log-redeadline time)
  3443. ("lognoteredeadline" org-log-redeadline note)
  3444. ("nologredeadline" org-log-redeadline nil)
  3445. ("logrefile" org-log-refile time)
  3446. ("lognoterefile" org-log-refile note)
  3447. ("nologrefile" org-log-refile nil)
  3448. ("fninline" org-footnote-define-inline t)
  3449. ("nofninline" org-footnote-define-inline nil)
  3450. ("fnlocal" org-footnote-section nil)
  3451. ("fnauto" org-footnote-auto-label t)
  3452. ("fnprompt" org-footnote-auto-label nil)
  3453. ("fnconfirm" org-footnote-auto-label confirm)
  3454. ("fnplain" org-footnote-auto-label plain)
  3455. ("fnadjust" org-footnote-auto-adjust t)
  3456. ("nofnadjust" org-footnote-auto-adjust nil)
  3457. ("constcgs" constants-unit-system cgs)
  3458. ("constSI" constants-unit-system SI)
  3459. ("noptag" org-tag-persistent-alist nil)
  3460. ("hideblocks" org-hide-block-startup t)
  3461. ("nohideblocks" org-hide-block-startup nil)
  3462. ("hidedrawers" org-hide-drawer-startup t)
  3463. ("nohidedrawers" org-hide-drawer-startup nil)
  3464. ("beamer" org-startup-with-beamer-mode t)
  3465. ("entitiespretty" org-pretty-entities t)
  3466. ("entitiesplain" org-pretty-entities nil))
  3467. "Variable associated with STARTUP options for Org.
  3468. Each element is a list of three items: the startup options (as written
  3469. in the #+STARTUP line), the corresponding variable, and the value to set
  3470. this variable to if the option is found. An optional fourth element PUSH
  3471. means to push this value onto the list in the variable.")
  3472. (defcustom org-group-tags t
  3473. "When non-nil (the default), use group tags.
  3474. This can be turned on/off through `org-toggle-tags-groups'."
  3475. :group 'org-tags
  3476. :group 'org-startup
  3477. :type 'boolean)
  3478. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3479. (defun org-toggle-tags-groups ()
  3480. "Toggle support for group tags.
  3481. Support for group tags is controlled by the option
  3482. `org-group-tags', which is non-nil by default."
  3483. (interactive)
  3484. (setq org-group-tags (not org-group-tags))
  3485. (cond ((and (derived-mode-p 'org-agenda-mode)
  3486. org-group-tags)
  3487. (org-agenda-redo))
  3488. ((derived-mode-p 'org-mode)
  3489. (let ((org-inhibit-startup t)) (org-mode))))
  3490. (message "Groups tags support has been turned %s"
  3491. (if org-group-tags "on" "off")))
  3492. (defun org--tag-add-to-alist (alist1 alist2)
  3493. "Merge tags from ALIST1 into ALIST2.
  3494. Duplicates tags outside a group are removed. Keywords and order
  3495. are preserved.
  3496. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3497. See `org-tag-alist' for their structure."
  3498. (cond
  3499. ((null alist2) alist1)
  3500. ((null alist1) alist2)
  3501. (t
  3502. (let ((to-add nil)
  3503. (group-flag nil))
  3504. (dolist (tag-pair alist1)
  3505. (pcase tag-pair
  3506. (`(,(or :startgrouptag :startgroup))
  3507. (setq group-flag t)
  3508. (push tag-pair to-add))
  3509. (`(,(or :endgrouptag :endgroup))
  3510. (setq group-flag nil)
  3511. (push tag-pair to-add))
  3512. (`(,(or :grouptags :newline))
  3513. (push tag-pair to-add))
  3514. (`(,tag . ,_)
  3515. ;; Remove duplicates from ALIST1, unless they are in
  3516. ;; a group. Indeed, it makes sense to have a tag appear in
  3517. ;; multiple groups.
  3518. (when (or group-flag (not (assoc tag alist2)))
  3519. (push tag-pair to-add)))
  3520. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3521. ;; Preserve order of ALIST1.
  3522. (append (nreverse to-add) alist2)))))
  3523. (defun org-priority-to-value (s)
  3524. "Convert priority string S to its numeric value."
  3525. (or (save-match-data
  3526. (and (string-match "\\([0-9]+\\)" s)
  3527. (string-to-number (match-string 1 s))))
  3528. (string-to-char s)))
  3529. (defun org-set-regexps-and-options (&optional tags-only)
  3530. "Precompute regular expressions used in the current buffer.
  3531. When optional argument TAGS-ONLY is non-nil, only compute tags
  3532. related expressions."
  3533. (when (derived-mode-p 'org-mode)
  3534. (let ((alist (org-collect-keywords
  3535. (append '("FILETAGS" "TAGS")
  3536. (and (not tags-only)
  3537. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3538. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3539. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3540. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3541. ;; Startup options. Get this early since it does change
  3542. ;; behavior for other options (e.g., tags).
  3543. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3544. (cdr (assoc "STARTUP" alist)))))
  3545. (dolist (option startup)
  3546. (pcase (assoc-string option org-startup-options t)
  3547. (`(,_ ,variable ,value t)
  3548. (unless (listp (symbol-value variable))
  3549. (set (make-local-variable variable) nil))
  3550. (add-to-list variable value))
  3551. (`(,_ ,variable ,value . ,_)
  3552. (set (make-local-variable variable) value))
  3553. (_ nil))))
  3554. (setq-local org-file-tags
  3555. (mapcar #'org-add-prop-inherited
  3556. (cl-mapcan (lambda (value)
  3557. (cl-mapcan
  3558. (lambda (k) (org-split-string k ":"))
  3559. (split-string value)))
  3560. (cdr (assoc "FILETAGS" alist)))))
  3561. (setq org-current-tag-alist
  3562. (org--tag-add-to-alist
  3563. org-tag-persistent-alist
  3564. (let ((tags (cdr (assoc "TAGS" alist))))
  3565. (if tags
  3566. (org-tag-string-to-alist
  3567. (mapconcat #'identity tags "\n"))
  3568. org-tag-alist))))
  3569. (setq org-tag-groups-alist
  3570. (org-tag-alist-to-groups org-current-tag-alist))
  3571. (unless tags-only
  3572. ;; Properties.
  3573. (let ((properties nil))
  3574. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3575. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3576. (setq properties (org--update-property-plist
  3577. (match-string-no-properties 1 value)
  3578. (match-string-no-properties 2 value)
  3579. properties))))
  3580. (setq-local org-keyword-properties properties))
  3581. ;; Archive location.
  3582. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3583. (when archive (setq-local org-archive-location archive)))
  3584. ;; Category.
  3585. (let ((category (cdr (assoc "CATEGORY" alist))))
  3586. (when category
  3587. (setq-local org-category (intern category))
  3588. (setq-local org-keyword-properties
  3589. (org--update-property-plist
  3590. "CATEGORY" category org-keyword-properties))))
  3591. ;; Columns.
  3592. (let ((column (cdr (assoc "COLUMNS" alist))))
  3593. (when column (setq-local org-columns-default-format column)))
  3594. ;; Constants.
  3595. (let ((store nil))
  3596. (dolist (pair (cl-mapcan #'split-string
  3597. (cdr (assoc "CONSTANTS" alist))))
  3598. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3599. (let* ((name (match-string 1 pair))
  3600. (value (match-string 2 pair))
  3601. (old (assoc name store)))
  3602. (if old (setcdr old value)
  3603. (push (cons name value) store)))))
  3604. (setq org-table-formula-constants-local store))
  3605. ;; Link abbreviations.
  3606. (let ((links
  3607. (delq nil
  3608. (mapcar
  3609. (lambda (value)
  3610. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3611. (cons (match-string-no-properties 1 value)
  3612. (match-string-no-properties 2 value))))
  3613. (cdr (assoc "LINK" alist))))))
  3614. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3615. ;; Priorities.
  3616. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3617. (pcase (and value (split-string value))
  3618. (`(,high ,low ,default . ,_)
  3619. (setq-local org-priority-highest (org-priority-to-value high))
  3620. (setq-local org-priority-lowest (org-priority-to-value low))
  3621. (setq-local org-priority-default (org-priority-to-value default)))))
  3622. ;; Scripts.
  3623. (let ((value (cdr (assoc "OPTIONS" alist))))
  3624. (dolist (option value)
  3625. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3626. (setq-local org-use-sub-superscripts
  3627. (read (match-string 1 option))))))
  3628. ;; TODO keywords.
  3629. (setq-local org-todo-kwd-alist nil)
  3630. (setq-local org-todo-key-alist nil)
  3631. (setq-local org-todo-key-trigger nil)
  3632. (setq-local org-todo-keywords-1 nil)
  3633. (setq-local org-done-keywords nil)
  3634. (setq-local org-todo-heads nil)
  3635. (setq-local org-todo-sets nil)
  3636. (setq-local org-todo-log-states nil)
  3637. (let ((todo-sequences
  3638. (or (append (mapcar (lambda (value)
  3639. (cons 'type (split-string value)))
  3640. (cdr (assoc "TYP_TODO" alist)))
  3641. (mapcar (lambda (value)
  3642. (cons 'sequence (split-string value)))
  3643. (append (cdr (assoc "TODO" alist))
  3644. (cdr (assoc "SEQ_TODO" alist)))))
  3645. (let ((d (default-value 'org-todo-keywords)))
  3646. (if (not (stringp (car d))) d
  3647. ;; XXX: Backward compatibility code.
  3648. (list (cons org-todo-interpretation d)))))))
  3649. (dolist (sequence todo-sequences)
  3650. (let* ((sequence (or (run-hook-with-args-until-success
  3651. 'org-todo-setup-filter-hook sequence)
  3652. sequence))
  3653. (sequence-type (car sequence))
  3654. (keywords (cdr sequence))
  3655. (sep (member "|" keywords))
  3656. names alist)
  3657. (dolist (k (remove "|" keywords))
  3658. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3659. k)
  3660. (error "Invalid TODO keyword %s" k))
  3661. (let ((name (match-string 1 k))
  3662. (key (match-string 2 k))
  3663. (log (org-extract-log-state-settings k)))
  3664. (push name names)
  3665. (push (cons name (and key (string-to-char key))) alist)
  3666. (when log (push log org-todo-log-states))))
  3667. (let* ((names (nreverse names))
  3668. (done (if sep (org-remove-keyword-keys (cdr sep))
  3669. (last names)))
  3670. (head (car names))
  3671. (tail (list sequence-type head (car done) (org-last done))))
  3672. (add-to-list 'org-todo-heads head 'append)
  3673. (push names org-todo-sets)
  3674. (setq org-done-keywords (append org-done-keywords done nil))
  3675. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3676. (setq org-todo-key-alist
  3677. (append org-todo-key-alist
  3678. (and alist
  3679. (append '((:startgroup))
  3680. (nreverse alist)
  3681. '((:endgroup))))))
  3682. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3683. (setq org-todo-sets (nreverse org-todo-sets)
  3684. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3685. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3686. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3687. ;; Compute the regular expressions and other local variables.
  3688. ;; Using `org-outline-regexp-bol' would complicate them much,
  3689. ;; because of the fixed white space at the end of that string.
  3690. (unless org-done-keywords
  3691. (setq org-done-keywords
  3692. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3693. (setq org-not-done-keywords
  3694. (org-delete-all org-done-keywords
  3695. (copy-sequence org-todo-keywords-1))
  3696. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3697. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3698. org-not-done-heading-regexp
  3699. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3700. org-todo-line-regexp
  3701. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3702. org-complex-heading-regexp
  3703. (concat "^\\(\\*+\\)"
  3704. "\\(?: +" org-todo-regexp "\\)?"
  3705. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3706. "\\(?: +\\(.*?\\)\\)??"
  3707. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3708. "[ \t]*$")
  3709. org-complex-heading-regexp-format
  3710. (concat "^\\(\\*+\\)"
  3711. "\\(?: +" org-todo-regexp "\\)?"
  3712. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3713. "\\(?: +"
  3714. ;; Headline might be commented
  3715. "\\(?:" org-comment-string " +\\)?"
  3716. ;; Stats cookies can be stuck to body.
  3717. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3718. "\\(%s\\)"
  3719. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3720. "\\)"
  3721. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3722. "[ \t]*$")
  3723. org-todo-line-tags-regexp
  3724. (concat "^\\(\\*+\\)"
  3725. "\\(?: +" org-todo-regexp "\\)?"
  3726. "\\(?: +\\(.*?\\)\\)??"
  3727. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3728. "[ \t]*$"))
  3729. (org-compute-latex-and-related-regexp)))))
  3730. (defun org-collect-keywords (keywords &optional unique directory)
  3731. "Return values for KEYWORDS in current buffer, as an alist.
  3732. KEYWORDS is a list of strings. Return value is a list of
  3733. elements with the pattern:
  3734. (NAME . LIST-OF-VALUES)
  3735. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3736. is a list of non-empty values, as strings, in order of appearance
  3737. in the buffer.
  3738. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3739. value, empty or not, appearing in the buffer, as a string.
  3740. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3741. (VALUE . DIRECTORY)
  3742. where VALUE is the regular value, and DIRECTORY is the variable
  3743. `default-directory' for the buffer containing the keyword. This
  3744. is important for values containing relative file names, since the
  3745. function follows SETUPFILE keywords, and may change its working
  3746. directory."
  3747. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3748. (unique (mapcar #'upcase unique))
  3749. (alist (org--collect-keywords-1
  3750. keywords unique directory
  3751. (and buffer-file-name (list buffer-file-name))
  3752. nil)))
  3753. ;; Re-order results.
  3754. (dolist (entry alist)
  3755. (pcase entry
  3756. (`(,_ . ,(and value (pred consp)))
  3757. (setcdr entry (nreverse value)))))
  3758. (nreverse alist)))
  3759. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3760. (org-with-point-at 1
  3761. (let ((case-fold-search t)
  3762. (regexp (org-make-options-regexp keywords)))
  3763. (while (and keywords (re-search-forward regexp nil t))
  3764. (let ((element (org-element-at-point)))
  3765. (when (eq 'keyword (org-element-type element))
  3766. (let ((value (org-element-property :value element)))
  3767. (pcase (org-element-property :key element)
  3768. ("SETUPFILE"
  3769. (when (and (org-string-nw-p value)
  3770. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3771. (let* ((uri (org-strip-quotes value))
  3772. (uri-is-url (org-url-p uri))
  3773. (uri (if uri-is-url
  3774. uri
  3775. (expand-file-name uri))))
  3776. (unless (member uri files)
  3777. (with-temp-buffer
  3778. (unless uri-is-url
  3779. (setq default-directory (file-name-directory uri)))
  3780. (let ((contents (org-file-contents uri :noerror)))
  3781. (when contents
  3782. (insert contents)
  3783. ;; Fake Org mode: `org-element-at-point'
  3784. ;; doesn't need full set-up.
  3785. (let ((major-mode 'org-mode))
  3786. (setq alist
  3787. (org--collect-keywords-1
  3788. keywords unique directory
  3789. (cons uri files)
  3790. alist))))))))))
  3791. (keyword
  3792. (let ((entry (assoc keyword alist))
  3793. (final
  3794. (cond ((not (member keyword directory)) value)
  3795. (buffer-file-name
  3796. (cons value
  3797. (file-name-directory buffer-file-name)))
  3798. (t (cons value default-directory)))))
  3799. (cond ((member keyword unique)
  3800. (push (cons keyword final) alist)
  3801. (setq keywords (remove keyword keywords))
  3802. (setq regexp (org-make-options-regexp keywords)))
  3803. ((null entry) (push (list keyword final) alist))
  3804. (t (push final (cdr entry)))))))))))
  3805. alist)))
  3806. (defun org-tag-string-to-alist (s)
  3807. "Return tag alist associated to string S.
  3808. S is a value for TAGS keyword or produced with
  3809. `org-tag-alist-to-string'. Return value is an alist suitable for
  3810. `org-tag-alist' or `org-tag-persistent-alist'."
  3811. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3812. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3813. "\\(?:(\\(.\\))\\)?\\'"))
  3814. alist group-flag)
  3815. (dolist (tokens lines (cdr (nreverse alist)))
  3816. (push '(:newline) alist)
  3817. (while tokens
  3818. (let ((token (pop tokens)))
  3819. (pcase token
  3820. ("{"
  3821. (push '(:startgroup) alist)
  3822. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3823. ("}"
  3824. (push '(:endgroup) alist)
  3825. (setq group-flag nil))
  3826. ("["
  3827. (push '(:startgrouptag) alist)
  3828. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3829. ("]"
  3830. (push '(:endgrouptag) alist)
  3831. (setq group-flag nil))
  3832. (":"
  3833. (push '(:grouptags) alist))
  3834. ((guard (string-match tag-re token))
  3835. (let ((tag (match-string 1 token))
  3836. (key (and (match-beginning 2)
  3837. (string-to-char (match-string 2 token)))))
  3838. ;; Push all tags in groups, no matter if they already
  3839. ;; appear somewhere else in the list.
  3840. (when (or group-flag (not (assoc tag alist)))
  3841. (push (cons tag key) alist))))))))))
  3842. (defun org-tag-alist-to-string (alist &optional skip-key)
  3843. "Return tag string associated to ALIST.
  3844. ALIST is an alist, as defined in `org-tag-alist' or
  3845. `org-tag-persistent-alist', or produced with
  3846. `org-tag-string-to-alist'.
  3847. Return value is a string suitable as a value for \"TAGS\"
  3848. keyword.
  3849. When optional argument SKIP-KEY is non-nil, skip selection keys
  3850. next to tags."
  3851. (mapconcat (lambda (token)
  3852. (pcase token
  3853. (`(:startgroup) "{")
  3854. (`(:endgroup) "}")
  3855. (`(:startgrouptag) "[")
  3856. (`(:endgrouptag) "]")
  3857. (`(:grouptags) ":")
  3858. (`(:newline) "\\n")
  3859. ((and
  3860. (guard (not skip-key))
  3861. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3862. (format "%s(%c)" tag key))
  3863. (`(,(and tag (pred stringp)) . ,_) tag)
  3864. (_ (user-error "Invalid tag token: %S" token))))
  3865. alist
  3866. " "))
  3867. (defun org-tag-alist-to-groups (alist)
  3868. "Return group alist from tag ALIST.
  3869. ALIST is an alist, as defined in `org-tag-alist' or
  3870. `org-tag-persistent-alist', or produced with
  3871. `org-tag-string-to-alist'. Return value is an alist following
  3872. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3873. a string, summarizing TAGS, as a list of strings."
  3874. (let (groups group-status current-group)
  3875. (dolist (token alist (nreverse groups))
  3876. (pcase token
  3877. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3878. (`(,(or :endgroup :endgrouptag))
  3879. (when (eq group-status 'append)
  3880. (push (nreverse current-group) groups))
  3881. (setq group-status nil current-group nil))
  3882. (`(:grouptags) (setq group-status 'append))
  3883. ((and `(,tag . ,_) (guard group-status))
  3884. (if (eq group-status 'append) (push tag current-group)
  3885. (setq current-group (list tag))))
  3886. (_ nil)))))
  3887. (defvar org--file-cache (make-hash-table :test #'equal)
  3888. "Hash table to store contents of files referenced via a URL.
  3889. This is the cache of file URLs read using `org-file-contents'.")
  3890. (defun org-reset-file-cache ()
  3891. "Reset the cache of files downloaded by `org-file-contents'."
  3892. (clrhash org--file-cache))
  3893. (defun org-file-contents (file &optional noerror nocache)
  3894. "Return the contents of FILE, as a string.
  3895. FILE can be a file name or URL.
  3896. If FILE is a URL, download the contents. If the URL contents are
  3897. already cached in the `org--file-cache' hash table, the download step
  3898. is skipped.
  3899. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3900. from file or URL, and return nil.
  3901. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3902. is available. This option applies only if FILE is a URL."
  3903. (let* ((is-url (org-url-p file))
  3904. (cache (and is-url
  3905. (not nocache)
  3906. (gethash file org--file-cache))))
  3907. (cond
  3908. (cache)
  3909. (is-url
  3910. (if (org--should-fetch-remote-resource-p file)
  3911. (with-current-buffer (url-retrieve-synchronously file)
  3912. (goto-char (point-min))
  3913. ;; Move point to after the url-retrieve header.
  3914. (search-forward "\n\n" nil :move)
  3915. ;; Search for the success code only in the url-retrieve header.
  3916. (if (save-excursion
  3917. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3918. ;; Update the cache `org--file-cache' and return contents.
  3919. (puthash file
  3920. (buffer-substring-no-properties (point) (point-max))
  3921. org--file-cache)
  3922. (funcall (if noerror #'message #'user-error)
  3923. "Unable to fetch file from %S"
  3924. file)
  3925. nil))
  3926. (funcall (if noerror #'message #'user-error)
  3927. "The remote resource %S is considered unsafe, and will not be downloaded."
  3928. file)))
  3929. (t
  3930. (with-temp-buffer
  3931. (condition-case nil
  3932. (progn
  3933. (insert-file-contents file)
  3934. (buffer-string))
  3935. (file-error
  3936. (funcall (if noerror #'message #'user-error)
  3937. "Unable to read file %S"
  3938. file)
  3939. nil)))))))
  3940. (defun org--should-fetch-remote-resource-p (uri)
  3941. "Return non-nil if the URI should be fetched."
  3942. (or (eq org-resource-download-policy t)
  3943. (org--safe-remote-resource-p uri)
  3944. (and (eq org-resource-download-policy 'prompt)
  3945. (org--confirm-resource-safe uri))))
  3946. (defun org--safe-remote-resource-p (uri)
  3947. "Return non-nil if URI is considered safe.
  3948. This checks every pattern in `org-safe-remote-resources', and
  3949. returns non-nil if any of them match."
  3950. (let ((uri-patterns org-safe-remote-resources)
  3951. (file-uri (and buffer-file-name
  3952. (concat "file://" (file-truename buffer-file-name))))
  3953. match-p)
  3954. (while (and (not match-p) uri-patterns)
  3955. (setq match-p (or (string-match-p (car uri-patterns) uri)
  3956. (and file-uri (string-match-p (car uri-patterns) file-uri)))
  3957. uri-patterns (cdr uri-patterns)))
  3958. match-p))
  3959. (defun org--confirm-resource-safe (uri)
  3960. "Ask the user if URI should be considered safe, returning non-nil if so."
  3961. (unless noninteractive
  3962. (let ((current-file (and buffer-file-name (file-truename buffer-file-name)))
  3963. (domain (and (string-match
  3964. (rx (seq "http" (? "s") "://")
  3965. (optional (+ (not (any "@/\n"))) "@")
  3966. (optional "www.")
  3967. (one-or-more (not (any ":/?\n"))))
  3968. uri)
  3969. (match-string 0 uri)))
  3970. (buf (get-buffer-create "*Org Remote Resource*")))
  3971. ;; Set up the contents of the *Org Remote Resource* buffer.
  3972. (with-current-buffer buf
  3973. (erase-buffer)
  3974. (insert "An org-mode document would like to download "
  3975. (propertize uri 'face '(:inherit org-link :weight normal))
  3976. ", which is not considered safe.\n\n"
  3977. "Do you want to download this? You can type\n "
  3978. (propertize "!" 'face 'success)
  3979. " to download this resource, and permanantly mark it as safe.\n "
  3980. (if domain
  3981. (concat
  3982. (propertize "d" 'face 'success)
  3983. " to download this resource, and mark the domain ("
  3984. (propertize domain 'face '(:inherit org-link :weight normal))
  3985. ") as safe.\n ")
  3986. "")
  3987. (propertize "f" 'face 'success)
  3988. (if current-file
  3989. (concat
  3990. " to download this resource, and permanantly mark all resources in "
  3991. (propertize current-file 'face 'underline)
  3992. " as safe.\n ")
  3993. "")
  3994. (propertize "y" 'face 'warning)
  3995. " to download this resource, just this once.\n "
  3996. (propertize "n" 'face 'error)
  3997. " to skip this resource.\n")
  3998. (setq-local cursor-type nil)
  3999. (set-buffer-modified-p nil)
  4000. (goto-char (point-min)))
  4001. ;; Display the buffer and read a choice.
  4002. (save-window-excursion
  4003. (pop-to-buffer buf)
  4004. (let* ((exit-chars (append '(?y ?n ?! ?d ?\s) (and current-file '(?f))))
  4005. (prompt (format "Please type y, n%s, d, or !%s: "
  4006. (if current-file ", f" "")
  4007. (if (< (line-number-at-pos (point-max))
  4008. (window-body-height))
  4009. ""
  4010. ", or C-v/M-v to scroll")))
  4011. char)
  4012. (setq char (read-char-choice prompt exit-chars))
  4013. (when (memq char '(?! ?f ?d))
  4014. (customize-push-and-save
  4015. 'org-safe-remote-resources
  4016. (list (if (eq char ?d)
  4017. (concat "\\`" (regexp-quote domain) "\\(?:/\\|\\'\\)")
  4018. (concat "\\`"
  4019. (regexp-quote
  4020. (if (and (= char ?f) current-file)
  4021. (concat "file://" current-file) uri))
  4022. "\\'")))))
  4023. (prog1 (memq char '(?y ?n ?! ?d ?\s ?f))
  4024. (quit-window t)))))))
  4025. (defun org-extract-log-state-settings (x)
  4026. "Extract the log state setting from a TODO keyword string.
  4027. This will extract info from a string like \"WAIT(w@/!)\"."
  4028. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4029. (let ((kw (match-string 1 x))
  4030. (log1 (and (match-end 3) (match-string 3 x)))
  4031. (log2 (and (match-end 4) (match-string 4 x))))
  4032. (and (or log1 log2)
  4033. (list kw
  4034. (and log1 (if (equal log1 "!") 'time 'note))
  4035. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4036. (defun org-remove-keyword-keys (list)
  4037. "Remove a pair of parenthesis at the end of each string in LIST."
  4038. (mapcar (lambda (x)
  4039. (if (string-match "(.*)$" x)
  4040. (substring x 0 (match-beginning 0))
  4041. x))
  4042. list))
  4043. (defun org-assign-fast-keys (alist)
  4044. "Assign fast keys to a keyword-key alist.
  4045. Respect keys that are already there."
  4046. (let (new e (alt ?0))
  4047. (while (setq e (pop alist))
  4048. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4049. (cdr e)) ;; Key already assigned.
  4050. (push e new)
  4051. (let ((clist (string-to-list (downcase (car e))))
  4052. (used (append new alist)))
  4053. (when (= (car clist) ?@)
  4054. (pop clist))
  4055. (while (and clist (rassoc (car clist) used))
  4056. (pop clist))
  4057. (unless clist
  4058. (while (rassoc alt used)
  4059. (cl-incf alt)))
  4060. (push (cons (car e) (or (car clist) alt)) new))))
  4061. (nreverse new)))
  4062. ;;; Some variables used in various places
  4063. (defvar org-window-configuration nil
  4064. "Used in various places to store a window configuration.")
  4065. (defvar org-selected-window nil
  4066. "Used in various places to store a window configuration.")
  4067. (defvar org-finish-function nil
  4068. "Function to be called when `C-c C-c' is used.
  4069. This is for getting out of special buffers like capture.")
  4070. (defvar org-last-state)
  4071. ;; Defined somewhere in this file, but used before definition.
  4072. (defvar org-entities) ;; defined in org-entities.el
  4073. (defvar org-struct-menu)
  4074. (defvar org-org-menu)
  4075. (defvar org-tbl-menu)
  4076. ;;;; Define the Org mode
  4077. (defun org-before-change-function (_beg _end)
  4078. "Every change indicates that a table might need an update."
  4079. (setq org-table-may-need-update t))
  4080. (defvar org-mode-map)
  4081. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4082. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4083. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4084. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4085. (defvar bidi-paragraph-direction)
  4086. (defvar buffer-face-mode-face)
  4087. (require 'outline)
  4088. ;; Other stuff we need.
  4089. (require 'time-date)
  4090. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4091. (require 'easymenu))
  4092. (require 'org-entities)
  4093. (require 'org-faces)
  4094. (require 'org-list)
  4095. (require 'org-pcomplete)
  4096. (require 'org-src)
  4097. (require 'org-footnote)
  4098. (require 'org-macro)
  4099. ;; babel
  4100. (require 'ob)
  4101. (defvar org-element-cache-persistent); Defined in org-element.el
  4102. (defvar org-element-use-cache); Defined in org-element.el
  4103. (defvar org-mode-loading nil
  4104. "Non-nil during Org mode initialisation.")
  4105. ;;;###autoload
  4106. (define-derived-mode org-mode outline-mode "Org"
  4107. "Outline-based notes management and organizer, alias
  4108. \"Carsten's outline-mode for keeping track of everything.\"
  4109. Org mode develops organizational tasks around a NOTES file which
  4110. contains information about projects as plain text. Org mode is
  4111. implemented on top of Outline mode, which is ideal to keep the content
  4112. of large files well structured. It supports ToDo items, deadlines and
  4113. time stamps, which magically appear in the diary listing of the Emacs
  4114. calendar. Tables are easily created with a built-in table editor.
  4115. Plain text URL-like links connect to websites, emails (VM), Usenet
  4116. messages (Gnus), BBDB entries, and any files related to the project.
  4117. For printing and sharing of notes, an Org file (or a part of it)
  4118. can be exported as a structured ASCII or HTML file.
  4119. The following commands are available:
  4120. \\{org-mode-map}"
  4121. (setq-local org-mode-loading t)
  4122. (org-load-modules-maybe)
  4123. (when org-agenda-file-menu-enabled
  4124. (org-install-agenda-files-menu))
  4125. (when (and org-link-descriptive
  4126. (eq org-fold-core-style 'overlays))
  4127. (add-to-invisibility-spec '(org-link)))
  4128. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4129. "..."))
  4130. (make-local-variable 'org-link-descriptive)
  4131. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  4132. (if org-link-descriptive
  4133. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  4134. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  4135. (setq-local outline-regexp org-outline-regexp)
  4136. (setq-local outline-level 'org-outline-level)
  4137. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4138. (unless org-display-table
  4139. (setq org-display-table (make-display-table)))
  4140. (set-display-table-slot
  4141. org-display-table 4
  4142. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4143. org-ellipsis)))
  4144. (setq buffer-display-table org-display-table))
  4145. (org-set-regexps-and-options)
  4146. (org-set-font-lock-defaults)
  4147. (when (and org-tag-faces (not org-tags-special-faces-re))
  4148. ;; tag faces set outside customize.... force initialization.
  4149. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4150. ;; Calc embedded
  4151. (setq-local calc-embedded-open-mode "# ")
  4152. ;; Modify a few syntax entries
  4153. (modify-syntax-entry ?\" "\"")
  4154. (modify-syntax-entry ?\\ "_")
  4155. (modify-syntax-entry ?~ "_")
  4156. (modify-syntax-entry ?< "(>")
  4157. (modify-syntax-entry ?> ")<")
  4158. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4159. ;; Activate before-change-function
  4160. (setq-local org-table-may-need-update t)
  4161. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4162. ;; Check for running clock before killing a buffer
  4163. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4164. ;; Initialize cache.
  4165. (org-element-cache-reset)
  4166. (when (and org-element-cache-persistent
  4167. org-element-use-cache)
  4168. (org-persist-load 'org-element--cache (current-buffer) t))
  4169. ;; Initialize macros templates.
  4170. (org-macro-initialize-templates)
  4171. ;; Initialize radio targets.
  4172. (org-update-radio-target-regexp)
  4173. ;; Indentation.
  4174. (setq-local indent-line-function 'org-indent-line)
  4175. (setq-local indent-region-function 'org-indent-region)
  4176. ;; Filling and auto-filling.
  4177. (org-setup-filling)
  4178. ;; Comments.
  4179. (org-setup-comments-handling)
  4180. ;; Beginning/end of defun
  4181. (setq-local beginning-of-defun-function 'org-backward-element)
  4182. (setq-local end-of-defun-function
  4183. (lambda ()
  4184. (if (not (org-at-heading-p))
  4185. (org-forward-element)
  4186. (org-forward-element)
  4187. (forward-char -1))))
  4188. ;; Next error for sparse trees
  4189. (setq-local next-error-function 'org-occur-next-match)
  4190. ;; Make commit log messages from Org documents easier.
  4191. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4192. ;; Make sure dependence stuff works reliably, even for users who set it
  4193. ;; too late :-(
  4194. (if org-enforce-todo-dependencies
  4195. (add-hook 'org-blocker-hook
  4196. 'org-block-todo-from-children-or-siblings-or-parent)
  4197. (remove-hook 'org-blocker-hook
  4198. 'org-block-todo-from-children-or-siblings-or-parent))
  4199. (if org-enforce-todo-checkbox-dependencies
  4200. (add-hook 'org-blocker-hook
  4201. 'org-block-todo-from-checkboxes)
  4202. (remove-hook 'org-blocker-hook
  4203. 'org-block-todo-from-checkboxes))
  4204. ;; Align options lines
  4205. (setq-local
  4206. align-mode-rules-list
  4207. '((org-in-buffer-settings
  4208. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4209. (modes . '(org-mode)))))
  4210. ;; Setup the pcomplete hooks
  4211. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4212. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4213. (setq-local pcomplete-default-completion-function #'ignore)
  4214. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4215. (setq-local pcomplete-termination-string "")
  4216. (add-hook 'completion-at-point-functions
  4217. #'pcomplete-completions-at-point nil t)
  4218. (setq-local buffer-face-mode-face 'org-default)
  4219. ;; If empty file that did not turn on Org mode automatically, make
  4220. ;; it to.
  4221. (when (and org-insert-mode-line-in-empty-file
  4222. (called-interactively-p 'any)
  4223. (= (point-min) (point-max)))
  4224. (insert "# -*- mode: org -*-\n\n"))
  4225. (unless org-inhibit-startup
  4226. (org-unmodified
  4227. (when org-startup-with-beamer-mode (org-beamer-mode))
  4228. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4229. (org-table-map-tables
  4230. (cond ((and org-startup-align-all-tables
  4231. org-startup-shrink-all-tables)
  4232. (lambda () (org-table-align) (org-table-shrink)))
  4233. (org-startup-align-all-tables #'org-table-align)
  4234. (t #'org-table-shrink))
  4235. t))
  4236. (when org-startup-with-inline-images (org-display-inline-images))
  4237. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4238. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4239. (when org-startup-truncated (setq truncate-lines t))
  4240. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4241. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4242. ;; Add a custom keymap for `visual-line-mode' so that activating
  4243. ;; this minor mode does not override Org's keybindings.
  4244. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4245. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4246. (newmap (make-sparse-keymap)))
  4247. (set-keymap-parent newmap oldmap)
  4248. (define-key newmap [remap move-beginning-of-line] nil)
  4249. (define-key newmap [remap move-end-of-line] nil)
  4250. (define-key newmap [remap kill-line] nil)
  4251. (make-local-variable 'minor-mode-overriding-map-alist)
  4252. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4253. ;; Activate `org-table-header-line-mode'
  4254. (when org-table-header-line-p
  4255. (org-table-header-line-mode 1))
  4256. ;; Try to set `org-hide' face correctly.
  4257. (let ((foreground (org-find-invisible-foreground)))
  4258. (when foreground
  4259. (set-face-foreground 'org-hide foreground)))
  4260. ;; Set face extension as requested.
  4261. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4262. org-fontify-whole-block-delimiter-line)
  4263. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4264. (setq-local org-mode-loading nil))
  4265. ;; Update `customize-package-emacs-version-alist'
  4266. (add-to-list 'customize-package-emacs-version-alist
  4267. '(Org ("8.0" . "24.4")
  4268. ("8.1" . "24.4")
  4269. ("8.2" . "24.4")
  4270. ("8.2.7" . "24.4")
  4271. ("8.3" . "26.1")
  4272. ("9.0" . "26.1")
  4273. ("9.1" . "26.1")
  4274. ("9.2" . "27.1")
  4275. ("9.3" . "27.1")
  4276. ("9.4" . "27.2")
  4277. ("9.5" . "28.1")
  4278. ("9.6" . "29.1")))
  4279. (defvar org-mode-transpose-word-syntax-table
  4280. (let ((st (make-syntax-table text-mode-syntax-table)))
  4281. (dolist (c org-emphasis-alist st)
  4282. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4283. (when (fboundp 'abbrev-table-put)
  4284. (abbrev-table-put org-mode-abbrev-table
  4285. :parents (list text-mode-abbrev-table)))
  4286. (defun org-find-invisible-foreground ()
  4287. (let ((candidates (remove
  4288. "unspecified-bg"
  4289. (nconc
  4290. (list (face-background 'default)
  4291. (face-background 'org-default))
  4292. (mapcar
  4293. (lambda (alist)
  4294. (when (boundp alist)
  4295. (cdr (assq 'background-color (symbol-value alist)))))
  4296. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4297. (list (face-foreground 'org-hide))))))
  4298. (car (remove nil candidates))))
  4299. (defun org-current-time (&optional rounding-minutes past)
  4300. "Current time, possibly rounded to ROUNDING-MINUTES.
  4301. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4302. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4303. the rounding returns a past time."
  4304. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4305. (car org-time-stamp-rounding-minutes)))
  4306. (now (current-time)))
  4307. (if (< r 1)
  4308. now
  4309. (let* ((time (decode-time now))
  4310. (res (org-encode-time
  4311. (apply #'list
  4312. 0 (* r (round (nth 1 time) r))
  4313. (nthcdr 2 time)))))
  4314. (if (or (not past) (time-less-p res now))
  4315. res
  4316. (time-subtract res (* r 60)))))))
  4317. (defun org-today ()
  4318. "Return today date, considering `org-extend-today-until'."
  4319. (time-to-days
  4320. (time-since (* 3600 org-extend-today-until))))
  4321. ;;;; Font-Lock stuff, including the activators
  4322. (defconst org-match-sexp-depth 3
  4323. "Number of stacked braces for sub/superscript matching.")
  4324. (defun org-create-multibrace-regexp (left right n)
  4325. "Create a regular expression which will match a balanced sexp.
  4326. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4327. as single character strings.
  4328. The regexp returned will match the entire expression including the
  4329. delimiters. It will also define a single group which contains the
  4330. match except for the outermost delimiters. The maximum depth of
  4331. stacked delimiters is N. Escaping delimiters is not possible."
  4332. (let* ((nothing (concat "[^" left right "]*?"))
  4333. (or "\\|")
  4334. (re nothing)
  4335. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4336. (while (> n 1)
  4337. (setq n (1- n)
  4338. re (concat re or next)
  4339. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4340. (concat left "\\(" re "\\)" right)))
  4341. (defconst org-match-substring-regexp
  4342. (concat
  4343. "\\(\\S-\\)\\([_^]\\)\\("
  4344. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4345. "\\|"
  4346. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4347. "\\|"
  4348. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4349. "The regular expression matching a sub- or superscript.")
  4350. (defconst org-match-substring-with-braces-regexp
  4351. (concat
  4352. "\\(\\S-\\)\\([_^]\\)"
  4353. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4354. "The regular expression matching a sub- or superscript, forcing braces.")
  4355. (defvar org-emph-face nil)
  4356. (defun org-do-emphasis-faces (limit)
  4357. "Run through the buffer and emphasize strings."
  4358. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4359. (car org-emphasis-regexp-components))))
  4360. (catch :exit
  4361. (while (re-search-forward quick-re limit t)
  4362. (let* ((marker (match-string 2))
  4363. (verbatim? (member marker '("~" "="))))
  4364. (when (save-excursion
  4365. (goto-char (match-beginning 0))
  4366. (and
  4367. ;; Do not match table hlines.
  4368. (not (and (equal marker "+")
  4369. (org-match-line
  4370. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4371. ;; Do not match headline stars. Do not consider
  4372. ;; stars of a headline as closing marker for bold
  4373. ;; markup either.
  4374. (not (and (equal marker "*")
  4375. (save-excursion
  4376. (forward-char)
  4377. (skip-chars-backward "*")
  4378. (looking-at-p org-outline-regexp-bol))))
  4379. ;; Match full emphasis markup regexp.
  4380. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4381. ;; Do not span over paragraph boundaries.
  4382. (not (string-match-p org-element-paragraph-separate
  4383. (match-string 2)))
  4384. ;; Do not span over cells in table rows.
  4385. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4386. (string-match-p "|" (match-string 4))))))
  4387. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4388. (m (if org-hide-emphasis-markers 4 2)))
  4389. (font-lock-prepend-text-property
  4390. (match-beginning m) (match-end m) 'face face)
  4391. (when verbatim?
  4392. (org-remove-flyspell-overlays-in
  4393. (match-beginning 0) (match-end 0))
  4394. (when (and (org-fold-core-folding-spec-p 'org-link)
  4395. (org-fold-core-folding-spec-p 'org-link-description))
  4396. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
  4397. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
  4398. (remove-text-properties (match-beginning 2) (match-end 2)
  4399. '(display t invisible t intangible t)))
  4400. (add-text-properties (match-beginning 2) (match-end 2)
  4401. '(font-lock-multiline t org-emphasis t))
  4402. (when (and org-hide-emphasis-markers
  4403. (not (org-at-comment-p)))
  4404. (add-text-properties (match-end 4) (match-beginning 5)
  4405. '(invisible t))
  4406. (add-text-properties (match-beginning 3) (match-end 3)
  4407. '(invisible t)))
  4408. (throw :exit t))))))))
  4409. (defun org-emphasize (&optional char)
  4410. "Insert or change an emphasis, i.e. a font like bold or italic.
  4411. If there is an active region, change that region to a new emphasis.
  4412. If there is no region, just insert the marker characters and position
  4413. the cursor between them.
  4414. CHAR should be the marker character. If it is a space, it means to
  4415. remove the emphasis of the selected region.
  4416. If CHAR is not given (for example in an interactive call) it will be
  4417. prompted for."
  4418. (interactive)
  4419. (let ((erc org-emphasis-regexp-components)
  4420. (string "") beg end move s)
  4421. (if (org-region-active-p)
  4422. (setq beg (region-beginning)
  4423. end (region-end)
  4424. string (buffer-substring beg end))
  4425. (setq move t))
  4426. (unless char
  4427. (message "Emphasis marker or tag: [%s]"
  4428. (mapconcat #'car org-emphasis-alist ""))
  4429. (setq char (read-char-exclusive)))
  4430. (if (equal char ?\s)
  4431. (setq s ""
  4432. move nil)
  4433. (unless (assoc (char-to-string char) org-emphasis-alist)
  4434. (user-error "No such emphasis marker: \"%c\"" char))
  4435. (setq s (char-to-string char)))
  4436. (while (and (> (length string) 1)
  4437. (equal (substring string 0 1) (substring string -1))
  4438. (assoc (substring string 0 1) org-emphasis-alist))
  4439. (setq string (substring string 1 -1)))
  4440. (setq string (concat s string s))
  4441. (when beg (delete-region beg end))
  4442. (unless (or (bolp)
  4443. (string-match (concat "[" (nth 0 erc) "\n]")
  4444. (char-to-string (char-before (point)))))
  4445. (insert " "))
  4446. (unless (or (eobp)
  4447. (string-match (concat "[" (nth 1 erc) "\n]")
  4448. (char-to-string (char-after (point)))))
  4449. (insert " ") (backward-char 1))
  4450. (insert string)
  4451. (and move (backward-char 1))))
  4452. (defconst org-nonsticky-props
  4453. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4454. (defsubst org-rear-nonsticky-at (pos)
  4455. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4456. (defun org-activate-links--overlays (limit)
  4457. "Add link properties to links.
  4458. This includes angle, plain, and bracket links."
  4459. (catch :exit
  4460. (while (re-search-forward org-link-any-re limit t)
  4461. (let* ((start (match-beginning 0))
  4462. (end (match-end 0))
  4463. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4464. (visible-end (or (match-end 3) (match-end 2)))
  4465. (style (cond ((eq ?< (char-after start)) 'angle)
  4466. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4467. (t 'plain))))
  4468. (when (and (memq style org-highlight-links)
  4469. ;; Do not span over paragraph boundaries.
  4470. (not (string-match-p org-element-paragraph-separate
  4471. (match-string 0)))
  4472. ;; Do not confuse plain links with tags.
  4473. (not (and (eq style 'plain)
  4474. (let ((face (get-text-property
  4475. (max (1- start) (point-min)) 'face)))
  4476. (if (consp face) (memq 'org-tag face)
  4477. (eq 'org-tag face))))))
  4478. (let* ((link-object (save-excursion
  4479. (goto-char start)
  4480. (save-match-data (org-element-link-parser))))
  4481. (link (org-element-property :raw-link link-object))
  4482. (type (org-element-property :type link-object))
  4483. (path (org-element-property :path link-object))
  4484. (face-property (pcase (org-link-get-parameter type :face)
  4485. ((and (pred functionp) face) (funcall face path))
  4486. ((and (pred facep) face) face)
  4487. ((and (pred consp) face) face) ;anonymous
  4488. (_ 'org-link)))
  4489. (properties ;for link's visible part
  4490. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4491. 'highlight)
  4492. 'keymap (or (org-link-get-parameter type :keymap)
  4493. org-mouse-map)
  4494. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4495. ((and (pred stringp) echo) echo)
  4496. ((and (pred functionp) echo) echo)
  4497. (_ (concat "LINK: " link)))
  4498. 'htmlize-link (pcase (org-link-get-parameter type
  4499. :htmlize-link)
  4500. ((and (pred functionp) f) (funcall f))
  4501. (_ `(:uri ,link)))
  4502. 'font-lock-multiline t)))
  4503. (org-remove-flyspell-overlays-in start end)
  4504. (org-rear-nonsticky-at end)
  4505. (if (not (eq 'bracket style))
  4506. (progn
  4507. (add-face-text-property start end face-property)
  4508. (add-text-properties start end properties))
  4509. ;; Handle invisible parts in bracket links.
  4510. (remove-text-properties start end '(invisible nil))
  4511. (let ((hidden
  4512. (append `(invisible
  4513. ,(or (org-link-get-parameter type :display)
  4514. 'org-link))
  4515. properties)))
  4516. (add-text-properties start visible-start hidden)
  4517. (add-face-text-property start end face-property)
  4518. (add-text-properties visible-start visible-end properties)
  4519. (add-text-properties visible-end end hidden)
  4520. (org-rear-nonsticky-at visible-start)
  4521. (org-rear-nonsticky-at visible-end)))
  4522. (let ((f (org-link-get-parameter type :activate-func)))
  4523. (when (functionp f)
  4524. (funcall f start end path (eq style 'bracket))))
  4525. (throw :exit t))))) ;signal success
  4526. nil))
  4527. (defun org-activate-links--text-properties (limit)
  4528. "Add link properties to links.
  4529. This includes angle, plain, and bracket links."
  4530. (catch :exit
  4531. (while (re-search-forward org-link-any-re limit t)
  4532. (let* ((start (match-beginning 0))
  4533. (end (match-end 0))
  4534. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4535. (visible-end (or (match-end 3) (match-end 2)))
  4536. (style (cond ((eq ?< (char-after start)) 'angle)
  4537. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4538. (t 'plain))))
  4539. (when (and (memq style org-highlight-links)
  4540. ;; Do not span over paragraph boundaries.
  4541. (not (string-match-p org-element-paragraph-separate
  4542. (match-string 0)))
  4543. ;; Do not confuse plain links with tags.
  4544. (not (and (eq style 'plain)
  4545. (let ((face (get-text-property
  4546. (max (1- start) (point-min)) 'face)))
  4547. (if (consp face) (memq 'org-tag face)
  4548. (eq 'org-tag face))))))
  4549. (let* ((link-object (save-excursion
  4550. (goto-char start)
  4551. (save-match-data (org-element-link-parser))))
  4552. (link (org-element-property :raw-link link-object))
  4553. (type (org-element-property :type link-object))
  4554. (path (org-element-property :path link-object))
  4555. (face-property (pcase (org-link-get-parameter type :face)
  4556. ((and (pred functionp) face) (funcall face path))
  4557. ((and (pred facep) face) face)
  4558. ((and (pred consp) face) face) ;anonymous
  4559. (_ 'org-link)))
  4560. (properties ;for link's visible part
  4561. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4562. 'highlight)
  4563. 'keymap (or (org-link-get-parameter type :keymap)
  4564. org-mouse-map)
  4565. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4566. ((and (pred stringp) echo) echo)
  4567. ((and (pred functionp) echo) echo)
  4568. (_ (concat "LINK: " link)))
  4569. 'htmlize-link (pcase (org-link-get-parameter type
  4570. :htmlize-link)
  4571. ((and (pred functionp) f) (funcall f))
  4572. (_ `(:uri ,link)))
  4573. 'font-lock-multiline t)))
  4574. (org-remove-flyspell-overlays-in start end)
  4575. (org-rear-nonsticky-at end)
  4576. (if (not (eq 'bracket style))
  4577. (progn
  4578. (add-face-text-property start end face-property)
  4579. (add-text-properties start end properties))
  4580. ;; Initialise folding when used outside org-mode.
  4581. (unless (or (derived-mode-p 'org-mode)
  4582. (and (org-fold-folding-spec-p 'org-link-description)
  4583. (org-fold-folding-spec-p 'org-link)))
  4584. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4585. "...")))
  4586. ;; Handle invisible parts in bracket links.
  4587. (let ((spec (or (org-link-get-parameter type :display)
  4588. 'org-link)))
  4589. (unless (org-fold-folding-spec-p spec)
  4590. (org-fold-add-folding-spec spec
  4591. (cdr org-link--link-folding-spec)
  4592. nil
  4593. 'append)
  4594. (org-fold-core-set-folding-spec-property spec :visible t))
  4595. (org-fold-region start end nil 'org-link)
  4596. (org-fold-region start end nil 'org-link-description)
  4597. ;; We are folding the whole emphasised text with SPEC
  4598. ;; first. It makes everything invisible (or whatever
  4599. ;; the user wants).
  4600. (org-fold-region start end t spec)
  4601. ;; The visible part of the text is folded using
  4602. ;; 'org-link-description, which is forcing this part of
  4603. ;; the text to be visible.
  4604. (org-fold-region visible-start visible-end t 'org-link-description)
  4605. (add-text-properties start end properties)
  4606. (add-face-text-property start end face-property)
  4607. (org-rear-nonsticky-at visible-start)
  4608. (org-rear-nonsticky-at visible-end)))
  4609. (let ((f (org-link-get-parameter type :activate-func)))
  4610. (when (functionp f)
  4611. (funcall f start end path (eq style 'bracket))))
  4612. (throw :exit t))))) ;signal success
  4613. nil))
  4614. (defsubst org-activate-links (limit)
  4615. "Add link properties to links.
  4616. This includes angle, plain, and bracket links."
  4617. (if (eq org-fold-core-style 'text-properties)
  4618. (org-activate-links--text-properties limit)
  4619. (org-activate-links--overlays limit)))
  4620. (defun org-activate-code (limit)
  4621. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4622. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4623. (remove-text-properties (match-beginning 0) (match-end 0)
  4624. '(display t invisible t intangible t))
  4625. t))
  4626. (defcustom org-src-fontify-natively t
  4627. "When non-nil, fontify code in code blocks.
  4628. See also the `org-block' face."
  4629. :type 'boolean
  4630. :version "26.1"
  4631. :package-version '(Org . "8.3")
  4632. :group 'org-appearance
  4633. :group 'org-babel)
  4634. (defcustom org-allow-promoting-top-level-subtree nil
  4635. "When non-nil, allow promoting a top level subtree.
  4636. The leading star of the top level headline will be replaced
  4637. by a #."
  4638. :type 'boolean
  4639. :version "24.1"
  4640. :group 'org-appearance)
  4641. (defun org-fontify-meta-lines-and-blocks (limit)
  4642. (condition-case nil
  4643. (org-fontify-meta-lines-and-blocks-1 limit)
  4644. (error (message "Org mode fontification error in %S at %d"
  4645. (current-buffer)
  4646. (line-number-at-pos)))))
  4647. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4648. "Fontify #+ lines and blocks."
  4649. (let ((case-fold-search t))
  4650. (when (re-search-forward
  4651. (rx bol (group (zero-or-more (any " \t")) "#"
  4652. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4653. (any " \t")
  4654. eol))
  4655. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4656. (zero-or-more (any " \t"))
  4657. (group (group (zero-or-more (not (any " \t\n"))))
  4658. (zero-or-more (any " \t"))
  4659. (group (zero-or-more any)))))
  4660. limit t)
  4661. (let ((beg (match-beginning 0))
  4662. (end-of-beginline (match-end 0))
  4663. ;; Including \n at end of #+begin line will include \n
  4664. ;; after the end of block content.
  4665. (block-start (match-end 0))
  4666. (block-end nil)
  4667. (lang (match-string 7)) ; The language, if it is a source block.
  4668. (bol-after-beginline (line-beginning-position 2))
  4669. (dc1 (downcase (match-string 2)))
  4670. (dc3 (downcase (match-string 3)))
  4671. (whole-blockline org-fontify-whole-block-delimiter-line)
  4672. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4673. (cond
  4674. ((and (match-end 4) (equal dc3 "+begin"))
  4675. ;; Truly a block
  4676. (setq block-type (downcase (match-string 5))
  4677. ;; Src, example, export, maybe more.
  4678. quoting (member block-type org-protecting-blocks))
  4679. (when (re-search-forward
  4680. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4681. (seq (zero-or-more (any " \t"))
  4682. "#+end"
  4683. ,(match-string 4)
  4684. word-end
  4685. (zero-or-more any)))))
  4686. ;; We look further than LIMIT on purpose.
  4687. nil t)
  4688. ;; We do have a matching #+end line.
  4689. (setq beg-of-endline (match-beginning 0)
  4690. end-of-endline (match-end 0)
  4691. nl-before-endline (1- (match-beginning 0)))
  4692. (setq block-end (match-beginning 0)) ; Include the final newline.
  4693. (when quoting
  4694. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4695. (remove-text-properties beg end-of-endline
  4696. '(display t invisible t intangible t)))
  4697. (add-text-properties
  4698. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4699. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4700. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4701. (cond
  4702. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4703. (save-match-data
  4704. (org-src-font-lock-fontify-block lang block-start block-end))
  4705. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4706. (quoting
  4707. (add-text-properties
  4708. bol-after-beginline beg-of-endline
  4709. (list 'face
  4710. (list :inherit
  4711. (let ((face-name
  4712. (intern (format "org-block-%s" lang))))
  4713. (append (and (facep face-name) (list face-name))
  4714. '(org-block)))))))
  4715. ((not org-fontify-quote-and-verse-blocks))
  4716. ((string= block-type "quote")
  4717. (add-face-text-property
  4718. bol-after-beginline beg-of-endline 'org-quote t))
  4719. ((string= block-type "verse")
  4720. (add-face-text-property
  4721. bol-after-beginline beg-of-endline 'org-verse t)))
  4722. ;; Fontify the #+begin and #+end lines of the blocks
  4723. (add-text-properties
  4724. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4725. '(face org-block-begin-line))
  4726. (unless (eq (char-after beg-of-endline) ?*)
  4727. (add-text-properties
  4728. beg-of-endline
  4729. (if whole-blockline
  4730. (let ((beg-of-next-line (1+ end-of-endline)))
  4731. (min (point-max) beg-of-next-line))
  4732. (min (point-max) end-of-endline))
  4733. '(face org-block-end-line)))
  4734. t))
  4735. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4736. (org-remove-flyspell-overlays-in
  4737. (match-beginning 0)
  4738. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4739. (add-text-properties
  4740. beg (match-end 3)
  4741. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4742. '(font-lock-fontified t invisible t)
  4743. '(font-lock-fontified t face org-document-info-keyword)))
  4744. (add-text-properties
  4745. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4746. (if (string-equal dc1 "+title:")
  4747. '(font-lock-fontified t face org-document-title)
  4748. '(font-lock-fontified t face org-document-info))))
  4749. ((string-prefix-p "+caption" dc1)
  4750. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4751. (remove-text-properties (match-beginning 0) (match-end 0)
  4752. '(display t invisible t intangible t))
  4753. ;; Handle short captions
  4754. (save-excursion
  4755. (beginning-of-line)
  4756. (looking-at (rx (group (zero-or-more (any " \t"))
  4757. "#+caption"
  4758. (optional "[" (zero-or-more any) "]")
  4759. ":")
  4760. (zero-or-more (any " \t")))))
  4761. (add-text-properties (line-beginning-position) (match-end 1)
  4762. '(font-lock-fontified t face org-meta-line))
  4763. (add-text-properties (match-end 0) (line-end-position)
  4764. '(font-lock-fontified t face org-block))
  4765. t)
  4766. ((member dc3 '(" " ""))
  4767. ;; Just a comment, the plus was not there
  4768. (org-remove-flyspell-overlays-in beg (match-end 0))
  4769. (add-text-properties
  4770. beg (match-end 0)
  4771. '(font-lock-fontified t face font-lock-comment-face)))
  4772. (t ;; Just any other in-buffer setting, but not indented
  4773. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4774. (remove-text-properties (match-beginning 0) (match-end 0)
  4775. '(display t invisible t intangible t))
  4776. (add-text-properties beg (match-end 0)
  4777. '(font-lock-fontified t face org-meta-line))
  4778. t))))))
  4779. (defun org-fontify-drawers (limit)
  4780. "Fontify drawers."
  4781. (when (re-search-forward org-drawer-regexp limit t)
  4782. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4783. '(font-lock-fontified t face org-drawer))
  4784. (org-remove-flyspell-overlays-in
  4785. (line-beginning-position) (line-beginning-position 2))
  4786. t))
  4787. (defun org-fontify-macros (limit)
  4788. "Fontify macros."
  4789. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4790. (let ((begin (match-beginning 0))
  4791. (opening-end (match-beginning 1)))
  4792. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4793. (match-string 1))
  4794. (let ((end (match-end 1))
  4795. (closing-start (match-beginning 1)))
  4796. (add-text-properties
  4797. begin end
  4798. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4799. (org-remove-flyspell-overlays-in begin end)
  4800. (when org-hide-macro-markers
  4801. (add-text-properties begin opening-end '(invisible t))
  4802. (add-text-properties closing-start end '(invisible t)))
  4803. t)))))
  4804. (defun org-fontify-extend-region (beg end _old-len)
  4805. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4806. (1+ end) end))
  4807. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4808. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4809. (extend
  4810. (lambda (r1 r2 dir)
  4811. (let ((re (replace-regexp-in-string
  4812. "\\(begin\\|end\\)" r1
  4813. (replace-regexp-in-string
  4814. "[][]" r2
  4815. (match-string-no-properties 0)))))
  4816. (re-search-forward (regexp-quote re) nil t dir)))))
  4817. (goto-char beg)
  4818. (back-to-indentation)
  4819. (save-match-data
  4820. (cond ((looking-at end-re)
  4821. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4822. ((looking-at begin-re)
  4823. (cons beg (or (funcall extend "end" "]" 1) end)))
  4824. (t (cons beg end))))))
  4825. (defun org-activate-footnote-links (limit)
  4826. "Add text properties for footnotes."
  4827. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4828. (when fn
  4829. (let* ((beg (nth 1 fn))
  4830. (end (nth 2 fn))
  4831. (label (car fn))
  4832. (referencep (/= (line-beginning-position) beg)))
  4833. (when (and referencep (nth 3 fn))
  4834. (save-excursion
  4835. (goto-char beg)
  4836. (search-forward (or label "fn:"))
  4837. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4838. (add-text-properties beg end
  4839. (list 'mouse-face 'highlight
  4840. 'keymap org-mouse-map
  4841. 'help-echo
  4842. (if referencep "Footnote reference"
  4843. "Footnote definition")
  4844. 'font-lock-fontified t
  4845. 'font-lock-multiline t
  4846. 'face 'org-footnote))))))
  4847. (defun org-activate-dates (limit)
  4848. "Add text properties for dates."
  4849. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4850. (not (equal (char-before (match-beginning 0)) 91)))
  4851. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4852. (add-text-properties (match-beginning 0) (match-end 0)
  4853. (list 'mouse-face 'highlight
  4854. 'keymap org-mouse-map))
  4855. (org-rear-nonsticky-at (match-end 0))
  4856. (when org-display-custom-times
  4857. ;; If it's a date range, activate custom time for second date.
  4858. (when (match-end 3)
  4859. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4860. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4861. t))
  4862. (defun org-activate-target-links (limit)
  4863. "Add text properties for target matches."
  4864. (when org-target-link-regexp
  4865. (let ((case-fold-search t))
  4866. ;; `org-target-link-regexp' matches one character before the
  4867. ;; actual target.
  4868. (unless (bolp) (forward-char -1))
  4869. (when (re-search-forward org-target-link-regexp limit t)
  4870. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4871. (add-text-properties (match-beginning 1) (match-end 1)
  4872. (list 'mouse-face 'highlight
  4873. 'keymap org-mouse-map
  4874. 'help-echo "Radio target link"
  4875. 'org-linked-text t))
  4876. (org-rear-nonsticky-at (match-end 1))
  4877. t))))
  4878. (defvar org-latex-and-related-regexp nil
  4879. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4880. (defun org-compute-latex-and-related-regexp ()
  4881. "Compute regular expression for LaTeX, entities and sub/superscript.
  4882. Result depends on variable `org-highlight-latex-and-related'."
  4883. (let ((re-sub
  4884. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4885. ((eq org-use-sub-superscripts '{})
  4886. (list org-match-substring-with-braces-regexp))
  4887. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4888. (re-latex
  4889. (when (or (memq 'latex org-highlight-latex-and-related)
  4890. (memq 'native org-highlight-latex-and-related))
  4891. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4892. (delq nil
  4893. (mapcar (lambda (x)
  4894. (and (member (car x) matchers) (nth 1 x)))
  4895. org-latex-regexps)))))
  4896. (re-entities
  4897. (when (memq 'entities org-highlight-latex-and-related)
  4898. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4899. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4900. (setq-local org-latex-and-related-regexp
  4901. (mapconcat #'identity
  4902. (append re-latex re-entities re-sub)
  4903. "\\|"))))
  4904. (defun org-do-latex-and-related (limit)
  4905. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4906. Stop at first highlighted object, if any. Return t if some
  4907. highlighting was done, nil otherwise."
  4908. (when (org-string-nw-p org-latex-and-related-regexp)
  4909. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4910. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4911. (catch 'found
  4912. (while (and (< (point) limit)
  4913. (re-search-forward org-latex-and-related-regexp nil t))
  4914. (cond
  4915. ((>= (match-beginning 0) limit)
  4916. (throw 'found nil))
  4917. ((cl-some (lambda (f)
  4918. (memq f '(org-code org-verbatim underline
  4919. org-special-keyword)))
  4920. (save-excursion
  4921. (goto-char (1+ (match-beginning 0)))
  4922. (face-at-point nil t))))
  4923. ;; Try to limit false positives. In this case, ignore
  4924. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4925. ;; contain an empty line.
  4926. ((save-excursion
  4927. (goto-char (match-beginning 0))
  4928. (and (looking-at-p latex-prefix-re)
  4929. (save-match-data
  4930. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4931. (t
  4932. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4933. '(?_ ?^))
  4934. 1
  4935. 0))
  4936. (start (+ offset (match-beginning 0)))
  4937. (end (match-end 0)))
  4938. (if (memq 'native org-highlight-latex-and-related)
  4939. (org-src-font-lock-fontify-block "latex" start end)
  4940. (font-lock-prepend-text-property start end
  4941. 'face 'org-latex-and-related))
  4942. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4943. '(font-lock-multiline t))
  4944. (throw 'found t)))))
  4945. nil))))
  4946. (defun org-restart-font-lock ()
  4947. "Restart `font-lock-mode', to force refontification."
  4948. (when font-lock-mode
  4949. (font-lock-mode -1)
  4950. (font-lock-mode 1)))
  4951. (defun org-activate-tags (limit)
  4952. (when (re-search-forward org-tag-line-re limit t)
  4953. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4954. (add-text-properties (match-beginning 1) (match-end 1)
  4955. (list 'mouse-face 'highlight
  4956. 'keymap org-mouse-map))
  4957. (org-rear-nonsticky-at (match-end 1))
  4958. t))
  4959. (defun org-outline-level ()
  4960. "Compute the outline level of the heading at point.
  4961. If this is called at a normal headline, the level is the number
  4962. of stars. Use `org-reduced-level' to remove the effect of
  4963. `org-odd-levels'. Unlike to `org-current-level', this function
  4964. takes into consideration inlinetasks."
  4965. (org-with-wide-buffer
  4966. (end-of-line)
  4967. (if (re-search-backward org-outline-regexp-bol nil t)
  4968. (1- (- (match-end 0) (match-beginning 0)))
  4969. 0)))
  4970. (defvar org-font-lock-keywords nil)
  4971. (defsubst org-re-property (property &optional literal allow-null value)
  4972. "Return a regexp matching a PROPERTY line.
  4973. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4974. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4975. non-nil, match properties even without a value.
  4976. Match group 3 is set to the value when it exists. If there is no
  4977. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4978. With optional argument VALUE, match only property lines with
  4979. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4980. unless LITERAL is non-nil."
  4981. (concat
  4982. "^\\(?4:[ \t]*\\)"
  4983. (format "\\(?1::\\(?2:%s\\):\\)"
  4984. (if literal property (regexp-quote property)))
  4985. (cond (value
  4986. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4987. (if literal value (regexp-quote value))))
  4988. (allow-null
  4989. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4990. (t
  4991. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4992. (defconst org-property-re
  4993. (org-re-property "\\S-+" 'literal t)
  4994. "Regular expression matching a property line.
  4995. There are four matching groups:
  4996. 1: :PROPKEY: including the leading and trailing colon,
  4997. 2: PROPKEY without the leading and trailing colon,
  4998. 3: PROPVAL without leading or trailing spaces,
  4999. 4: the indentation of the current line,
  5000. 5: trailing whitespace.")
  5001. (defvar org-font-lock-hook nil
  5002. "Functions to be called for special font lock stuff.")
  5003. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5004. (defvar org-font-lock-set-keywords-hook nil
  5005. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5006. This is called after `org-font-lock-extra-keywords' is defined, but before
  5007. it is installed to be used by font lock. This can be useful if something
  5008. needs to be inserted at a specific position in the font-lock sequence.")
  5009. (defun org-font-lock-hook (limit)
  5010. "Run `org-font-lock-hook' within LIMIT."
  5011. (run-hook-with-args 'org-font-lock-hook limit))
  5012. (defun org-set-font-lock-defaults ()
  5013. "Set font lock defaults for the current buffer."
  5014. (let ((org-font-lock-extra-keywords
  5015. (list
  5016. ;; Call the hook
  5017. '(org-font-lock-hook)
  5018. ;; Headlines
  5019. `(,(if org-fontify-whole-heading-line
  5020. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5021. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5022. (1 (org-get-level-face 1))
  5023. (2 (org-get-level-face 2))
  5024. (3 (org-get-level-face 3)))
  5025. ;; Table lines
  5026. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5027. (1 'org-table t))
  5028. ;; Table internals
  5029. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5030. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5031. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5032. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5033. ;; Properties
  5034. (list org-property-re
  5035. '(1 'org-special-keyword t)
  5036. '(3 'org-property-value t))
  5037. ;; Drawers
  5038. '(org-fontify-drawers)
  5039. ;; Link related fontification.
  5040. '(org-activate-links)
  5041. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  5042. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  5043. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  5044. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5045. ;; Targets.
  5046. (list org-radio-target-regexp '(0 'org-target t))
  5047. (list org-target-regexp '(0 'org-target t))
  5048. ;; Diary sexps.
  5049. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5050. ;; Macro
  5051. '(org-fontify-macros)
  5052. ;; TODO keyword
  5053. (list (format org-heading-keyword-regexp-format
  5054. org-todo-regexp)
  5055. '(2 (org-get-todo-face 2) prepend))
  5056. ;; TODO
  5057. (when org-fontify-todo-headline
  5058. (list (format org-heading-keyword-regexp-format
  5059. (concat
  5060. "\\(?:"
  5061. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5062. "\\)"))
  5063. '(2 'org-headline-todo prepend)))
  5064. ;; DONE
  5065. (when org-fontify-done-headline
  5066. (list (format org-heading-keyword-regexp-format
  5067. (concat
  5068. "\\(?:"
  5069. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5070. "\\)"))
  5071. '(2 'org-headline-done prepend)))
  5072. ;; Priorities
  5073. '(org-font-lock-add-priority-faces)
  5074. ;; Tags
  5075. '(org-font-lock-add-tag-faces)
  5076. ;; Tags groups
  5077. (when (and org-group-tags org-tag-groups-alist)
  5078. (list (concat org-outline-regexp-bol ".+\\(:"
  5079. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5080. ":\\).*$")
  5081. '(1 'org-tag-group prepend)))
  5082. ;; Special keywords
  5083. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5084. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5085. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5086. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5087. ;; Emphasis
  5088. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5089. ;; Checkboxes
  5090. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5091. 1 'org-checkbox prepend)
  5092. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5093. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5094. (0 (org-get-checkbox-statistics-face) prepend)))
  5095. ;; Description list items
  5096. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5097. 1 'org-list-dt prepend)
  5098. ;; Inline export snippets
  5099. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5100. (1 'font-lock-comment-face t)
  5101. (2 'org-tag t)
  5102. (3 'font-lock-comment-face t))
  5103. ;; ARCHIVEd headings
  5104. (list (concat
  5105. org-outline-regexp-bol
  5106. "\\(.*:" org-archive-tag ":.*\\)")
  5107. '(1 'org-archived prepend))
  5108. ;; Specials
  5109. '(org-do-latex-and-related)
  5110. '(org-fontify-entities)
  5111. '(org-raise-scripts)
  5112. ;; Code
  5113. '(org-activate-code (1 'org-code t))
  5114. ;; COMMENT
  5115. (list (format
  5116. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5117. org-todo-regexp
  5118. org-comment-string)
  5119. '(9 'org-special-keyword t))
  5120. ;; Blocks and meta lines
  5121. '(org-fontify-meta-lines-and-blocks)
  5122. '(org-fontify-inline-src-blocks)
  5123. ;; Citations. When an activate processor is specified, if
  5124. ;; specified, try loading it beforehand.
  5125. (progn
  5126. (unless (null org-cite-activate-processor)
  5127. (org-cite-try-load-processor org-cite-activate-processor))
  5128. '(org-cite-activate)))))
  5129. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5130. (run-hooks 'org-font-lock-set-keywords-hook)
  5131. ;; Now set the full font-lock-keywords
  5132. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5133. (setq-local font-lock-defaults
  5134. '(org-font-lock-keywords t nil nil backward-paragraph))
  5135. (setq-local font-lock-extend-after-change-region-function
  5136. #'org-fontify-extend-region)
  5137. (kill-local-variable 'font-lock-keywords)
  5138. nil))
  5139. (defun org-toggle-pretty-entities ()
  5140. "Toggle the composition display of entities as UTF8 characters."
  5141. (interactive)
  5142. (setq-local org-pretty-entities (not org-pretty-entities))
  5143. (org-restart-font-lock)
  5144. (if org-pretty-entities
  5145. (message "Entities are now displayed as UTF8 characters")
  5146. (save-restriction
  5147. (widen)
  5148. (decompose-region (point-min) (point-max))
  5149. (message "Entities are now displayed as plain text"))))
  5150. (defvar-local org-custom-properties-overlays nil
  5151. "List of overlays used for custom properties.")
  5152. (defun org-toggle-custom-properties-visibility ()
  5153. "Display or hide properties in `org-custom-properties'."
  5154. (interactive)
  5155. (if org-custom-properties-overlays
  5156. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5157. (setq org-custom-properties-overlays nil))
  5158. (when org-custom-properties
  5159. (org-with-wide-buffer
  5160. (goto-char (point-min))
  5161. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5162. (while (re-search-forward regexp nil t)
  5163. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5164. (when (and end (< (point) end))
  5165. ;; Hide first custom property in current drawer.
  5166. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5167. (overlay-put o 'invisible t)
  5168. (overlay-put o 'org-custom-property t)
  5169. (push o org-custom-properties-overlays))
  5170. ;; Hide additional custom properties in the same drawer.
  5171. (while (re-search-forward regexp end t)
  5172. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5173. (overlay-put o 'invisible t)
  5174. (overlay-put o 'org-custom-property t)
  5175. (push o org-custom-properties-overlays)))))
  5176. ;; Each entry is limited to a single property drawer.
  5177. (outline-next-heading)))))))
  5178. (defun org-fontify-entities (limit)
  5179. "Find an entity to fontify."
  5180. (let (ee)
  5181. (when org-pretty-entities
  5182. (catch 'match
  5183. ;; "\_ "-family is left out on purpose. Only the first one,
  5184. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5185. ;; confusing when adding a second white space character.
  5186. (while (re-search-forward
  5187. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5188. limit t)
  5189. (when (and (not (org-at-comment-p))
  5190. (setq ee (org-entity-get (match-string 1)))
  5191. (= (length (nth 6 ee)) 1))
  5192. (let* ((end (if (equal (match-string 2) "{}")
  5193. (match-end 2)
  5194. (match-end 1))))
  5195. (add-text-properties
  5196. (match-beginning 0) end
  5197. (list 'font-lock-fontified t))
  5198. (compose-region (match-beginning 0) end
  5199. (nth 6 ee) nil)
  5200. (backward-char 1)
  5201. (throw 'match t))))
  5202. nil))))
  5203. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5204. "Fontify string S like in Org mode."
  5205. (with-temp-buffer
  5206. (insert s)
  5207. (let ((org-odd-levels-only odd-levels))
  5208. (org-mode)
  5209. (font-lock-ensure)
  5210. (if org-link-descriptive
  5211. (org-link-display-format
  5212. (buffer-string))
  5213. (buffer-string)))))
  5214. (defun org-get-level-face (n)
  5215. "Get the right face for match N in font-lock matching of headlines."
  5216. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5217. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5218. (org-f (if org-cycle-level-faces
  5219. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5220. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5221. (cond
  5222. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5223. ((eq n 2) org-f)
  5224. (t (unless org-level-color-stars-only org-f)))))
  5225. (defun org-face-from-face-or-color (context inherit face-or-color)
  5226. "Create a face list that inherits INHERIT, but sets the foreground color.
  5227. When FACE-OR-COLOR is not a string, just return it."
  5228. (if (stringp face-or-color)
  5229. (list :inherit inherit
  5230. (cdr (assoc context org-faces-easy-properties))
  5231. face-or-color)
  5232. face-or-color))
  5233. (defun org-get-todo-face (kwd)
  5234. "Get the right face for a TODO keyword KWD.
  5235. If KWD is a number, get the corresponding match group."
  5236. (when (numberp kwd) (setq kwd (match-string kwd)))
  5237. (or (org-face-from-face-or-color
  5238. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5239. (and (member kwd org-done-keywords) 'org-done)
  5240. 'org-todo))
  5241. (defun org-get-priority-face (priority)
  5242. "Get the right face for PRIORITY.
  5243. PRIORITY is a character."
  5244. (or (org-face-from-face-or-color
  5245. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5246. 'org-priority))
  5247. (defun org-get-tag-face (tag)
  5248. "Get the right face for TAG.
  5249. If TAG is a number, get the corresponding match group."
  5250. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5251. (or (org-face-from-face-or-color
  5252. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5253. 'org-tag)))
  5254. (defvar org-priority-regexp) ; defined later in the file
  5255. (defun org-font-lock-add-priority-faces (limit)
  5256. "Add the special priority faces."
  5257. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5258. (let ((beg (match-beginning 1))
  5259. (end (1+ (match-end 2))))
  5260. (add-face-text-property
  5261. beg end
  5262. (org-get-priority-face (string-to-char (match-string 2))))
  5263. (add-text-properties
  5264. beg end
  5265. (list 'font-lock-fontified t)))))
  5266. (defun org-font-lock-add-tag-faces (limit)
  5267. "Add the special tag faces."
  5268. (when (and org-tag-faces org-tags-special-faces-re)
  5269. (while (re-search-forward org-tags-special-faces-re limit t)
  5270. (add-face-text-property
  5271. (match-beginning 1)
  5272. (match-end 1)
  5273. (org-get-tag-face 1))
  5274. (add-text-properties (match-beginning 1) (match-end 1)
  5275. (list 'font-lock-fontified t))
  5276. (backward-char 1))))
  5277. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5278. "Remove fontification and activation overlays from links."
  5279. (font-lock-default-unfontify-region beg end)
  5280. (let* ((buffer-undo-list t)
  5281. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5282. (inhibit-modification-hooks t)
  5283. deactivate-mark buffer-file-name buffer-file-truename)
  5284. (decompose-region beg end)
  5285. (remove-text-properties beg end
  5286. '(mouse-face t keymap t org-linked-text t
  5287. invisible t intangible t
  5288. org-emphasis t))
  5289. (org-fold-region beg end nil 'org-link)
  5290. (org-fold-region beg end nil 'org-link-description)
  5291. (org-fold-core-update-optimisation beg end)
  5292. (org-remove-font-lock-display-properties beg end)))
  5293. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5294. ((raise 0.3) (height 0.7))
  5295. ((raise -0.5))
  5296. ((raise 0.5)))
  5297. "Display properties for showing superscripts and subscripts.")
  5298. (defun org-remove-font-lock-display-properties (beg end)
  5299. "Remove specific display properties that have been added by font lock.
  5300. The will remove the raise properties that are used to show superscripts
  5301. and subscripts."
  5302. (let (next prop)
  5303. (while (< beg end)
  5304. (setq next (next-single-property-change beg 'display nil end)
  5305. prop (get-text-property beg 'display))
  5306. (when (member prop org-script-display)
  5307. (put-text-property beg next 'display nil))
  5308. (setq beg next))))
  5309. (defun org-raise-scripts (limit)
  5310. "Add raise properties to sub/superscripts."
  5311. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5312. (re-search-forward
  5313. (if (eq org-use-sub-superscripts t)
  5314. org-match-substring-regexp
  5315. org-match-substring-with-braces-regexp)
  5316. limit t))
  5317. (let* ((pos (point)) table-p comment-p
  5318. (mpos (match-beginning 3))
  5319. (emph-p (get-text-property mpos 'org-emphasis))
  5320. (link-p (get-text-property mpos 'mouse-face))
  5321. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5322. (goto-char (line-beginning-position))
  5323. (setq table-p (looking-at-p org-table-dataline-regexp)
  5324. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5325. (goto-char pos)
  5326. ;; Handle a_b^c
  5327. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5328. (unless (or comment-p emph-p link-p keyw-p)
  5329. (put-text-property (match-beginning 3) (match-end 0)
  5330. 'display
  5331. (if (equal (char-after (match-beginning 2)) ?^)
  5332. (nth (if table-p 3 1) org-script-display)
  5333. (nth (if table-p 2 0) org-script-display)))
  5334. (put-text-property (match-beginning 2) (match-end 3)
  5335. 'org-emphasis t)
  5336. (add-text-properties (match-beginning 2) (match-end 2)
  5337. (list 'invisible t))
  5338. (when (and (eq (char-after (match-beginning 3)) ?{)
  5339. (eq (char-before (match-end 3)) ?}))
  5340. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5341. (list 'invisible t))
  5342. (add-text-properties (1- (match-end 3)) (match-end 3)
  5343. (list 'invisible t))))
  5344. t)))
  5345. (defun org-remove-empty-overlays-at (pos)
  5346. "Remove outline overlays that do not contain non-white stuff."
  5347. (dolist (o (overlays-at pos))
  5348. (and (eq 'outline (overlay-get o 'invisible))
  5349. (not (string-match-p
  5350. "\\S-" (buffer-substring (overlay-start o)
  5351. (overlay-end o))))
  5352. (delete-overlay o))))
  5353. ;; FIXME: This function is unused.
  5354. (defun org-show-empty-lines-in-parent ()
  5355. "Move to the parent and re-show empty lines before visible headlines."
  5356. (save-excursion
  5357. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5358. (org-cycle-show-empty-lines context))))
  5359. (defun org-files-list ()
  5360. "Return `org-agenda-files' list, plus all open Org files.
  5361. This is useful for operations that need to scan all of a user's
  5362. open and agenda-wise Org files."
  5363. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5364. (dolist (buf (buffer-list))
  5365. (with-current-buffer buf
  5366. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5367. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5368. :test #'equal))))
  5369. files))
  5370. (defsubst org-entry-beginning-position ()
  5371. "Return the beginning position of the current entry."
  5372. (save-excursion (org-back-to-heading t) (point)))
  5373. (defsubst org-entry-end-position ()
  5374. "Return the end position of the current entry."
  5375. (save-excursion (outline-next-heading) (point)))
  5376. (defun org-subtree-end-visible-p ()
  5377. "Is the end of the current subtree visible?"
  5378. (pos-visible-in-window-p
  5379. (save-excursion (org-end-of-subtree t) (point))))
  5380. (defun org-first-headline-recenter ()
  5381. "Move cursor to the first headline and recenter the headline."
  5382. (let ((window (get-buffer-window)))
  5383. (when window
  5384. (goto-char (point-min))
  5385. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5386. (set-window-start window (line-beginning-position))))))
  5387. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5388. (defvar org-called-with-limited-levels nil
  5389. "Non-nil when `org-with-limited-levels' is currently active.")
  5390. ;;; Indirect buffer display of subtrees
  5391. (defvar org-indirect-dedicated-frame nil
  5392. "This is the frame being used for indirect tree display.")
  5393. (defvar org-last-indirect-buffer nil)
  5394. (defun org-tree-to-indirect-buffer (&optional arg)
  5395. "Create indirect buffer and narrow it to current subtree.
  5396. With a numerical prefix ARG, go up to this level and then take that tree.
  5397. If ARG is negative, go up that many levels.
  5398. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5399. indirect buffer previously made with this command, to avoid proliferation of
  5400. indirect buffers. However, when you call the command with a \
  5401. `\\[universal-argument]' prefix, or
  5402. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5403. so that you can work with several indirect buffers at the same time. If
  5404. `org-indirect-buffer-display' is `dedicated-frame', the \
  5405. `\\[universal-argument]' prefix also
  5406. requests that a new frame be made for the new buffer, so that the dedicated
  5407. frame is not changed."
  5408. (interactive "P")
  5409. (let ((cbuf (current-buffer))
  5410. (cwin (selected-window))
  5411. (pos (point))
  5412. beg end level heading ibuf)
  5413. (save-excursion
  5414. (org-back-to-heading t)
  5415. (when (numberp arg)
  5416. (setq level (org-outline-level))
  5417. (when (< arg 0) (setq arg (+ level arg)))
  5418. (while (> (setq level (org-outline-level)) arg)
  5419. (org-up-heading-safe)))
  5420. (setq beg (point)
  5421. heading (org-get-heading 'no-tags))
  5422. (org-end-of-subtree t t)
  5423. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5424. (setq end (point)))
  5425. (when (and (buffer-live-p org-last-indirect-buffer)
  5426. (not (eq org-indirect-buffer-display 'new-frame))
  5427. (not arg))
  5428. (kill-buffer org-last-indirect-buffer))
  5429. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5430. org-last-indirect-buffer ibuf)
  5431. (cond
  5432. ((or (eq org-indirect-buffer-display 'new-frame)
  5433. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5434. (select-frame (make-frame))
  5435. (delete-other-windows)
  5436. (pop-to-buffer-same-window ibuf)
  5437. (org-set-frame-title heading))
  5438. ((eq org-indirect-buffer-display 'dedicated-frame)
  5439. (raise-frame
  5440. (select-frame (or (and org-indirect-dedicated-frame
  5441. (frame-live-p org-indirect-dedicated-frame)
  5442. org-indirect-dedicated-frame)
  5443. (setq org-indirect-dedicated-frame (make-frame)))))
  5444. (delete-other-windows)
  5445. (pop-to-buffer-same-window ibuf)
  5446. (org-set-frame-title (concat "Indirect: " heading)))
  5447. ((eq org-indirect-buffer-display 'current-window)
  5448. (pop-to-buffer-same-window ibuf))
  5449. ((eq org-indirect-buffer-display 'other-window)
  5450. (pop-to-buffer ibuf))
  5451. (t (error "Invalid value")))
  5452. (narrow-to-region beg end)
  5453. (org-fold-show-all '(headings drawers blocks))
  5454. (goto-char pos)
  5455. (run-hook-with-args 'org-cycle-hook 'all)
  5456. (and (window-live-p cwin) (select-window cwin))))
  5457. (defun org-get-indirect-buffer (&optional buffer heading)
  5458. (setq buffer (or buffer (current-buffer)))
  5459. (let ((n 1) (base (buffer-name buffer)) bname)
  5460. (while (buffer-live-p
  5461. (get-buffer
  5462. (setq bname
  5463. (concat base "-"
  5464. (if heading (concat heading "-" (number-to-string n))
  5465. (number-to-string n))))))
  5466. (setq n (1+ n)))
  5467. (condition-case nil
  5468. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5469. ;; Decouple folding state. We need to do it manually since
  5470. ;; `make-indirect-buffer' does not run
  5471. ;; `clone-indirect-buffer-hook'.
  5472. (org-fold-core-decouple-indirect-buffer-folds)
  5473. ;; Return the buffer.
  5474. indirect-buffer)
  5475. (error (make-indirect-buffer buffer bname)))))
  5476. (defun org-set-frame-title (title)
  5477. "Set the title of the current frame to the string TITLE."
  5478. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5479. ;;;; Structure editing
  5480. ;;; Inserting headlines
  5481. (defun org--blank-before-heading-p (&optional parent)
  5482. "Non-nil when an empty line should precede a new heading here.
  5483. When optional argument PARENT is non-nil, consider parent
  5484. headline instead of current one."
  5485. (pcase (assq 'heading org-blank-before-new-entry)
  5486. (`(heading . auto)
  5487. (save-excursion
  5488. (org-with-limited-levels
  5489. (unless (and (org-before-first-heading-p)
  5490. (not (outline-next-heading)))
  5491. (org-back-to-heading t)
  5492. (when parent (org-up-heading-safe))
  5493. (cond ((not (bobp))
  5494. (org-previous-line-empty-p))
  5495. ((outline-next-heading)
  5496. (org-previous-line-empty-p))
  5497. ;; Ignore trailing spaces on last buffer line.
  5498. ((progn (skip-chars-backward " \t") (bolp))
  5499. (org-previous-line-empty-p))
  5500. (t nil))))))
  5501. (`(heading . ,value) value)
  5502. (_ nil)))
  5503. (defun org-insert-heading (&optional arg invisible-ok top)
  5504. "Insert a new heading or an item with the same depth at point.
  5505. If point is at the beginning of a heading, insert a new heading
  5506. or a new headline above the current one. When at the beginning
  5507. of a regular line of text, turn it into a heading.
  5508. If point is in the middle of a line, split it and create a new
  5509. headline with the text in the current line after point (see
  5510. `org-M-RET-may-split-line' on how to modify this behavior). As
  5511. a special case, on a headline, splitting can only happen on the
  5512. title itself. E.g., this excludes breaking stars or tags.
  5513. With a `\\[universal-argument]' prefix, set \
  5514. `org-insert-heading-respect-content' to
  5515. a non-nil value for the duration of the command. This forces the
  5516. insertion of a heading after the current subtree, independently
  5517. on the location of point.
  5518. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5519. insert the heading at the end of the tree
  5520. above the current heading. For example, if point is within a
  5521. 2nd-level heading, then it will insert a 2nd-level heading at
  5522. the end of the 1st-level parent subtree.
  5523. When INVISIBLE-OK is set, stop at invisible headlines when going
  5524. back. This is important for non-interactive uses of the
  5525. command.
  5526. When optional argument TOP is non-nil, insert a level 1 heading,
  5527. unconditionally."
  5528. (interactive "P")
  5529. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5530. (level (org-current-level))
  5531. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5532. (cond
  5533. ((or org-insert-heading-respect-content
  5534. (member arg '((4) (16)))
  5535. (and (not invisible-ok)
  5536. (invisible-p (max (1- (point)) (point-min)))))
  5537. ;; Position point at the location of insertion. Make sure we
  5538. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5539. (org-with-limited-levels
  5540. (if (not level) (outline-next-heading) ;before first headline
  5541. (org-back-to-heading invisible-ok)
  5542. (when (equal arg '(16)) (org-up-heading-safe))
  5543. (org-end-of-subtree)))
  5544. (unless (bolp) (insert "\n"))
  5545. (when (and blank? (save-excursion
  5546. (backward-char)
  5547. (org-before-first-heading-p)))
  5548. (insert "\n")
  5549. (backward-char))
  5550. (when (and (not level) (not (eobp)) (not (bobp)))
  5551. (when (org-at-heading-p) (insert "\n"))
  5552. (backward-char))
  5553. (unless (and blank? (org-previous-line-empty-p))
  5554. (org-N-empty-lines-before-current (if blank? 1 0)))
  5555. (insert stars " ")
  5556. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5557. ;; is visible.
  5558. (unless invisible-ok
  5559. (if (eq org-fold-core-style 'text-properties)
  5560. (cond
  5561. ((org-fold-folded-p
  5562. (max (point-min)
  5563. (1- (line-beginning-position)))
  5564. 'headline)
  5565. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5566. (t nil))
  5567. (pcase (get-char-property-and-overlay (point) 'invisible)
  5568. (`(outline . ,o)
  5569. (move-overlay o (overlay-start o) (line-end-position 0)))
  5570. (_ nil)))))
  5571. ;; At a headline...
  5572. ((org-at-heading-p)
  5573. (cond ((bolp)
  5574. (when blank? (save-excursion (insert "\n")))
  5575. (save-excursion (insert stars " \n"))
  5576. (unless (and blank? (org-previous-line-empty-p))
  5577. (org-N-empty-lines-before-current (if blank? 1 0)))
  5578. (end-of-line))
  5579. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5580. (org-match-line org-complex-heading-regexp)
  5581. (org-pos-in-match-range (point) 4))
  5582. ;; Grab the text that should moved to the new headline.
  5583. ;; Preserve tags.
  5584. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5585. (if (looking-at "[ \t]*$") (replace-match "")
  5586. (org-align-tags))
  5587. (end-of-line)
  5588. (when blank? (insert "\n"))
  5589. (insert "\n" stars " ")
  5590. (when (org-string-nw-p split) (insert split))))
  5591. (t
  5592. (end-of-line)
  5593. (when blank? (insert "\n"))
  5594. (insert "\n" stars " "))))
  5595. ;; On regular text, turn line into a headline or split, if
  5596. ;; appropriate.
  5597. ((bolp)
  5598. (insert stars " ")
  5599. (unless (and blank? (org-previous-line-empty-p))
  5600. (org-N-empty-lines-before-current (if blank? 1 0))))
  5601. (t
  5602. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5603. (end-of-line))
  5604. (insert "\n" stars " ")
  5605. (unless (and blank? (org-previous-line-empty-p))
  5606. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5607. (run-hooks 'org-insert-heading-hook))
  5608. (defun org-N-empty-lines-before-current (n)
  5609. "Make the number of empty lines before current exactly N.
  5610. So this will delete or add empty lines."
  5611. (let ((column (current-column)))
  5612. (beginning-of-line)
  5613. (unless (bobp)
  5614. (let ((start (save-excursion
  5615. (skip-chars-backward " \r\t\n")
  5616. (line-end-position))))
  5617. (delete-region start (line-end-position 0))))
  5618. (insert (make-string n ?\n))
  5619. (move-to-column column)))
  5620. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5621. "Return the heading of the current entry, without the stars.
  5622. When NO-TAGS is non-nil, don't include tags.
  5623. When NO-TODO is non-nil, don't include TODO keywords.
  5624. When NO-PRIORITY is non-nil, don't include priority cookie.
  5625. When NO-COMMENT is non-nil, don't include COMMENT string.
  5626. Return nil before first heading."
  5627. (unless (org-before-first-heading-p)
  5628. (save-excursion
  5629. (org-back-to-heading t)
  5630. (let ((case-fold-search nil))
  5631. (looking-at org-complex-heading-regexp)
  5632. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5633. ;; returned text will be invisible. Clear it up.
  5634. (save-match-data
  5635. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
  5636. (let ((todo (and (not no-todo) (match-string 2)))
  5637. (priority (and (not no-priority) (match-string 3)))
  5638. (headline (pcase (match-string 4)
  5639. (`nil "")
  5640. ((and (guard no-comment) h)
  5641. (replace-regexp-in-string
  5642. (eval-when-compile
  5643. (format "\\`%s[ \t]+" org-comment-string))
  5644. "" h))
  5645. (h h)))
  5646. (tags (and (not no-tags) (match-string 5))))
  5647. ;; Restore cleared optimisation.
  5648. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5649. (mapconcat #'identity
  5650. (delq nil (list todo priority headline tags))
  5651. " "))))))
  5652. (defun org-heading-components ()
  5653. "Return the components of the current heading.
  5654. This is a list with the following elements:
  5655. - the level as an integer
  5656. - the reduced level, different if `org-odd-levels-only' is set.
  5657. - the TODO keyword, or nil
  5658. - the priority character, like ?A, or nil if no priority is given
  5659. - the headline text itself, or the tags string if no headline text
  5660. - the tags string, or nil."
  5661. (save-excursion
  5662. (org-back-to-heading t)
  5663. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5664. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5665. (prog1
  5666. (list (length (match-string 1))
  5667. (org-reduced-level (length (match-string 1)))
  5668. (match-string-no-properties 2)
  5669. (and (match-end 3) (aref (match-string 3) 2))
  5670. (match-string-no-properties 4)
  5671. (match-string-no-properties 5))
  5672. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5673. (defun org-get-entry ()
  5674. "Get the entry text, after heading, entire subtree."
  5675. (save-excursion
  5676. (org-back-to-heading t)
  5677. (filter-buffer-substring (line-beginning-position 2) (org-end-of-subtree t))))
  5678. (defun org-edit-headline (&optional heading)
  5679. "Edit the current headline.
  5680. Set it to HEADING when provided."
  5681. (interactive)
  5682. (org-with-wide-buffer
  5683. (org-back-to-heading t)
  5684. (let ((case-fold-search nil))
  5685. (when (looking-at org-complex-heading-regexp)
  5686. (let* ((old (match-string-no-properties 4))
  5687. (new (save-match-data
  5688. (org-trim (or heading (read-string "Edit: " old))))))
  5689. (unless (equal old new)
  5690. (if old (replace-match new t t nil 4)
  5691. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5692. (insert " " new))
  5693. (org-align-tags)
  5694. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5695. (defun org-insert-heading-after-current ()
  5696. "Insert a new heading with same level as current, after current subtree."
  5697. (interactive)
  5698. (org-back-to-heading)
  5699. (org-insert-heading)
  5700. (org-move-subtree-down)
  5701. (end-of-line 1))
  5702. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5703. "Insert heading with `org-insert-heading-respect-content' set to t."
  5704. (interactive)
  5705. (org-insert-heading '(4) invisible-ok))
  5706. (defun org-insert-todo-heading-respect-content (&optional _)
  5707. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5708. (interactive)
  5709. (let ((org-insert-heading-respect-content t))
  5710. (org-insert-todo-heading '(4) t)))
  5711. (defun org-insert-todo-heading (arg &optional force-heading)
  5712. "Insert a new heading with the same level and TODO state as current heading.
  5713. If the heading has no TODO state, or if the state is DONE, use
  5714. the first state (TODO by default). Also with one prefix arg,
  5715. force first state. With two prefix args, force inserting at the
  5716. end of the parent subtree.
  5717. When called at a plain list item, insert a new item with an
  5718. unchecked check box."
  5719. (interactive "P")
  5720. (when (or force-heading (not (org-insert-item 'checkbox)))
  5721. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5722. force-heading))
  5723. (save-excursion
  5724. (org-forward-heading-same-level -1)
  5725. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5726. (let* ((new-mark-x
  5727. (if (or (equal arg '(4))
  5728. (not (match-beginning 2))
  5729. (member (match-string 2) org-done-keywords))
  5730. (car org-todo-keywords-1)
  5731. (match-string 2)))
  5732. (new-mark
  5733. (or
  5734. (run-hook-with-args-until-success
  5735. 'org-todo-get-default-hook new-mark-x nil)
  5736. new-mark-x)))
  5737. (beginning-of-line 1)
  5738. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5739. (if org-treat-insert-todo-heading-as-state-change
  5740. (org-todo new-mark)
  5741. (insert new-mark " "))))
  5742. (when org-provide-todo-statistics
  5743. (org-update-parent-todo-statistics))))
  5744. (defun org-insert-subheading (arg)
  5745. "Insert a new subheading and demote it.
  5746. Works for outline headings and for plain lists alike."
  5747. (interactive "P")
  5748. (org-insert-heading arg)
  5749. (cond
  5750. ((org-at-heading-p) (org-do-demote))
  5751. ((org-at-item-p) (org-indent-item))))
  5752. (defun org-insert-todo-subheading (arg)
  5753. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5754. Works for outline headings and for plain lists alike."
  5755. (interactive "P")
  5756. (org-insert-todo-heading arg)
  5757. (cond
  5758. ((org-at-heading-p) (org-do-demote))
  5759. ((org-at-item-p) (org-indent-item))))
  5760. ;;; Promotion and Demotion
  5761. (defvar org-after-demote-entry-hook nil
  5762. "Hook run after an entry has been demoted.
  5763. The cursor will be at the beginning of the entry.
  5764. When a subtree is being demoted, the hook will be called for each node.")
  5765. (defvar org-after-promote-entry-hook nil
  5766. "Hook run after an entry has been promoted.
  5767. The cursor will be at the beginning of the entry.
  5768. When a subtree is being promoted, the hook will be called for each node.")
  5769. (defun org-promote-subtree ()
  5770. "Promote the entire subtree.
  5771. See also `org-promote'."
  5772. (interactive)
  5773. (save-excursion
  5774. (org-back-to-heading t)
  5775. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5776. (org-with-limited-levels (org-map-tree 'org-promote))))
  5777. (org-fix-position-after-promote))
  5778. (defun org-demote-subtree ()
  5779. "Demote the entire subtree.
  5780. See `org-demote' and `org-promote'."
  5781. (interactive)
  5782. (save-excursion
  5783. (org-back-to-heading t)
  5784. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5785. (org-with-limited-levels (org-map-tree 'org-demote))))
  5786. (org-fix-position-after-promote))
  5787. (defun org-do-promote ()
  5788. "Promote the current heading higher up the tree.
  5789. If the region is active in `transient-mark-mode', promote all
  5790. headings in the region."
  5791. (interactive)
  5792. (save-excursion
  5793. (if (org-region-active-p)
  5794. (org-map-region 'org-promote (region-beginning) (region-end))
  5795. (org-promote)))
  5796. (org-fix-position-after-promote))
  5797. (defun org-do-demote ()
  5798. "Demote the current heading lower down the tree.
  5799. If the region is active in `transient-mark-mode', demote all
  5800. headings in the region."
  5801. (interactive)
  5802. (save-excursion
  5803. (if (org-region-active-p)
  5804. (org-map-region 'org-demote (region-beginning) (region-end))
  5805. (org-demote)))
  5806. (org-fix-position-after-promote))
  5807. (defun org-fix-position-after-promote ()
  5808. "Fix cursor position and indentation after demoting/promoting."
  5809. (let ((pos (point)))
  5810. (when (save-excursion
  5811. (beginning-of-line)
  5812. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5813. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5814. (cond ((eobp) (insert " "))
  5815. ((eolp) (insert " "))
  5816. ((equal (char-after) ?\s) (forward-char 1))))))
  5817. (defun org-current-level ()
  5818. "Return the level of the current entry, or nil if before the first headline.
  5819. The level is the number of stars at the beginning of the
  5820. headline. Use `org-reduced-level' to remove the effect of
  5821. `org-odd-levels'. Unlike to `org-outline-level', this function
  5822. ignores inlinetasks."
  5823. (let ((level (org-with-limited-levels (org-outline-level))))
  5824. (and (> level 0) level)))
  5825. (defun org-get-previous-line-level ()
  5826. "Return the outline depth of the last headline before the current line.
  5827. Returns 0 for the first headline in the buffer, and nil if before the
  5828. first headline."
  5829. (and (org-current-level)
  5830. (or (and (/= (line-beginning-position) (point-min))
  5831. (save-excursion (beginning-of-line 0) (org-current-level)))
  5832. 0)))
  5833. (defun org-reduced-level (l)
  5834. "Compute the effective level of a heading.
  5835. This takes into account the setting of `org-odd-levels-only'."
  5836. (cond
  5837. ((zerop l) 0)
  5838. (org-odd-levels-only (1+ (floor (/ l 2))))
  5839. (t l)))
  5840. (defun org-level-increment ()
  5841. "Return the number of stars that will be added or removed at a
  5842. time to headlines when structure editing, based on the value of
  5843. `org-odd-levels-only'."
  5844. (if org-odd-levels-only 2 1))
  5845. (defun org-get-valid-level (level &optional change)
  5846. "Rectify a level change under the influence of `org-odd-levels-only'.
  5847. LEVEL is a current level, CHANGE is by how much the level should
  5848. be modified. Even if CHANGE is nil, LEVEL may be returned
  5849. modified because even level numbers will become the next higher
  5850. odd number. Returns values greater than 0."
  5851. (if org-odd-levels-only
  5852. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5853. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5854. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5855. (max 1 (+ level (or change 0)))))
  5856. (defun org-promote ()
  5857. "Promote the current heading higher up the tree."
  5858. (org-with-wide-buffer
  5859. (org-back-to-heading t)
  5860. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5861. after-change-functions))
  5862. (level (save-match-data (funcall outline-level)))
  5863. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5864. (diff (abs (- level (length up-head) -1))))
  5865. (cond
  5866. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5867. (replace-match "# " nil t))
  5868. ((= level 1)
  5869. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5870. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5871. (unless (= level 1)
  5872. (when org-auto-align-tags (org-align-tags))
  5873. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5874. (run-hooks 'org-after-promote-entry-hook))))
  5875. (defun org-demote ()
  5876. "Demote the current heading lower down the tree."
  5877. (org-with-wide-buffer
  5878. (org-back-to-heading t)
  5879. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5880. after-change-functions))
  5881. (level (save-match-data (funcall outline-level)))
  5882. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5883. (diff (abs (- level (length down-head) -1))))
  5884. (org-fold-core-ignore-fragility-checks
  5885. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5886. (when org-auto-align-tags (org-align-tags))
  5887. (when org-adapt-indentation (org-fixup-indentation diff)))
  5888. (run-hooks 'org-after-demote-entry-hook))))
  5889. (defun org-cycle-level ()
  5890. "Cycle the level of an empty headline through possible states.
  5891. This goes first to child, then to parent, level, then up the hierarchy.
  5892. After top level, it switches back to sibling level."
  5893. (interactive)
  5894. (let ((org-adapt-indentation nil))
  5895. (when (org-point-at-end-of-empty-headline)
  5896. (setq this-command 'org-cycle-level) ; Only needed for caching
  5897. (let ((cur-level (org-current-level))
  5898. (prev-level (org-get-previous-line-level)))
  5899. (cond
  5900. ;; If first headline in file, promote to top-level.
  5901. ((= prev-level 0)
  5902. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5903. do (org-do-promote)))
  5904. ;; If same level as prev, demote one.
  5905. ((= prev-level cur-level)
  5906. (org-do-demote))
  5907. ;; If parent is top-level, promote to top level if not already.
  5908. ((= prev-level 1)
  5909. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5910. do (org-do-promote)))
  5911. ;; If top-level, return to prev-level.
  5912. ((= cur-level 1)
  5913. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5914. do (org-do-demote)))
  5915. ;; If less than prev-level, promote one.
  5916. ((< cur-level prev-level)
  5917. (org-do-promote))
  5918. ;; If deeper than prev-level, promote until higher than
  5919. ;; prev-level.
  5920. ((> cur-level prev-level)
  5921. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5922. do (org-do-promote))))
  5923. t))))
  5924. (defun org-map-tree (fun)
  5925. "Call FUN for every heading underneath the current one."
  5926. (org-back-to-heading t)
  5927. (let ((level (funcall outline-level)))
  5928. (save-excursion
  5929. (funcall fun)
  5930. (while (and (progn
  5931. (outline-next-heading)
  5932. (> (funcall outline-level) level))
  5933. (not (eobp)))
  5934. (funcall fun)))))
  5935. (defun org-map-region (fun beg end)
  5936. "Call FUN for every heading between BEG and END."
  5937. (let ((org-ignore-region t))
  5938. (save-excursion
  5939. (setq end (copy-marker end))
  5940. (goto-char beg)
  5941. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5942. (< (point) end))
  5943. (funcall fun))
  5944. (while (and (progn
  5945. (outline-next-heading)
  5946. (< (point) end))
  5947. (not (eobp)))
  5948. (funcall fun)))))
  5949. (defun org-fixup-indentation (diff)
  5950. "Change the indentation in the current entry by DIFF.
  5951. DIFF is an integer. Indentation is done according to the
  5952. following rules:
  5953. - Planning information and property drawers are always indented
  5954. according to the new level of the headline;
  5955. - Footnote definitions and their contents are ignored;
  5956. - Inlinetasks' boundaries are not shifted;
  5957. - Empty lines are ignored;
  5958. - Other lines' indentation are shifted by DIFF columns, unless
  5959. it would introduce a structural change in the document, in
  5960. which case no shifting is done at all.
  5961. Assume point is at a heading or an inlinetask beginning."
  5962. (org-with-wide-buffer
  5963. (narrow-to-region (line-beginning-position)
  5964. (save-excursion
  5965. (if (org-with-limited-levels (org-at-heading-p))
  5966. (org-with-limited-levels (outline-next-heading))
  5967. (org-inlinetask-goto-end))
  5968. (point)))
  5969. (forward-line)
  5970. ;; Indent properly planning info and property drawer.
  5971. (when (looking-at-p org-planning-line-re)
  5972. (org-indent-line)
  5973. (forward-line))
  5974. (when (looking-at org-property-drawer-re)
  5975. (goto-char (match-end 0))
  5976. (forward-line)
  5977. (org-indent-region (match-beginning 0) (match-end 0)))
  5978. (when (looking-at org-logbook-drawer-re)
  5979. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5980. (col (+ (current-indentation) diff)))
  5981. (when (wholenump col)
  5982. (while (< (point) end-marker)
  5983. (if (natnump diff)
  5984. (insert (make-string diff 32))
  5985. (delete-char (abs diff)))
  5986. (forward-line)))))
  5987. (catch 'no-shift
  5988. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5989. (throw 'no-shift nil))
  5990. ;; If DIFF is negative, first check if a shift is possible at all
  5991. ;; (e.g., it doesn't break structure). This can only happen if
  5992. ;; some contents are not properly indented.
  5993. (let ((case-fold-search t))
  5994. (when (< diff 0)
  5995. (let ((diff (- diff))
  5996. (forbidden-re (concat org-outline-regexp
  5997. "\\|"
  5998. (substring org-footnote-definition-re 1))))
  5999. (save-excursion
  6000. (while (not (eobp))
  6001. (cond
  6002. ((looking-at-p "[ \t]*$") (forward-line))
  6003. ((and (looking-at-p org-footnote-definition-re)
  6004. (let ((e (org-element-at-point)))
  6005. (and (eq (org-element-type e) 'footnote-definition)
  6006. (goto-char (org-element-property :end e))))))
  6007. ((looking-at-p org-outline-regexp) (forward-line))
  6008. ;; Give up if shifting would move before column 0 or
  6009. ;; if it would introduce a headline or a footnote
  6010. ;; definition.
  6011. (t
  6012. (skip-chars-forward " \t")
  6013. (let ((ind (current-column)))
  6014. (when (or (< ind diff)
  6015. (and (= ind diff) (looking-at-p forbidden-re)))
  6016. (throw 'no-shift nil)))
  6017. ;; Ignore contents of example blocks and source
  6018. ;; blocks if their indentation is meant to be
  6019. ;; preserved. Jump to block's closing line.
  6020. (beginning-of-line)
  6021. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6022. (let ((e (org-element-at-point)))
  6023. (and (memq (org-element-type e)
  6024. '(example-block src-block))
  6025. (or org-src-preserve-indentation
  6026. (org-element-property :preserve-indent e))
  6027. (goto-char (org-element-property :end e))
  6028. (progn (skip-chars-backward " \r\t\n")
  6029. (beginning-of-line)
  6030. t))))
  6031. (forward-line))))))))
  6032. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6033. ;; by DIFF. Also skip contents of source or example blocks
  6034. ;; when indentation is meant to be preserved.
  6035. (while (not (eobp))
  6036. (cond
  6037. ((and (looking-at-p org-footnote-definition-re)
  6038. (let ((e (org-element-at-point)))
  6039. (and (eq (org-element-type e) 'footnote-definition)
  6040. (goto-char (org-element-property :end e))))))
  6041. ((looking-at-p org-outline-regexp) (forward-line))
  6042. ((looking-at-p "[ \t]*$") (forward-line))
  6043. (t
  6044. (indent-line-to (+ (current-indentation) diff))
  6045. (beginning-of-line)
  6046. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6047. (let ((e (org-element-at-point)))
  6048. (and (memq (org-element-type e)
  6049. '(example-block src-block))
  6050. (or org-src-preserve-indentation
  6051. (org-element-property :preserve-indent e))
  6052. (goto-char (org-element-property :end e))
  6053. (progn (skip-chars-backward " \r\t\n")
  6054. (beginning-of-line)
  6055. t))))
  6056. (forward-line)))))))))
  6057. (defun org-convert-to-odd-levels ()
  6058. "Convert an Org file with all levels allowed to one with odd levels.
  6059. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6060. level 5 etc."
  6061. (interactive)
  6062. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6063. (let ((outline-level 'org-outline-level)
  6064. (org-odd-levels-only nil) n)
  6065. (save-excursion
  6066. (goto-char (point-min))
  6067. (while (re-search-forward "^\\*\\*+ " nil t)
  6068. (setq n (- (length (match-string 0)) 2))
  6069. (while (>= (setq n (1- n)) 0)
  6070. (org-demote))
  6071. (end-of-line 1))))))
  6072. (defun org-convert-to-oddeven-levels ()
  6073. "Convert an Org file with only odd levels to one with odd/even levels.
  6074. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6075. file contains a section with an even level, conversion would
  6076. destroy the structure of the file. An error is signaled in this
  6077. case."
  6078. (interactive)
  6079. (goto-char (point-min))
  6080. ;; First check if there are no even levels
  6081. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6082. (org-fold-show-set-visibility 'canonical)
  6083. (error "Not all levels are odd in this file. Conversion not possible"))
  6084. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6085. (let ((outline-regexp org-outline-regexp)
  6086. (outline-level 'org-outline-level)
  6087. (org-odd-levels-only nil) n)
  6088. (save-excursion
  6089. (goto-char (point-min))
  6090. (while (re-search-forward "^\\*\\*+ " nil t)
  6091. (setq n (/ (1- (length (match-string 0))) 2))
  6092. (while (>= (setq n (1- n)) 0)
  6093. (org-promote))
  6094. (end-of-line 1))))))
  6095. (defun org-tr-level (n)
  6096. "Make N odd if required."
  6097. (if org-odd-levels-only (1+ (/ n 2)) n))
  6098. ;;; Vertical tree motion, cutting and pasting of subtrees
  6099. (defun org-move-subtree-up (&optional arg)
  6100. "Move the current subtree up past ARG headlines of the same level."
  6101. (interactive "p")
  6102. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6103. (defun org-clean-visibility-after-subtree-move ()
  6104. "Fix visibility issues after moving a subtree."
  6105. ;; First, find a reasonable region to look at:
  6106. ;; Start two siblings above, end three below
  6107. (let* ((beg (save-excursion
  6108. (and (org-get-previous-sibling)
  6109. (org-get-previous-sibling))
  6110. (point)))
  6111. (end (save-excursion
  6112. (and (org-get-next-sibling)
  6113. (org-get-next-sibling)
  6114. (org-get-next-sibling))
  6115. (if (org-at-heading-p)
  6116. (line-end-position)
  6117. (point))))
  6118. (level (looking-at "\\*+"))
  6119. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6120. (save-excursion
  6121. (save-restriction
  6122. (narrow-to-region beg end)
  6123. (when re
  6124. ;; Properly fold already folded siblings
  6125. (goto-char (point-min))
  6126. (while (re-search-forward re nil t)
  6127. (when (and (not (org-invisible-p))
  6128. (org-invisible-p (line-end-position)))
  6129. (org-fold-heading nil))))
  6130. (org-cycle-hide-drawers 'all)
  6131. (org-cycle-show-empty-lines 'overview)))))
  6132. (defun org-move-subtree-down (&optional arg)
  6133. "Move the current subtree down past ARG headlines of the same level."
  6134. (interactive "p")
  6135. (setq arg (prefix-numeric-value arg))
  6136. (org-preserve-local-variables
  6137. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6138. 'org-get-previous-sibling))
  6139. (ins-point (make-marker))
  6140. (cnt (abs arg))
  6141. (col (current-column))
  6142. beg end txt folded)
  6143. ;; Select the tree
  6144. (org-back-to-heading)
  6145. (setq beg (point))
  6146. (save-match-data
  6147. (save-excursion (outline-end-of-heading)
  6148. (setq folded (org-invisible-p)))
  6149. (progn (org-end-of-subtree nil t)
  6150. (unless (eobp) (backward-char))))
  6151. (outline-next-heading)
  6152. (setq end (point))
  6153. (goto-char beg)
  6154. ;; Find insertion point, with error handling
  6155. (while (> cnt 0)
  6156. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6157. (goto-char beg)
  6158. (user-error "Cannot move past superior level or buffer limit"))
  6159. (setq cnt (1- cnt)))
  6160. (when (> arg 0)
  6161. ;; Moving forward - still need to move over subtree
  6162. (org-end-of-subtree t t)
  6163. (save-excursion
  6164. (org-back-over-empty-lines)
  6165. (or (bolp) (newline))))
  6166. (move-marker ins-point (point))
  6167. (setq txt (buffer-substring beg end))
  6168. (org-save-markers-in-region beg end)
  6169. (delete-region beg end)
  6170. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  6171. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6172. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6173. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6174. (let ((bbb (point)))
  6175. (insert-before-markers txt)
  6176. (org-reinstall-markers-in-region bbb)
  6177. (move-marker ins-point bbb))
  6178. (or (bolp) (insert "\n"))
  6179. (goto-char ins-point)
  6180. (org-skip-whitespace)
  6181. (move-marker ins-point nil)
  6182. (if folded
  6183. (org-fold-subtree t)
  6184. (org-fold-show-entry 'hide-drawers)
  6185. (org-fold-show-children))
  6186. (org-clean-visibility-after-subtree-move)
  6187. ;; move back to the initial column we were at
  6188. (move-to-column col))))
  6189. (defvar org-subtree-clip ""
  6190. "Clipboard for cut and paste of subtrees.
  6191. This is actually only a copy of the kill, because we use the normal kill
  6192. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6193. (defvar org-subtree-clip-folded nil
  6194. "Was the last copied subtree folded?
  6195. This is used to fold the tree back after pasting.")
  6196. (defun org-cut-subtree (&optional n)
  6197. "Cut the current subtree into the clipboard.
  6198. With prefix arg N, cut this many sequential subtrees.
  6199. This is a short-hand for marking the subtree and then cutting it."
  6200. (interactive "p")
  6201. (org-copy-subtree n 'cut))
  6202. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6203. "Copy the current subtree into the clipboard.
  6204. With prefix arg N, copy this many sequential subtrees.
  6205. This is a short-hand for marking the subtree and then copying it.
  6206. If CUT is non-nil, actually cut the subtree.
  6207. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6208. of some markers in the region, even if CUT is non-nil. This is
  6209. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6210. (interactive "p")
  6211. (org-preserve-local-variables
  6212. (let (beg end folded (beg0 (point)))
  6213. (if (called-interactively-p 'any)
  6214. (org-back-to-heading nil) ; take what looks like a subtree
  6215. (org-back-to-heading t)) ; take what is really there
  6216. (setq beg (point))
  6217. (skip-chars-forward " \t\r\n")
  6218. (save-match-data
  6219. (if nosubtrees
  6220. (outline-next-heading)
  6221. (save-excursion (outline-end-of-heading)
  6222. (setq folded (org-invisible-p)))
  6223. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6224. (org-end-of-subtree t t)))
  6225. ;; Include the end of an inlinetask
  6226. (when (and (featurep 'org-inlinetask)
  6227. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6228. "END[ \t]*$")))
  6229. (end-of-line))
  6230. (setq end (point))
  6231. (goto-char beg0)
  6232. (when (> end beg)
  6233. (setq org-subtree-clip-folded folded)
  6234. (when (or cut force-store-markers)
  6235. (org-save-markers-in-region beg end))
  6236. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6237. (setq org-subtree-clip (current-kill 0))
  6238. (message "%s: Subtree(s) with %d characters"
  6239. (if cut "Cut" "Copied")
  6240. (length org-subtree-clip))))))
  6241. (defun org-paste-subtree (&optional level tree for-yank remove)
  6242. "Paste the clipboard as a subtree, with modification of headline level.
  6243. The entire subtree is promoted or demoted in order to match a new headline
  6244. level.
  6245. If the cursor is at the beginning of a headline, the same level as
  6246. that headline is used to paste the tree.
  6247. If not, the new level is derived from the *visible* headings
  6248. before and after the insertion point, and taken to be the inferior headline
  6249. level of the two. So if the previous visible heading is level 3 and the
  6250. next is level 4 (or vice versa), level 4 will be used for insertion.
  6251. This makes sure that the subtree remains an independent subtree and does
  6252. not swallow low level entries.
  6253. You can also force a different level, either by using a numeric prefix
  6254. argument, or by inserting the heading marker by hand. For example, if the
  6255. cursor is after \"*****\", then the tree will be shifted to level 5.
  6256. If optional TREE is given, use this text instead of the kill ring.
  6257. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6258. move back over whitespace before inserting, and move point to the end of
  6259. the inserted text when done.
  6260. When REMOVE is non-nil, remove the subtree from the clipboard."
  6261. (interactive "P")
  6262. (setq tree (or tree (and kill-ring (current-kill 0))))
  6263. (unless (org-kill-is-subtree-p tree)
  6264. (user-error
  6265. (substitute-command-keys
  6266. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6267. (org-with-limited-levels
  6268. (org-fold-core-ignore-fragility-checks
  6269. (let* ((visp (not (org-invisible-p)))
  6270. (txt tree)
  6271. (old-level (if (string-match org-outline-regexp-bol txt)
  6272. (- (match-end 0) (match-beginning 0) 1)
  6273. -1))
  6274. (force-level
  6275. (cond
  6276. (level (prefix-numeric-value level))
  6277. ;; When point is after the stars in an otherwise empty
  6278. ;; headline, use the number of stars as the forced level.
  6279. ((and (org-match-line "^\\*+[ \t]*$")
  6280. (not (eq ?* (char-after))))
  6281. (org-outline-level))
  6282. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6283. (previous-level
  6284. (save-excursion
  6285. (org-previous-visible-heading 1)
  6286. (if (org-at-heading-p) (org-outline-level) 1)))
  6287. (next-level
  6288. (save-excursion
  6289. (if (org-at-heading-p) (org-outline-level)
  6290. (org-next-visible-heading 1)
  6291. (if (org-at-heading-p) (org-outline-level) 1))))
  6292. (new-level (or force-level (max previous-level next-level)))
  6293. (shift (if (or (= old-level -1)
  6294. (= new-level -1)
  6295. (= old-level new-level))
  6296. 0
  6297. (- new-level old-level)))
  6298. (delta (if (> shift 0) -1 1))
  6299. (func (if (> shift 0) #'org-demote #'org-promote))
  6300. (org-odd-levels-only nil)
  6301. beg end newend)
  6302. ;; Remove the forced level indicator.
  6303. (when (and force-level (not level))
  6304. (delete-region (line-beginning-position) (point)))
  6305. ;; Paste before the next visible heading or at end of buffer,
  6306. ;; unless point is at the beginning of a headline.
  6307. (unless (and (bolp) (org-at-heading-p))
  6308. (org-next-visible-heading 1)
  6309. (unless (bolp) (insert "\n")))
  6310. (setq beg (point))
  6311. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6312. ;; is inserted and then promoted.
  6313. (combine-change-calls beg beg
  6314. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6315. (insert txt)
  6316. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6317. (setq newend (point))
  6318. (org-reinstall-markers-in-region beg)
  6319. (setq end (point))
  6320. (goto-char beg)
  6321. (skip-chars-forward " \t\n\r")
  6322. (setq beg (point))
  6323. (when (and (org-invisible-p) visp)
  6324. (save-excursion (org-fold-heading nil)))
  6325. ;; Shift if necessary.
  6326. (unless (= shift 0)
  6327. (save-restriction
  6328. (narrow-to-region beg end)
  6329. (while (not (= shift 0))
  6330. (org-map-region func (point-min) (point-max))
  6331. (setq shift (+ delta shift)))
  6332. (goto-char (point-min))
  6333. (setq newend (point-max)))))
  6334. (when (or for-yank (called-interactively-p 'interactive))
  6335. (message "Clipboard pasted as level %d subtree" new-level))
  6336. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6337. kill-ring
  6338. (equal org-subtree-clip (current-kill 0))
  6339. org-subtree-clip-folded)
  6340. ;; The tree was folded before it was killed/copied
  6341. (org-fold-subtree t))
  6342. (when for-yank (goto-char newend))
  6343. (when remove (pop kill-ring))))))
  6344. (defun org-kill-is-subtree-p (&optional txt)
  6345. "Check if the current kill is an outline subtree, or a set of trees.
  6346. Returns nil if kill does not start with a headline, or if the first
  6347. headline level is not the largest headline level in the tree.
  6348. So this will actually accept several entries of equal levels as well,
  6349. which is OK for `org-paste-subtree'.
  6350. If optional TXT is given, check this string instead of the current kill."
  6351. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6352. (re (org-get-limited-outline-regexp))
  6353. (^re (concat "^" re))
  6354. (start-level (and kill
  6355. (string-match
  6356. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6357. kill)
  6358. (- (match-end 2) (match-beginning 2) 1)))
  6359. (start (1+ (or (match-beginning 2) -1))))
  6360. (if (not start-level)
  6361. (progn
  6362. nil) ;; does not even start with a heading
  6363. (catch 'exit
  6364. (while (setq start (string-match ^re kill (1+ start)))
  6365. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6366. (throw 'exit nil)))
  6367. t))))
  6368. (defvar org-markers-to-move nil
  6369. "Markers that should be moved with a cut-and-paste operation.
  6370. Those markers are stored together with their positions relative to
  6371. the start of the region.")
  6372. (defun org-save-markers-in-region (beg end)
  6373. "Check markers in region.
  6374. If these markers are between BEG and END, record their position relative
  6375. to BEG, so that after moving the block of text, we can put the markers back
  6376. into place.
  6377. This function gets called just before an entry or tree gets cut from the
  6378. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6379. called immediately, to move the markers with the entries."
  6380. (setq org-markers-to-move nil)
  6381. (when (featurep 'org-clock)
  6382. (org-clock-save-markers-for-cut-and-paste beg end))
  6383. (when (featurep 'org-agenda)
  6384. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6385. (defun org-check-and-save-marker (marker beg end)
  6386. "Check if MARKER is between BEG and END.
  6387. If yes, remember the marker and the distance to BEG."
  6388. (when (and (marker-buffer marker)
  6389. (or (equal (marker-buffer marker) (current-buffer))
  6390. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6391. (>= marker beg) (< marker end))
  6392. (push (cons marker (- marker beg)) org-markers-to-move)))
  6393. (defun org-reinstall-markers-in-region (beg)
  6394. "Move all remembered markers to their position relative to BEG."
  6395. (dolist (x org-markers-to-move)
  6396. (move-marker (car x) (+ beg (cdr x))))
  6397. (setq org-markers-to-move nil))
  6398. (defun org-narrow-to-subtree (&optional element)
  6399. "Narrow buffer to the current subtree."
  6400. (interactive)
  6401. (if (org-element--cache-active-p)
  6402. (let* ((heading (org-element-lineage
  6403. (or element (org-element-at-point))
  6404. '(headline) t))
  6405. (end (org-element-property :end heading)))
  6406. (if (and heading end)
  6407. (narrow-to-region (org-element-property :begin heading)
  6408. (if (= end (point-max))
  6409. end (1- end)))
  6410. (signal 'outline-before-first-heading nil)))
  6411. (save-excursion
  6412. (save-match-data
  6413. (org-with-limited-levels
  6414. (narrow-to-region
  6415. (progn (org-back-to-heading t) (point))
  6416. (progn (org-end-of-subtree t t)
  6417. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6418. (point))))))))
  6419. (defun org-toggle-narrow-to-subtree ()
  6420. "Narrow to the subtree at point or widen a narrowed buffer."
  6421. (interactive)
  6422. (if (buffer-narrowed-p)
  6423. (progn (widen) (message "Buffer widen"))
  6424. (org-narrow-to-subtree)
  6425. (message "Buffer narrowed to current subtree")))
  6426. (defun org-narrow-to-block ()
  6427. "Narrow buffer to the current block."
  6428. (interactive)
  6429. (let* ((case-fold-search t)
  6430. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6431. "^[ \t]*#\\+end_.*")))
  6432. (if blockp
  6433. (narrow-to-region (car blockp) (cdr blockp))
  6434. (user-error "Not in a block"))))
  6435. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6436. "Clone the task (subtree) at point N times.
  6437. The clones will be inserted as siblings.
  6438. In interactive use, the user will be prompted for the number of
  6439. clones to be produced. If the entry has a timestamp, the user
  6440. will also be prompted for a time shift, which may be a repeater
  6441. as used in time stamps, for example `+3d'. To disable this,
  6442. you can call the function with a universal prefix argument.
  6443. When a valid repeater is given and the entry contains any time
  6444. stamps, the clones will become a sequence in time, with time
  6445. stamps in the subtree shifted for each clone produced. If SHIFT
  6446. is nil or the empty string, time stamps will be left alone. The
  6447. ID property of the original subtree is removed.
  6448. In each clone, all the CLOCK entries will be removed. This
  6449. prevents Org from considering that the clocked times overlap.
  6450. If the original subtree did contain time stamps with a repeater,
  6451. the following will happen:
  6452. - the repeater will be removed in each clone
  6453. - an additional clone will be produced, with the current, unshifted
  6454. date(s) in the entry.
  6455. - the original entry will be placed *after* all the clones, with
  6456. repeater intact.
  6457. - the start days in the repeater in the original entry will be shifted
  6458. to past the last clone.
  6459. In this way you can spell out a number of instances of a repeating task,
  6460. and still retain the repeater to cover future instances of the task.
  6461. As described above, N+1 clones are produced when the original
  6462. subtree has a repeater. Setting N to 0, then, can be used to
  6463. remove the repeater from a subtree and create a shifted clone
  6464. with the original repeater."
  6465. (interactive "nNumber of clones to produce: ")
  6466. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6467. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6468. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6469. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6470. (shift
  6471. (or shift
  6472. (if (and (not (equal current-prefix-arg '(4)))
  6473. (save-excursion
  6474. (goto-char beg)
  6475. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6476. (read-from-minibuffer
  6477. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6478. ""))) ;No time shift
  6479. (doshift
  6480. (and (org-string-nw-p shift)
  6481. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6482. shift)
  6483. (user-error "Invalid shift specification %s" shift)))))
  6484. (goto-char end-of-tree)
  6485. (unless (bolp) (insert "\n"))
  6486. (let* ((end (point))
  6487. (template (buffer-substring beg end))
  6488. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6489. (shift-what (pcase (and doshift (match-string 2 shift))
  6490. (`nil nil)
  6491. ("h" 'hour)
  6492. ("d" 'day)
  6493. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6494. ("m" 'month)
  6495. ("y" 'year)
  6496. (_ (error "Unsupported time unit"))))
  6497. (nmin 1)
  6498. (nmax n)
  6499. (n-no-remove -1)
  6500. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6501. (idprop (org-entry-get beg "ID")))
  6502. (when (and doshift
  6503. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6504. template))
  6505. (delete-region beg end)
  6506. (setq end beg)
  6507. (setq nmin 0)
  6508. (setq nmax (1+ nmax))
  6509. (setq n-no-remove nmax))
  6510. (goto-char end)
  6511. (cl-loop for n from nmin to nmax do
  6512. (insert
  6513. ;; Prepare clone.
  6514. (with-temp-buffer
  6515. (insert template)
  6516. (org-mode)
  6517. (goto-char (point-min))
  6518. (org-fold-show-subtree)
  6519. (and idprop (if org-clone-delete-id
  6520. (org-entry-delete nil "ID")
  6521. (org-id-get-create t)))
  6522. (unless (= n 0)
  6523. (while (re-search-forward org-clock-line-re nil t)
  6524. (delete-region (line-beginning-position)
  6525. (line-beginning-position 2)))
  6526. (goto-char (point-min))
  6527. (while (re-search-forward org-drawer-regexp nil t)
  6528. (org-remove-empty-drawer-at (point))))
  6529. (goto-char (point-min))
  6530. (when doshift
  6531. (while (re-search-forward org-ts-regexp-both nil t)
  6532. (org-timestamp-change (* n shift-n) shift-what))
  6533. (unless (= n n-no-remove)
  6534. (goto-char (point-min))
  6535. (while (re-search-forward org-ts-regexp nil t)
  6536. (save-excursion
  6537. (goto-char (match-beginning 0))
  6538. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6539. (delete-region (match-beginning 1) (match-end 1)))))))
  6540. (buffer-string)))))
  6541. (goto-char beg)))
  6542. ;;; Outline path
  6543. (defvar org-outline-path-cache nil
  6544. "Alist between buffer positions and outline paths.
  6545. It value is an alist (POSITION . PATH) where POSITION is the
  6546. buffer position at the beginning of an entry and PATH is a list
  6547. of strings describing the outline path for that entry, in reverse
  6548. order.")
  6549. (defun org--get-outline-path-1 (&optional use-cache)
  6550. "Return outline path to current headline.
  6551. Outline path is a list of strings, in reverse order. When
  6552. optional argument USE-CACHE is non-nil, make use of a cache. See
  6553. `org-get-outline-path' for details.
  6554. Assume buffer is widened and point is on a headline."
  6555. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6556. (let ((p (point))
  6557. (heading (let ((case-fold-search nil))
  6558. (looking-at org-complex-heading-regexp)
  6559. (if (not (match-end 4)) ""
  6560. ;; Remove statistics cookies.
  6561. (org-trim
  6562. (org-link-display-format
  6563. (replace-regexp-in-string
  6564. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6565. (match-string-no-properties 4))))))))
  6566. (if (org-up-heading-safe)
  6567. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6568. (when use-cache
  6569. (push (cons p path) org-outline-path-cache))
  6570. path)
  6571. ;; This is a new root node. Since we assume we are moving
  6572. ;; forward, we can drop previous cache so as to limit number
  6573. ;; of associations there.
  6574. (let ((path (list heading)))
  6575. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6576. path)))))
  6577. (defun org-get-outline-path (&optional with-self use-cache)
  6578. "Return the outline path to the current entry.
  6579. An outline path is a list of ancestors for current headline, as
  6580. a list of strings. Statistics cookies are removed and links are
  6581. replaced with their description, if any, or their path otherwise.
  6582. When optional argument WITH-SELF is non-nil, the path also
  6583. includes the current headline.
  6584. When optional argument USE-CACHE is non-nil, cache outline paths
  6585. between calls to this function so as to avoid backtracking. This
  6586. argument is useful when planning to find more than one outline
  6587. path in the same document. In that case, there are two
  6588. conditions to satisfy:
  6589. - `org-outline-path-cache' is set to nil before starting the
  6590. process;
  6591. - outline paths are computed by increasing buffer positions."
  6592. (org-with-wide-buffer
  6593. (and (or (and with-self (org-back-to-heading t))
  6594. (org-up-heading-safe))
  6595. (reverse (org--get-outline-path-1 use-cache)))))
  6596. (defun org-format-outline-path (path &optional width prefix separator)
  6597. "Format the outline path PATH for display.
  6598. WIDTH is the maximum number of characters that is available.
  6599. PREFIX is a prefix to be included in the returned string,
  6600. such as the file name.
  6601. SEPARATOR is inserted between the different parts of the path,
  6602. the default is \"/\"."
  6603. (setq width (or width 79))
  6604. (setq path (delq nil path))
  6605. (unless (> width 0)
  6606. (user-error "Argument `width' must be positive"))
  6607. (setq separator (or separator "/"))
  6608. (let* ((org-odd-levels-only nil)
  6609. (fpath (concat
  6610. prefix (and prefix path separator)
  6611. (mapconcat
  6612. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6613. (cl-loop for head in path
  6614. for n from 0
  6615. collect (org-add-props
  6616. head nil 'face
  6617. (nth (% n org-n-level-faces) org-level-faces)))
  6618. separator))))
  6619. (when (> (length fpath) width)
  6620. (if (< width 7)
  6621. ;; It's unlikely that `width' will be this small, but don't
  6622. ;; waste characters by adding ".." if it is.
  6623. (setq fpath (substring fpath 0 width))
  6624. (setf (substring fpath (- width 2)) "..")))
  6625. fpath))
  6626. (defun org-display-outline-path (&optional file current separator just-return-string)
  6627. "Display the current outline path in the echo area.
  6628. If FILE is non-nil, prepend the output with the file name.
  6629. If CURRENT is non-nil, append the current heading to the output.
  6630. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6631. the different parts of the path and defaults to \"/\".
  6632. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6633. (interactive "P")
  6634. (let* (case-fold-search
  6635. (bfn (buffer-file-name (buffer-base-buffer)))
  6636. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6637. res)
  6638. (when current (setq path (append path
  6639. (save-excursion
  6640. (org-back-to-heading t)
  6641. (when (looking-at org-complex-heading-regexp)
  6642. (list (match-string 4)))))))
  6643. (setq res
  6644. (org-format-outline-path
  6645. path
  6646. (1- (frame-width))
  6647. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6648. separator))
  6649. (add-face-text-property 0 (length res)
  6650. `(:height ,(face-attribute 'default :height))
  6651. nil res)
  6652. (if just-return-string
  6653. res
  6654. (org-unlogged-message "%s" res))))
  6655. ;;; Outline Sorting
  6656. (defun org-sort (&optional with-case)
  6657. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6658. Optional argument WITH-CASE means sort case-sensitively."
  6659. (interactive "P")
  6660. (org-call-with-arg
  6661. (cond ((org-at-table-p) #'org-table-sort-lines)
  6662. ((org-at-item-p) #'org-sort-list)
  6663. (t #'org-sort-entries))
  6664. with-case))
  6665. (defun org-sort-remove-invisible (s)
  6666. "Remove emphasis markers and any invisible property from string S.
  6667. Assume S may contain only objects."
  6668. ;; org-element-interpret-data clears any text property, including
  6669. ;; invisible part.
  6670. (org-element-interpret-data
  6671. (let ((tree (org-element-parse-secondary-string
  6672. s (org-element-restriction 'paragraph))))
  6673. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6674. (lambda (o)
  6675. (pcase (org-element-type o)
  6676. ;; Terminal object. Replace it with its value.
  6677. ((or `code `verbatim)
  6678. (let ((new (org-element-property :value o)))
  6679. (org-element-insert-before new o)
  6680. (org-element-put-property
  6681. new :post-blank (org-element-property :post-blank o))))
  6682. ;; Non-terminal objects. Splice contents.
  6683. (type
  6684. (let ((contents
  6685. (or (org-element-contents o)
  6686. (and (eq type 'link)
  6687. (list (org-element-property :raw-link o)))))
  6688. (c nil))
  6689. (while contents
  6690. (setq c (pop contents))
  6691. (org-element-insert-before c o))
  6692. (org-element-put-property
  6693. c :post-blank (org-element-property :post-blank o)))))
  6694. (org-element-extract-element o)))
  6695. ;; Return modified tree.
  6696. tree)))
  6697. (defvar org-after-sorting-entries-or-items-hook nil
  6698. "Hook that is run after a bunch of entries or items have been sorted.
  6699. When children are sorted, the cursor is in the parent line when this
  6700. hook gets called. When a region or a plain list is sorted, the cursor
  6701. will be in the first entry of the sorted region/list.")
  6702. (defun org-sort-entries
  6703. (&optional with-case sorting-type getkey-func compare-func property
  6704. interactive?)
  6705. "Sort entries on a certain level of an outline tree.
  6706. If there is an active region, the entries in the region are sorted.
  6707. Else, if the cursor is before the first entry, sort the top-level items.
  6708. Else, the children of the entry at point are sorted.
  6709. Sorting can be alphabetically, numerically, by date/time as given by
  6710. a time stamp, by a property, by priority order, or by a custom function.
  6711. The command prompts for the sorting type unless it has been given to the
  6712. function through the SORTING-TYPE argument, which needs to be a character,
  6713. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6714. the precise meaning of each character:
  6715. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6716. c By creation time, which is assumed to be the first inactive time stamp
  6717. at the beginning of a line.
  6718. d By deadline date/time.
  6719. k By clocking time.
  6720. n Numerically, by converting the beginning of the entry/item to a number.
  6721. o By order of TODO keywords.
  6722. p By priority according to the cookie.
  6723. r By the value of a property.
  6724. s By scheduled date/time.
  6725. t By date/time, either the first active time stamp in the entry, or, if
  6726. none exist, by the first inactive one.
  6727. Capital letters will reverse the sort order.
  6728. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6729. called with point at the beginning of the record. It must return a
  6730. value that is compatible with COMPARE-FUNC, the function used to
  6731. compare entries.
  6732. Comparing entries ignores case by default. However, with an optional argument
  6733. WITH-CASE, the sorting considers case as well.
  6734. Sorting is done against the visible part of the headlines, it ignores hidden
  6735. links.
  6736. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6737. A non-nil value for INTERACTIVE? is used to signal that this
  6738. function is being called interactively."
  6739. (interactive (list current-prefix-arg nil nil nil nil t))
  6740. (let ((case-func (if with-case 'identity 'downcase))
  6741. start beg end stars re re2
  6742. txt what tmp)
  6743. ;; Find beginning and end of region to sort
  6744. (cond
  6745. ((org-region-active-p)
  6746. ;; we will sort the region
  6747. (setq end (region-end)
  6748. what "region")
  6749. (goto-char (region-beginning))
  6750. (unless (org-at-heading-p) (outline-next-heading))
  6751. (setq start (point)))
  6752. ((or (org-at-heading-p)
  6753. (ignore-errors (progn (org-back-to-heading) t)))
  6754. ;; we will sort the children of the current headline
  6755. (org-back-to-heading)
  6756. (setq start (point)
  6757. end (progn (org-end-of-subtree t t)
  6758. (or (bolp) (insert "\n"))
  6759. (when (>= (org-back-over-empty-lines) 1)
  6760. (forward-line 1))
  6761. (point))
  6762. what "children")
  6763. (goto-char start)
  6764. (org-fold-show-subtree)
  6765. (outline-next-heading))
  6766. (t
  6767. ;; we will sort the top-level entries in this file
  6768. (goto-char (point-min))
  6769. (or (org-at-heading-p) (outline-next-heading))
  6770. (setq start (point))
  6771. (goto-char (point-max))
  6772. (beginning-of-line 1)
  6773. (when (looking-at ".*?\\S-")
  6774. ;; File ends in a non-white line
  6775. (end-of-line 1)
  6776. (insert "\n"))
  6777. (setq end (point-max))
  6778. (setq what "top-level")
  6779. (goto-char start)
  6780. (org-fold-show-all '(headings drawers blocks))))
  6781. (setq beg (point))
  6782. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6783. (looking-at "\\(\\*+\\)")
  6784. (setq stars (match-string 1)
  6785. re (concat "^" (regexp-quote stars) " +")
  6786. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6787. txt (buffer-substring beg end))
  6788. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6789. (when (and (not (equal stars "*")) (string-match re2 txt))
  6790. (user-error "Region to sort contains a level above the first entry"))
  6791. (unless sorting-type
  6792. (message
  6793. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6794. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6795. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6796. what)
  6797. (setq sorting-type (read-char-exclusive)))
  6798. (unless getkey-func
  6799. (and (= (downcase sorting-type) ?f)
  6800. (setq getkey-func
  6801. (or (and interactive?
  6802. (org-read-function
  6803. "Function for extracting keys: "))
  6804. (error "Missing key extractor")))))
  6805. (and (= (downcase sorting-type) ?r)
  6806. (not property)
  6807. (setq property
  6808. (completing-read "Property: "
  6809. (mapcar #'list (org-buffer-property-keys t))
  6810. nil t)))
  6811. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6812. (message "Sorting entries...")
  6813. (save-restriction
  6814. (narrow-to-region start end)
  6815. (let ((restore-clock?
  6816. ;; The clock marker is lost when using `sort-subr'; mark
  6817. ;; the clock with temporary `:org-clock-marker-backup'
  6818. ;; text property.
  6819. (when (and (eq (org-clocking-buffer) (current-buffer))
  6820. (<= start (marker-position org-clock-marker))
  6821. (>= end (marker-position org-clock-marker)))
  6822. (with-silent-modifications
  6823. (put-text-property (1- org-clock-marker) org-clock-marker
  6824. :org-clock-marker-backup t))
  6825. t))
  6826. (dcst (downcase sorting-type))
  6827. (case-fold-search nil)
  6828. (now (current-time)))
  6829. (org-preserve-local-variables
  6830. (sort-subr
  6831. (/= dcst sorting-type)
  6832. ;; This function moves to the beginning character of the
  6833. ;; "record" to be sorted.
  6834. (lambda nil
  6835. (if (re-search-forward re nil t)
  6836. (goto-char (match-beginning 0))
  6837. (goto-char (point-max))))
  6838. ;; This function moves to the last character of the "record" being
  6839. ;; sorted.
  6840. (lambda nil
  6841. (save-match-data
  6842. (condition-case nil
  6843. (outline-forward-same-level 1)
  6844. (error
  6845. (goto-char (point-max))))))
  6846. ;; This function returns the value that gets sorted against.
  6847. (lambda ()
  6848. (cond
  6849. ((= dcst ?n)
  6850. (string-to-number
  6851. (org-sort-remove-invisible (org-get-heading t t t t))))
  6852. ((= dcst ?a)
  6853. (funcall case-func
  6854. (org-sort-remove-invisible (org-get-heading t t t t))))
  6855. ((= dcst ?k)
  6856. (or (get-text-property (point) :org-clock-minutes) 0))
  6857. ((= dcst ?t)
  6858. (let ((end (save-excursion (outline-next-heading) (point))))
  6859. (if (or (re-search-forward org-ts-regexp end t)
  6860. (re-search-forward org-ts-regexp-both end t))
  6861. (org-time-string-to-seconds (match-string 0))
  6862. (float-time now))))
  6863. ((= dcst ?c)
  6864. (let ((end (save-excursion (outline-next-heading) (point))))
  6865. (if (re-search-forward
  6866. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6867. end t)
  6868. (org-time-string-to-seconds (match-string 0))
  6869. (float-time now))))
  6870. ((= dcst ?s)
  6871. (let ((end (save-excursion (outline-next-heading) (point))))
  6872. (if (re-search-forward org-scheduled-time-regexp end t)
  6873. (org-time-string-to-seconds (match-string 1))
  6874. (float-time now))))
  6875. ((= dcst ?d)
  6876. (let ((end (save-excursion (outline-next-heading) (point))))
  6877. (if (re-search-forward org-deadline-time-regexp end t)
  6878. (org-time-string-to-seconds (match-string 1))
  6879. (float-time now))))
  6880. ((= dcst ?p)
  6881. (if (re-search-forward org-priority-regexp (line-end-position) t)
  6882. (string-to-char (match-string 2))
  6883. org-priority-default))
  6884. ((= dcst ?r)
  6885. (or (org-entry-get nil property) ""))
  6886. ((= dcst ?o)
  6887. (when (looking-at org-complex-heading-regexp)
  6888. (let* ((m (match-string 2))
  6889. (s (if (member m org-done-keywords) '- '+)))
  6890. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6891. ((= dcst ?f)
  6892. (if getkey-func
  6893. (progn
  6894. (setq tmp (funcall getkey-func))
  6895. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6896. tmp)
  6897. (error "Invalid key function `%s'" getkey-func)))
  6898. (t (error "Invalid sorting type `%c'" sorting-type))))
  6899. nil
  6900. (cond
  6901. ((= dcst ?a) 'string-collate-lessp)
  6902. ((= dcst ?f)
  6903. (or compare-func
  6904. (and interactive?
  6905. (org-read-function
  6906. (concat "Function for comparing keys "
  6907. "(empty for default `sort-subr' predicate): ")
  6908. 'allow-empty))))
  6909. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6910. (org-cycle-hide-drawers 'all)
  6911. (when restore-clock?
  6912. (move-marker org-clock-marker
  6913. (1+ (next-single-property-change
  6914. start :org-clock-marker-backup)))
  6915. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6916. '(:org-clock-marker-backup t)))))
  6917. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6918. (message "Sorting entries...done")))
  6919. (defun org-contextualize-keys (alist contexts)
  6920. "Return valid elements in ALIST depending on CONTEXTS.
  6921. `org-agenda-custom-commands' or `org-capture-templates' are the
  6922. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6923. or `org-capture-templates-contexts' are the associated contexts
  6924. definitions."
  6925. (let ((contexts
  6926. ;; normalize contexts
  6927. (mapcar
  6928. (lambda(c) (cond ((listp (cadr c))
  6929. (list (car c) (car c) (nth 1 c)))
  6930. ((string= "" (cadr c))
  6931. (list (car c) (car c) (nth 2 c)))
  6932. (t c)))
  6933. contexts))
  6934. (a alist) r s)
  6935. ;; loop over all commands or templates
  6936. (dolist (c a)
  6937. (let (vrules repl)
  6938. (cond
  6939. ((not (assoc (car c) contexts))
  6940. (push c r))
  6941. ((and (assoc (car c) contexts)
  6942. (setq vrules (org-contextualize-validate-key
  6943. (car c) contexts)))
  6944. (mapc (lambda (vr)
  6945. (unless (equal (car vr) (cadr vr))
  6946. (setq repl vr)))
  6947. vrules)
  6948. (if (not repl) (push c r)
  6949. (push (cadr repl) s)
  6950. (push
  6951. (cons (car c)
  6952. (cdr (or (assoc (cadr repl) alist)
  6953. (error "Undefined key `%s' as contextual replacement for `%s'"
  6954. (cadr repl) (car c)))))
  6955. r))))))
  6956. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6957. (delq
  6958. nil
  6959. (delete-dups
  6960. (mapcar (lambda (x)
  6961. (let ((tpl (car x)))
  6962. (unless (delq
  6963. nil
  6964. (mapcar (lambda (y)
  6965. (equal y tpl))
  6966. s))
  6967. x)))
  6968. (reverse r))))))
  6969. (defun org-contextualize-validate-key (key contexts)
  6970. "Check CONTEXTS for agenda or capture KEY."
  6971. (let (res)
  6972. (dolist (r contexts)
  6973. (dolist (rr (car (last r)))
  6974. (when
  6975. (and (equal key (car r))
  6976. (if (functionp rr) (funcall rr)
  6977. (or (and (eq (car rr) 'in-file)
  6978. (buffer-file-name)
  6979. (string-match (cdr rr) (buffer-file-name)))
  6980. (and (eq (car rr) 'in-mode)
  6981. (string-match (cdr rr) (symbol-name major-mode)))
  6982. (and (eq (car rr) 'in-buffer)
  6983. (string-match (cdr rr) (buffer-name)))
  6984. (when (and (eq (car rr) 'not-in-file)
  6985. (buffer-file-name))
  6986. (not (string-match (cdr rr) (buffer-file-name))))
  6987. (when (eq (car rr) 'not-in-mode)
  6988. (not (string-match (cdr rr) (symbol-name major-mode))))
  6989. (when (eq (car rr) 'not-in-buffer)
  6990. (not (string-match (cdr rr) (buffer-name)))))))
  6991. (push r res))))
  6992. (delete-dups (delq nil res))))
  6993. ;; Defined to provide a value for defcustom, since there is no
  6994. ;; string-collate-greaterp in Emacs.
  6995. (defun org-string-collate-greaterp (s1 s2)
  6996. "Return non-nil if S1 is greater than S2 in collation order."
  6997. (not (string-collate-lessp s1 s2)))
  6998. ;;;###autoload
  6999. (defun org-run-like-in-org-mode (cmd)
  7000. "Run a command, pretending that the current buffer is in Org mode.
  7001. This will temporarily bind local variables that are typically bound in
  7002. Org mode to the values they have in Org mode, and then interactively
  7003. call CMD."
  7004. (org-load-modules-maybe)
  7005. (let (vars vals)
  7006. (dolist (var (org-get-local-variables))
  7007. (when (or (not (boundp (car var)))
  7008. (eq (symbol-value (car var))
  7009. (default-value (car var))))
  7010. (push (car var) vars)
  7011. (push (cadr var) vals)))
  7012. (cl-progv vars vals
  7013. (call-interactively cmd))))
  7014. (defun org-get-category (&optional pos force-refresh)
  7015. "Get the category applying to position POS."
  7016. (save-match-data
  7017. (when force-refresh (org-refresh-category-properties))
  7018. (let ((pos (or pos (point))))
  7019. (if (org-element--cache-active-p)
  7020. ;; Sync cache.
  7021. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  7022. (or (org-entry-get-with-inheritance "CATEGORY")
  7023. "???"))
  7024. (or (get-text-property pos 'org-category)
  7025. (progn
  7026. (org-refresh-category-properties)
  7027. (get-text-property pos 'org-category)))))))
  7028. ;;; Refresh properties
  7029. (defun org-refresh-properties (dprop tprop)
  7030. "Refresh buffer text properties.
  7031. DPROP is the drawer property and TPROP is either the
  7032. corresponding text property to set, or an alist with each element
  7033. being a text property (as a symbol) and a function to apply to
  7034. the value of the drawer property."
  7035. (let* ((case-fold-search t)
  7036. (inhibit-read-only t)
  7037. (inherit? (org-property-inherit-p dprop))
  7038. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7039. (global-or-keyword (and inherit?
  7040. (org--property-global-or-keyword-value dprop nil))))
  7041. (with-silent-modifications
  7042. (org-with-point-at 1
  7043. ;; Set global and keyword based values to the whole buffer.
  7044. (when global-or-keyword
  7045. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7046. ;; Set values based on property-drawers throughout the document.
  7047. (while (re-search-forward property-re nil t)
  7048. (when (org-at-property-p)
  7049. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7050. (outline-next-heading))))))
  7051. (defun org-refresh-property (tprop p &optional inherit)
  7052. "Refresh the buffer text property TPROP from the drawer property P.
  7053. The refresh happens only for the current entry, or the whole
  7054. sub-tree if optional argument INHERIT is non-nil.
  7055. If point is before first headline, the function applies to the
  7056. part before the first headline. In that particular case, when
  7057. optional argument INHERIT is non-nil, it refreshes properties for
  7058. the whole buffer."
  7059. (save-excursion
  7060. (org-back-to-heading-or-point-min t)
  7061. (let ((start (point))
  7062. (end (save-excursion
  7063. (cond ((and inherit (org-before-first-heading-p))
  7064. (point-max))
  7065. (inherit
  7066. (org-end-of-subtree t t))
  7067. ((outline-next-heading))
  7068. ((point-max))))))
  7069. (with-silent-modifications
  7070. (if (symbolp tprop)
  7071. ;; TPROP is a text property symbol.
  7072. (put-text-property start end tprop p)
  7073. ;; TPROP is an alist with (property . function) elements.
  7074. (pcase-dolist (`(,prop . ,f) tprop)
  7075. (put-text-property start end prop (funcall f p))))))))
  7076. (defun org-refresh-category-properties ()
  7077. "Refresh category text properties in the buffer."
  7078. (unless (org-element--cache-active-p)
  7079. (let ((case-fold-search t)
  7080. (inhibit-read-only t)
  7081. (default-category
  7082. (cond ((null org-category)
  7083. (if buffer-file-name
  7084. (file-name-sans-extension
  7085. (file-name-nondirectory buffer-file-name))
  7086. "???"))
  7087. ((symbolp org-category) (symbol-name org-category))
  7088. (t org-category))))
  7089. (let ((category (catch 'buffer-category
  7090. (org-with-wide-buffer
  7091. (goto-char (point-max))
  7092. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7093. (let ((element (org-element-at-point-no-context)))
  7094. (when (eq (org-element-type element) 'keyword)
  7095. (throw 'buffer-category
  7096. (org-element-property :value element))))))
  7097. default-category)))
  7098. (with-silent-modifications
  7099. (org-with-wide-buffer
  7100. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7101. ;; keyword. If none is found, fall-back to `org-category' or
  7102. ;; buffer file name, or set it by the document property drawer.
  7103. (put-text-property (point-min) (point-max)
  7104. 'org-category category)
  7105. ;; Set categories from the document property drawer or
  7106. ;; property drawers in the outline. If category is found in
  7107. ;; the property drawer for the whole buffer that value
  7108. ;; overrides the keyword-based value set above.
  7109. (goto-char (point-min))
  7110. (let ((regexp (org-re-property "CATEGORY")))
  7111. (while (re-search-forward regexp nil t)
  7112. (let ((value (match-string-no-properties 3)))
  7113. (when (org-at-property-p)
  7114. (put-text-property
  7115. (save-excursion (org-back-to-heading-or-point-min t))
  7116. (save-excursion (if (org-before-first-heading-p)
  7117. (point-max)
  7118. (org-end-of-subtree t t)))
  7119. 'org-category
  7120. value)))))))))))
  7121. (defun org-refresh-stats-properties ()
  7122. "Refresh stats text properties in the buffer."
  7123. (with-silent-modifications
  7124. (org-with-point-at 1
  7125. (let ((regexp (concat org-outline-regexp-bol
  7126. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7127. (while (re-search-forward regexp nil t)
  7128. (let* ((numerator (string-to-number (match-string 1)))
  7129. (denominator (and (match-end 2)
  7130. (string-to-number (match-string 2))))
  7131. (stats (cond ((not denominator) numerator) ;percent
  7132. ((= denominator 0) 0)
  7133. (t (/ (* numerator 100) denominator)))))
  7134. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7135. 'org-stats stats)))))))
  7136. (defun org-refresh-effort-properties ()
  7137. "Refresh effort properties."
  7138. (org-refresh-properties
  7139. org-effort-property
  7140. '((effort . identity)
  7141. (effort-minutes . org-duration-to-minutes))))
  7142. (defun org-find-file-at-mouse (ev)
  7143. "Open file link or URL at mouse."
  7144. (interactive "e")
  7145. (mouse-set-point ev)
  7146. (org-open-at-point 'in-emacs))
  7147. (defun org-open-at-mouse (ev)
  7148. "Open file link or URL at mouse.
  7149. See the docstring of `org-open-file' for details."
  7150. (interactive "e")
  7151. (mouse-set-point ev)
  7152. (when (eq major-mode 'org-agenda-mode)
  7153. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7154. (org-open-at-point))
  7155. (defvar org-window-config-before-follow-link nil
  7156. "The window configuration before following a link.
  7157. This is saved in case the need arises to restore it.")
  7158. (defun org--file-default-apps ()
  7159. "Return the default applications for this operating system."
  7160. (pcase system-type
  7161. (`darwin org-file-apps-macos)
  7162. (`windows-nt org-file-apps-windowsnt)
  7163. (_ org-file-apps-gnu)))
  7164. (defun org--file-apps-entry-locator-p (entry)
  7165. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7166. It assumes that is the case when the entry uses a regular
  7167. expression which has at least one grouping construct and the
  7168. action is either a Lisp form or a command string containing
  7169. \"%1\", i.e., using at least one subexpression match as
  7170. a parameter."
  7171. (pcase entry
  7172. (`(,selector . ,action)
  7173. (and (stringp selector)
  7174. (> (regexp-opt-depth selector) 0)
  7175. (or (and (stringp action)
  7176. (string-match "%[0-9]" action))
  7177. (functionp action))))
  7178. (_ nil)))
  7179. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7180. "Convert extensions to regular expressions in the cars of LIST.
  7181. Also, weed out any non-string entries, because the return value
  7182. is used only for regexp matching.
  7183. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7184. point to the symbol `emacs', indicating that the file should be
  7185. opened in Emacs."
  7186. (append
  7187. (delq nil
  7188. (mapcar (lambda (x)
  7189. (unless (not (stringp (car x)))
  7190. (if (string-match "\\W" (car x))
  7191. x
  7192. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7193. list))
  7194. (when add-auto-mode
  7195. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7196. (defun org--open-file-format-command
  7197. (mailcap-command file link match-data)
  7198. "Format MAILCAP-COMMAND to launch viewer for the FILE.
  7199. MAILCAP-COMMAND may be an entry from the `org-file-apps' list or viewer
  7200. field from mailcap file loaded to `mailcap-mime-data'. See \"RFC
  7201. 1524. A User Agent Configuration Mechanism For Multimedia Mail Format
  7202. Information\" (URL `https://www.rfc-editor.org/rfc/rfc1524.html') for
  7203. details, man page `mailcap(5)' for brief summary, and Info node
  7204. `(emacs-mime) mailcap' for specific related to Emacs. Only a part of
  7205. mailcap specification is supported.
  7206. The following substitutions are interpolated in the MAILCAP-COMMAND
  7207. string:
  7208. - \"%s\" to FILE name passed through
  7209. `convert-standard-filename', so it must be absolute path.
  7210. - \"%1\" to \"%9\" groups from MATCH-DATA found in the LINK string by
  7211. the regular expression in the key part of the `org-file-apps' entry.
  7212. (performed by caller). Not recommended, consider a lisp function
  7213. instead of a shell command. For example, the following link in an
  7214. Org file
  7215. <file:///usr/share/doc/bash/bashref.pdf::#Redirections::allocate a file>
  7216. may be handled by an `org-file-apps' entry like
  7217. (\"\\\\.pdf\\\\(?:\\\\.[gx]z\\\\|\\\\.bz2\\\\)?::\\\\(#[^:]+\\\\)::\\\\(.+\\\\)\\\\\\='\"
  7218. . \"okular --find %2 %s%1\")
  7219. Use backslash \"\\\" to quote percent \"%\" or any other character
  7220. including backslash itself.
  7221. In addition, each argument is passed through `shell-quote-argument',
  7222. so quotes around substitutions should not be used. For compliance
  7223. with mailcap files shipped e.g. in Debian GNU/Linux, single or double
  7224. quotes around substitutions are stripped. It deviates from mailcap
  7225. specification that requires file name to be safe for shell and for the
  7226. application."
  7227. (let ((spec (list (cons ?s (convert-standard-filename file))))
  7228. (ngroups (min 9 (- (/ (length match-data) 2) 1))))
  7229. (when (> ngroups 0)
  7230. (set-match-data match-data)
  7231. (dolist (i (number-sequence 1 ngroups))
  7232. (push (cons (+ ?0 i) (match-string-no-properties i link)) spec)))
  7233. (replace-regexp-in-string
  7234. (rx (or (and "\\" (or (group anything) string-end))
  7235. (and (optional (group (any "'\"")))
  7236. "%"
  7237. (or (group anything) string-end)
  7238. (optional (group (backref 2))))))
  7239. (lambda (fmt)
  7240. (let* ((backslash (match-string-no-properties 1 fmt))
  7241. (key (match-string 3 fmt))
  7242. (value (and key (alist-get (string-to-char key) spec))))
  7243. (cond
  7244. (backslash)
  7245. (value (let ((quot (match-string 2 fmt))
  7246. (subst (shell-quote-argument value)))
  7247. ;; Remove quotes around the file name - we use
  7248. ;; `shell-quote-argument'.
  7249. (if (match-string 4 fmt)
  7250. subst
  7251. (concat quot subst))))
  7252. (t (error "Invalid format `%s'" fmt)))))
  7253. mailcap-command nil 'literal)))
  7254. ;;;###autoload
  7255. (defun org-open-file (path &optional in-emacs line search)
  7256. "Open the file at PATH.
  7257. First, this expands any special file name abbreviations. Then the
  7258. configuration variable `org-file-apps' is checked if it contains an
  7259. entry for this file type, and if yes, the corresponding command is launched.
  7260. If no application is found, Emacs simply visits the file.
  7261. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7262. With a double \\[universal-argument] \\[universal-argument] \
  7263. prefix arg, Org tries to avoid opening in Emacs
  7264. and to use an external application to visit the file.
  7265. Optional LINE specifies a line to go to, optional SEARCH a string
  7266. to search for. If LINE or SEARCH is given, the file will be
  7267. opened in Emacs, unless an entry from `org-file-apps' that makes
  7268. use of groups in a regexp matches.
  7269. If you want to change the way frames are used when following a
  7270. link, please customize `org-link-frame-setup'.
  7271. If the file does not exist, throw an error."
  7272. (let* ((file (if (equal path "") buffer-file-name
  7273. (substitute-in-file-name (expand-file-name path))))
  7274. (file-apps (append org-file-apps (org--file-default-apps)))
  7275. (apps (cl-remove-if #'org--file-apps-entry-locator-p file-apps))
  7276. (apps-locator (cl-remove-if-not #'org--file-apps-entry-locator-p
  7277. file-apps))
  7278. (remp (and (assq 'remote apps) (file-remote-p file)))
  7279. (dirp (unless remp (file-directory-p file)))
  7280. (file (if (and dirp org-open-directory-means-index-dot-org)
  7281. (concat (file-name-as-directory file) "index.org")
  7282. file))
  7283. (a-m-a-p (assq 'auto-mode apps))
  7284. (dfile (downcase file))
  7285. ;; Reconstruct the original link from the PATH, LINE and
  7286. ;; SEARCH args.
  7287. (link (cond (line (concat file "::" (number-to-string line)))
  7288. (search (concat file "::" search))
  7289. (t file)))
  7290. (ext
  7291. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7292. (match-string 1 dfile)))
  7293. (save-position-maybe
  7294. (let ((old-buffer (current-buffer))
  7295. (old-pos (point))
  7296. (old-mode major-mode))
  7297. (lambda ()
  7298. (and (derived-mode-p 'org-mode)
  7299. (eq old-mode 'org-mode)
  7300. (or (not (eq old-buffer (current-buffer)))
  7301. (not (eq old-pos (point))))
  7302. (org-mark-ring-push old-pos old-buffer)))))
  7303. cmd link-match-data)
  7304. (cond
  7305. ((member in-emacs '((16) system))
  7306. (setq cmd (cdr (assq 'system apps))))
  7307. (in-emacs (setq cmd 'emacs))
  7308. (t
  7309. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7310. (and dirp (cdr (assq 'directory apps)))
  7311. ;; First, try matching against apps-locator if we
  7312. ;; get a match here, store the match data for
  7313. ;; later.
  7314. (let* ((case-fold-search t)
  7315. (match (assoc-default link apps-locator
  7316. 'string-match)))
  7317. (if match
  7318. (progn (setq link-match-data (match-data))
  7319. match)
  7320. (progn (setq in-emacs (or in-emacs line search))
  7321. nil))) ; if we have no match in apps-locator,
  7322. ; always open the file in emacs if line or search
  7323. ; is given (for backwards compatibility)
  7324. (assoc-default dfile
  7325. (org--file-apps-regexp-alist apps a-m-a-p)
  7326. 'string-match)
  7327. (cdr (assoc ext apps))
  7328. (cdr (assq t apps))))))
  7329. (when (eq cmd 'system)
  7330. (setq cmd (cdr (assq 'system apps))))
  7331. (when (eq cmd 'default)
  7332. (setq cmd (cdr (assoc t apps))))
  7333. (when (eq cmd 'mailcap)
  7334. (require 'mailcap)
  7335. (mailcap-parse-mailcaps)
  7336. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7337. (command (mailcap-mime-info mime-type)))
  7338. (if (stringp command)
  7339. (setq cmd command)
  7340. (setq cmd 'emacs))))
  7341. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7342. (not (file-exists-p file))
  7343. (not org-open-non-existing-files))
  7344. (user-error "No such file: %s" file))
  7345. (cond
  7346. ((org-string-nw-p cmd)
  7347. (setq cmd (org--open-file-format-command cmd file link link-match-data))
  7348. (save-window-excursion
  7349. (message "Running %s...done" cmd)
  7350. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7351. ;; and exit immediately. Use pipe connection type instead of pty to
  7352. ;; avoid killing children processes with SIGHUP when temporary terminal
  7353. ;; session is finished.
  7354. ;;
  7355. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7356. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7357. ;; error messages.
  7358. (let ((process-connection-type nil))
  7359. (start-process-shell-command cmd nil cmd))
  7360. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7361. ((or (stringp cmd)
  7362. (eq cmd 'emacs))
  7363. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7364. (widen)
  7365. (cond (line (org-goto-line line)
  7366. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7367. (search (condition-case err
  7368. (org-link-search search)
  7369. ;; Save position before error-ing out so user
  7370. ;; can easily move back to the original buffer.
  7371. (error (funcall save-position-maybe)
  7372. (error (nth 1 err)))))))
  7373. ((functionp cmd)
  7374. (save-match-data
  7375. (set-match-data link-match-data)
  7376. (condition-case nil
  7377. (funcall cmd file link)
  7378. ;; FIXME: Remove this check when most default installations
  7379. ;; of Emacs have at least Org 9.0.
  7380. ((debug wrong-number-of-arguments wrong-type-argument
  7381. invalid-function)
  7382. (user-error "Please see Org News for version 9.0 about \
  7383. `org-file-apps'--Lisp error: %S" cmd)))))
  7384. ((consp cmd)
  7385. ;; FIXME: Remove this check when most default installations of
  7386. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7387. ;; fall back to `org-link-frame-setup' for an old usage of
  7388. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7389. (user-error "Please see Org News for version 9.0 about \
  7390. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7391. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7392. (funcall save-position-maybe)))
  7393. ;;;###autoload
  7394. (defun org-open-at-point-global ()
  7395. "Follow a link or a time-stamp like Org mode does.
  7396. Also follow links and emails as seen by `thing-at-point'.
  7397. This command can be called in any mode to follow an external
  7398. link or a time-stamp that has Org mode syntax. Its behavior
  7399. is undefined when called on internal links like fuzzy links.
  7400. Raise a user error when there is nothing to follow."
  7401. (interactive)
  7402. (let ((tap-url (thing-at-point 'url))
  7403. (tap-email (thing-at-point 'email)))
  7404. (cond ((org-in-regexp org-link-any-re)
  7405. (org-link-open-from-string (match-string-no-properties 0)))
  7406. ((or (org-in-regexp org-ts-regexp-both nil t)
  7407. (org-in-regexp org-tsr-regexp-both nil t))
  7408. (org-follow-timestamp-link))
  7409. (tap-url (org-link-open-from-string tap-url))
  7410. (tap-email (org-link-open-from-string
  7411. (concat "mailto:" tap-email)))
  7412. (t (user-error "No link found")))))
  7413. (defvar org-open-at-point-functions nil
  7414. "Hook that is run when following a link at point.
  7415. Functions in this hook must return t if they identify and follow
  7416. a link at point. If they don't find anything interesting at point,
  7417. they must return nil.")
  7418. (defun org-open-at-point (&optional arg)
  7419. "Open thing at point.
  7420. The thing can be a link, citation, timestamp, footnote, src-block or
  7421. tags.
  7422. When point is on a link, follow it. Normally, files will be
  7423. opened by an appropriate application. If the optional prefix
  7424. argument ARG is non-nil, Emacs will visit the file. With
  7425. a double prefix argument, try to open outside of Emacs, in the
  7426. application the system uses for this file type.
  7427. When point is on a timestamp, open the agenda at the day
  7428. specified.
  7429. When point is a footnote definition, move to the first reference
  7430. found. If it is on a reference, move to the associated
  7431. definition.
  7432. When point is on a src-block of inline src-block, open its result.
  7433. When point is on a citation, follow it.
  7434. When point is on a headline, display a list of every link in the
  7435. entry, so it is possible to pick one, or all, of them. If point
  7436. is on a tag, call `org-tags-view' instead.
  7437. On top of syntactically correct links, this function also tries
  7438. to open links and time-stamps in comments, node properties, and
  7439. keywords if point is on something looking like a timestamp or
  7440. a link."
  7441. (interactive "P")
  7442. (org-load-modules-maybe)
  7443. (setq org-window-config-before-follow-link (current-window-configuration))
  7444. (org-remove-occur-highlights nil nil t)
  7445. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7446. (let* ((context
  7447. ;; Only consider supported types, even if they are not the
  7448. ;; closest one.
  7449. (org-element-lineage
  7450. (org-element-context)
  7451. '(citation citation-reference clock comment comment-block
  7452. footnote-definition footnote-reference headline
  7453. inline-src-block inlinetask keyword link node-property
  7454. planning src-block timestamp)
  7455. t))
  7456. (type (org-element-type context))
  7457. (value (org-element-property :value context)))
  7458. (cond
  7459. ((not type) (user-error "No link found"))
  7460. ;; No valid link at point. For convenience, look if something
  7461. ;; looks like a link under point in some specific places.
  7462. ((memq type '(comment comment-block node-property keyword))
  7463. (call-interactively #'org-open-at-point-global))
  7464. ;; On a headline or an inlinetask, but not on a timestamp,
  7465. ;; a link, a footnote reference or a citation.
  7466. ((memq type '(headline inlinetask))
  7467. (org-match-line org-complex-heading-regexp)
  7468. (let ((tags-beg (match-beginning 5))
  7469. (tags-end (match-end 5)))
  7470. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7471. ;; On tags.
  7472. (org-tags-view
  7473. arg
  7474. (save-excursion
  7475. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7476. (end-tag (search-forward ":" tags-end nil 2)))
  7477. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7478. ;; Not on tags.
  7479. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7480. (`(nil . ,_)
  7481. (require 'org-attach)
  7482. (when (org-attach-dir)
  7483. (message "Opening attachment")
  7484. (if (equal arg '(4))
  7485. (org-attach-reveal-in-emacs)
  7486. (org-attach-reveal))))
  7487. (`(,links . ,links-end)
  7488. (dolist (link (if (stringp links) (list links) links))
  7489. (search-forward link nil links-end)
  7490. (goto-char (match-beginning 0))
  7491. (org-open-at-point arg)))))))
  7492. ;; On a footnote reference or at definition's label.
  7493. ((or (eq type 'footnote-reference)
  7494. (and (eq type 'footnote-definition)
  7495. (save-excursion
  7496. ;; Do not validate action when point is on the
  7497. ;; spaces right after the footnote label, in order
  7498. ;; to be on par with behavior on links.
  7499. (skip-chars-forward " \t")
  7500. (let ((begin
  7501. (org-element-property :contents-begin context)))
  7502. (if begin (< (point) begin)
  7503. (= (org-element-property :post-affiliated context)
  7504. (line-beginning-position)))))))
  7505. (org-footnote-action))
  7506. ;; On a planning line. Check if we are really on a timestamp.
  7507. ((and (eq type 'planning)
  7508. (org-in-regexp org-ts-regexp-both nil t))
  7509. (org-follow-timestamp-link))
  7510. ;; On a clock line, make sure point is on the timestamp
  7511. ;; before opening it.
  7512. ((and (eq type 'clock)
  7513. value
  7514. (>= (point) (org-element-property :begin value))
  7515. (<= (point) (org-element-property :end value)))
  7516. (org-follow-timestamp-link))
  7517. ((eq type 'src-block) (org-babel-open-src-block-result))
  7518. ;; Do nothing on white spaces after an object.
  7519. ((>= (point)
  7520. (save-excursion
  7521. (goto-char (org-element-property :end context))
  7522. (skip-chars-backward " \t")
  7523. (point)))
  7524. (user-error "No link found"))
  7525. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7526. ((eq type 'timestamp) (org-follow-timestamp-link))
  7527. ((eq type 'link) (org-link-open context arg))
  7528. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7529. (t (user-error "No link found")))))
  7530. (run-hook-with-args 'org-follow-link-hook))
  7531. ;;;###autoload
  7532. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7533. "Offer links in the current entry and return the selected link.
  7534. If there is only one link, return it.
  7535. If NTH is an integer, return the NTH link found.
  7536. If ZERO is a string, check also this string for a link, and if
  7537. there is one, return it."
  7538. (with-current-buffer buffer
  7539. (org-with-wide-buffer
  7540. (goto-char marker)
  7541. (let ((cnt ?0)
  7542. have-zero end links link c)
  7543. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7544. (push (match-string 0 zero) links)
  7545. (setq cnt (1- cnt) have-zero t))
  7546. (save-excursion
  7547. (org-back-to-heading t)
  7548. (setq end (save-excursion (outline-next-heading) (point)))
  7549. (while (re-search-forward org-link-any-re end t)
  7550. ;; Only consider valid links or links openable via
  7551. ;; `org-open-at-point'.
  7552. (when (memq (org-element-type (org-element-context)) '(link comment comment-block node-property keyword))
  7553. (push (match-string 0) links)))
  7554. (setq links (org-uniquify (reverse links))))
  7555. (cond
  7556. ((null links)
  7557. (message "No links"))
  7558. ((equal (length links) 1)
  7559. (setq link (car links)))
  7560. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7561. (setq link (nth (if have-zero nth (1- nth)) links)))
  7562. (t ; we have to select a link
  7563. (save-excursion
  7564. (save-window-excursion
  7565. (delete-other-windows)
  7566. (with-output-to-temp-buffer "*Select Link*"
  7567. (dolist (l links)
  7568. (cond
  7569. ((not (string-match org-link-bracket-re l))
  7570. (princ (format "[%c] %s\n" (cl-incf cnt)
  7571. (org-unbracket-string "<" ">" l))))
  7572. ((match-end 2)
  7573. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7574. (match-string 2 l) (match-string 1 l))))
  7575. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7576. (match-string 1 l)))))))
  7577. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7578. (message "Select link to open, RET to open all:")
  7579. (setq c (read-char-exclusive))
  7580. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7581. (when (equal c ?q) (user-error "Abort"))
  7582. (if (equal c ?\C-m)
  7583. (setq link links)
  7584. (setq nth (- c ?0))
  7585. (when have-zero (setq nth (1+ nth)))
  7586. (unless (and (integerp nth) (>= (length links) nth))
  7587. (user-error "Invalid link selection"))
  7588. (setq link (nth (1- nth) links)))))
  7589. (cons link end)))))
  7590. ;;; File search
  7591. (defun org-do-occur (regexp &optional cleanup)
  7592. "Call the Emacs command `occur'.
  7593. If CLEANUP is non-nil, remove the printout of the regular expression
  7594. in the *Occur* buffer. This is useful if the regex is long and not useful
  7595. to read."
  7596. (occur regexp)
  7597. (when cleanup
  7598. (let ((cwin (selected-window)) win beg end)
  7599. (when (setq win (get-buffer-window "*Occur*"))
  7600. (select-window win))
  7601. (goto-char (point-min))
  7602. (when (re-search-forward "match[a-z]+" nil t)
  7603. (setq beg (match-end 0))
  7604. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7605. (setq end (1- (match-beginning 0)))))
  7606. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7607. (goto-char (point-min))
  7608. (select-window cwin))))
  7609. ;;; The Mark Ring
  7610. (defvar org-mark-ring nil
  7611. "Mark ring for positions before jumps in Org mode.")
  7612. (defvar org-mark-ring-last-goto nil
  7613. "Last position in the mark ring used to go back.")
  7614. ;; Fill and close the ring
  7615. (setq org-mark-ring nil)
  7616. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7617. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7618. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7619. org-mark-ring)
  7620. (defun org-mark-ring-push (&optional pos buffer)
  7621. "Put the current position into the mark ring and rotate it.
  7622. Also push position into the Emacs mark ring. If optional
  7623. argument POS and BUFFER are not nil, mark this location instead."
  7624. (interactive)
  7625. (let ((pos (or pos (point)))
  7626. (buffer (or buffer (current-buffer))))
  7627. (with-current-buffer buffer
  7628. (org-with-point-at pos (push-mark nil t)))
  7629. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7630. (move-marker (car org-mark-ring) pos buffer))
  7631. (message
  7632. (substitute-command-keys
  7633. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7634. (defun org-mark-ring-goto (&optional n)
  7635. "Jump to the previous position in the mark ring.
  7636. With prefix arg N, jump back that many stored positions. When
  7637. called several times in succession, walk through the entire ring.
  7638. Org mode commands jumping to a different position in the current file,
  7639. or to another Org file, automatically push the old position onto the ring."
  7640. (interactive "p")
  7641. (let (p m)
  7642. (if (eq last-command this-command)
  7643. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7644. (setq p org-mark-ring))
  7645. (setq org-mark-ring-last-goto p)
  7646. (setq m (car p))
  7647. (pop-to-buffer-same-window (marker-buffer m))
  7648. (goto-char m)
  7649. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7650. ;;; Following specific links
  7651. (defvar org-agenda-buffer-tmp-name)
  7652. (defvar org-agenda-start-on-weekday)
  7653. (defvar org-agenda-buffer-name)
  7654. (defun org-follow-timestamp-link ()
  7655. "Open an agenda view for the time-stamp date/range at point."
  7656. ;; Avoid changing the global value.
  7657. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7658. (cond
  7659. ((org-at-date-range-p t)
  7660. (let ((org-agenda-start-on-weekday)
  7661. (t1 (match-string 1))
  7662. (t2 (match-string 2)) tt1 tt2)
  7663. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7664. tt2 (time-to-days (org-time-string-to-time t2)))
  7665. (let ((org-agenda-buffer-tmp-name
  7666. (format "*Org Agenda(a:%s)"
  7667. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7668. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7669. ((org-at-timestamp-p 'lax)
  7670. (let ((org-agenda-buffer-tmp-name
  7671. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7672. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7673. (substring (match-string 1) 0 10)))
  7674. 1)))
  7675. (t (error "This should not happen")))))
  7676. ;;; Following file links
  7677. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7678. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7679. (declare-function mailcap-mime-info
  7680. "mailcap" (string &optional request no-decode))
  7681. (defvar org-wait nil)
  7682. ;;;; Refiling
  7683. (defun org-get-org-file ()
  7684. "Read a filename, with default directory `org-directory'."
  7685. (let ((default (or org-default-notes-file remember-data-file)))
  7686. (read-file-name (format "File name [%s]: " default)
  7687. (file-name-as-directory org-directory)
  7688. default)))
  7689. (defun org-notes-order-reversed-p ()
  7690. "Check if the current file should receive notes in reversed order."
  7691. (cond
  7692. ((not org-reverse-note-order) nil)
  7693. ((eq t org-reverse-note-order) t)
  7694. ((not (listp org-reverse-note-order)) nil)
  7695. (t (catch 'exit
  7696. (dolist (entry org-reverse-note-order)
  7697. (when (string-match (car entry) buffer-file-name)
  7698. (throw 'exit (cdr entry))))))))
  7699. (defvar org-agenda-new-buffers nil
  7700. "Buffers created to visit agenda files.")
  7701. (declare-function org-string-nw-p "org-macs" (s))
  7702. ;;;; Dynamic blocks
  7703. (defun org-find-dblock (name)
  7704. "Find the first dynamic block with name NAME in the buffer.
  7705. If not found, stay at current position and return nil."
  7706. (let ((case-fold-search t) pos)
  7707. (save-excursion
  7708. (goto-char (point-min))
  7709. (setq pos (and (re-search-forward
  7710. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7711. (match-beginning 0))))
  7712. (when pos (goto-char pos))
  7713. pos))
  7714. (defun org-create-dblock (plist)
  7715. "Create a dynamic block section, with parameters taken from PLIST.
  7716. PLIST must contain a :name entry which is used as the name of the block."
  7717. (when (string-match "\\S-" (buffer-substring (line-beginning-position) (line-end-position)))
  7718. (end-of-line 1)
  7719. (newline))
  7720. (let ((col (current-column))
  7721. (name (plist-get plist :name)))
  7722. (insert "#+BEGIN: " name)
  7723. (while plist
  7724. (if (eq (car plist) :name)
  7725. (setq plist (cddr plist))
  7726. (insert " " (prin1-to-string (pop plist)))))
  7727. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7728. (beginning-of-line -2)))
  7729. (defun org-prepare-dblock ()
  7730. "Prepare dynamic block for refresh.
  7731. This empties the block, puts the cursor at the insert position and returns
  7732. the property list including an extra property :name with the block name."
  7733. (unless (looking-at org-dblock-start-re)
  7734. (user-error "Not at a dynamic block"))
  7735. (let* ((begdel (1+ (match-end 0)))
  7736. (name (org-no-properties (match-string 1)))
  7737. (params (append (list :name name)
  7738. (read (concat "(" (match-string 3) ")")))))
  7739. (save-excursion
  7740. (beginning-of-line 1)
  7741. (skip-chars-forward " \t")
  7742. (setq params (plist-put params :indentation-column (current-column))))
  7743. (unless (re-search-forward org-dblock-end-re nil t)
  7744. (error "Dynamic block not terminated"))
  7745. (setq params
  7746. (append params
  7747. (list :content (buffer-substring
  7748. begdel (match-beginning 0)))))
  7749. (delete-region begdel (match-beginning 0))
  7750. (goto-char begdel)
  7751. (open-line 1)
  7752. params))
  7753. (defun org-map-dblocks (&optional command)
  7754. "Apply COMMAND to all dynamic blocks in the current buffer.
  7755. If COMMAND is not given, use `org-update-dblock'."
  7756. (let ((cmd (or command 'org-update-dblock)))
  7757. (save-excursion
  7758. (goto-char (point-min))
  7759. (while (re-search-forward org-dblock-start-re nil t)
  7760. (goto-char (match-beginning 0))
  7761. (save-excursion
  7762. (condition-case nil
  7763. (funcall cmd)
  7764. (error (message "Error during update of dynamic block"))))
  7765. (unless (re-search-forward org-dblock-end-re nil t)
  7766. (error "Dynamic block not terminated"))))))
  7767. (defvar org-dynamic-block-alist nil
  7768. "Alist defining all the Org dynamic blocks.
  7769. The key is the dynamic block type name, as a string. The value
  7770. is the function used to insert the dynamic block.
  7771. Use `org-dynamic-block-define' to populate it.")
  7772. (defun org-dynamic-block-function (type)
  7773. "Return function associated to a given dynamic block type.
  7774. TYPE is the dynamic block type, as a string."
  7775. (cdr (assoc type org-dynamic-block-alist)))
  7776. (defun org-dynamic-block-types ()
  7777. "List all defined dynamic block types."
  7778. (mapcar #'car org-dynamic-block-alist))
  7779. (defun org-dynamic-block-define (type func)
  7780. "Define dynamic block TYPE with FUNC.
  7781. TYPE is a string. FUNC is the function creating the dynamic
  7782. block of such type."
  7783. (pcase (assoc type org-dynamic-block-alist)
  7784. (`nil (push (cons type func) org-dynamic-block-alist))
  7785. (def (setcdr def func))))
  7786. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7787. "Insert a dynamic block of type TYPE.
  7788. When used interactively, select the dynamic block types among
  7789. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7790. is non-nil, call the dynamic block function interactively."
  7791. (interactive (list (completing-read "Dynamic block: "
  7792. (org-dynamic-block-types))
  7793. t))
  7794. (pcase (org-dynamic-block-function type)
  7795. (`nil (error "No such dynamic block: %S" type))
  7796. ((and f (pred functionp))
  7797. (if interactive-p (call-interactively f) (funcall f)))
  7798. (_ (error "Invalid function for dynamic block %S" type))))
  7799. (defun org-dblock-update (&optional arg)
  7800. "User command for updating dynamic blocks.
  7801. Update the dynamic block at point. With prefix ARG, update all dynamic
  7802. blocks in the buffer."
  7803. (interactive "P")
  7804. (if arg
  7805. (org-update-all-dblocks)
  7806. (or (looking-at org-dblock-start-re)
  7807. (org-beginning-of-dblock))
  7808. (org-update-dblock)))
  7809. (defun org-update-dblock ()
  7810. "Update the dynamic block at point.
  7811. This means to empty the block, parse for parameters and then call
  7812. the correct writing function."
  7813. (interactive)
  7814. (save-excursion
  7815. (let* ((win (selected-window))
  7816. (pos (point))
  7817. (line (org-current-line))
  7818. (params (org-prepare-dblock))
  7819. (name (plist-get params :name))
  7820. (indent (plist-get params :indentation-column))
  7821. (cmd (intern (concat "org-dblock-write:" name))))
  7822. (message "Updating dynamic block `%s' at line %d..." name line)
  7823. (funcall cmd params)
  7824. (message "Updating dynamic block `%s' at line %d...done" name line)
  7825. (goto-char pos)
  7826. (when (and indent (> indent 0))
  7827. (setq indent (make-string indent ?\ ))
  7828. (save-excursion
  7829. (select-window win)
  7830. (org-beginning-of-dblock)
  7831. (forward-line 1)
  7832. (while (not (looking-at org-dblock-end-re))
  7833. (insert indent)
  7834. (beginning-of-line 2))
  7835. (when (looking-at org-dblock-end-re)
  7836. (and (looking-at "[ \t]+")
  7837. (replace-match ""))
  7838. (insert indent)))))))
  7839. (defun org-beginning-of-dblock ()
  7840. "Find the beginning of the dynamic block at point.
  7841. Error if there is no such block at point."
  7842. (let ((pos (point))
  7843. beg)
  7844. (end-of-line 1)
  7845. (if (and (re-search-backward org-dblock-start-re nil t)
  7846. (setq beg (match-beginning 0))
  7847. (re-search-forward org-dblock-end-re nil t)
  7848. (> (match-end 0) pos))
  7849. (goto-char beg)
  7850. (goto-char pos)
  7851. (error "Not in a dynamic block"))))
  7852. (defun org-update-all-dblocks ()
  7853. "Update all dynamic blocks in the buffer.
  7854. This function can be used in a hook."
  7855. (interactive)
  7856. (when (derived-mode-p 'org-mode)
  7857. (org-map-dblocks 'org-update-dblock)))
  7858. ;;;; Completion
  7859. (declare-function org-export-backend-options "ox" (cl-x) t)
  7860. (defun org-get-export-keywords ()
  7861. "Return a list of all currently understood export keywords.
  7862. Export keywords include options, block names, attributes and
  7863. keywords relative to each registered export back-end."
  7864. (let (keywords)
  7865. (dolist (backend
  7866. (bound-and-true-p org-export-registered-backends)
  7867. (delq nil keywords))
  7868. ;; Back-end name (for keywords, like #+LATEX:)
  7869. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7870. (dolist (option-entry (org-export-backend-options backend))
  7871. ;; Back-end options.
  7872. (push (nth 1 option-entry) keywords)))))
  7873. (defconst org-options-keywords
  7874. '("ARCHIVE:" "AUTHOR:" "BIBLIOGRAPHY:" "BIND:" "CATEGORY:" "CITE_EXPORT:"
  7875. "COLUMNS:" "CREATOR:" "DATE:" "DESCRIPTION:" "DRAWERS:" "EMAIL:"
  7876. "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" "INDEX:" "KEYWORDS:" "LANGUAGE:"
  7877. "MACRO:" "OPTIONS:" "PROPERTY:" "PRINT_BIBLIOGRAPHY" "PRIORITIES:"
  7878. "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" "TITLE:" "TODO:"
  7879. "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7880. (defcustom org-structure-template-alist
  7881. '(("a" . "export ascii")
  7882. ("c" . "center")
  7883. ("C" . "comment")
  7884. ("e" . "example")
  7885. ("E" . "export")
  7886. ("h" . "export html")
  7887. ("l" . "export latex")
  7888. ("q" . "quote")
  7889. ("s" . "src")
  7890. ("v" . "verse"))
  7891. "An alist of keys and block types.
  7892. `org-insert-structure-template' will display a menu with this list of
  7893. templates to choose from. The block type is inserted, with
  7894. \"#+begin_\" and \"#+end_\" added automatically. If the block type
  7895. consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
  7896. added instead.
  7897. The menu keys are defined by the car of each entry in this alist.
  7898. If two entries have the keys \"a\" and \"aa\" respectively, the
  7899. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7900. latter will be inserted by typing \"aa\". If an entry with the
  7901. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7902. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7903. block can be inserted by pressing TAB after the string \"<KEY\"."
  7904. :group 'org-edit-structure
  7905. :type '(repeat
  7906. (cons (string :tag "Key")
  7907. (string :tag "Template")))
  7908. :package-version '(Org . "9.2"))
  7909. (defun org--check-org-structure-template-alist (&optional checklist)
  7910. "Check whether `org-structure-template-alist' is set up correctly.
  7911. In particular, check if the Org 9.2 format is used as opposed to
  7912. previous format."
  7913. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7914. (or (symbol-value checklist)
  7915. org-structure-template-alist))))
  7916. (when elm
  7917. (org-display-warning
  7918. (format "
  7919. Please update the entries of `%s'.
  7920. In Org 9.2 the format was changed from something like
  7921. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7922. to something like
  7923. (\"s\" . \"src\")
  7924. Please refer to the documentation of `org-structure-template-alist'.
  7925. The following entries must be updated:
  7926. %s"
  7927. (or checklist 'org-structure-template-alist)
  7928. (pp-to-string elm))))))
  7929. (defun org--insert-structure-template-mks ()
  7930. "Present `org-structure-template-alist' with `org-mks'.
  7931. Menus are added if keys require more than one keystroke. Tabs
  7932. are added to single key entries when more than one stroke is
  7933. needed. Keys longer than two characters are reduced to two
  7934. characters."
  7935. (org--check-org-structure-template-alist)
  7936. (let* (case-fold-search
  7937. (templates (append org-structure-template-alist
  7938. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7939. (keys (mapcar #'car templates))
  7940. (start-letters
  7941. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7942. ;; Sort each element of `org-structure-template-alist' into
  7943. ;; sublists according to the first letter.
  7944. (superlist
  7945. (mapcar (lambda (letter)
  7946. (list letter
  7947. (cl-remove-if-not
  7948. (apply-partially #'string-match-p (concat "^" letter))
  7949. templates :key #'car)))
  7950. start-letters)))
  7951. (org-mks
  7952. (apply #'append
  7953. ;; Make an `org-mks' table. If only one element is
  7954. ;; present in a sublist, make it part of the top-menu,
  7955. ;; otherwise make a submenu according to the starting
  7956. ;; letter and populate it.
  7957. (mapcar (lambda (sublist)
  7958. (if (eq 1 (length (cadr sublist)))
  7959. (mapcar (lambda (elm)
  7960. (list (substring (car elm) 0 1)
  7961. (cdr elm) ""))
  7962. (cadr sublist))
  7963. ;; Create submenu.
  7964. (let* ((topkey (car sublist))
  7965. (elms (cadr sublist))
  7966. (keys (mapcar #'car elms))
  7967. (long (> (length elms) 3)))
  7968. (append
  7969. (list
  7970. ;; Make a description of the submenu.
  7971. (list topkey
  7972. (concat
  7973. (mapconcat #'cdr
  7974. (cl-subseq elms 0 (if long 3 (length elms)))
  7975. ", ")
  7976. (when long ", ..."))))
  7977. ;; List of entries in submenu.
  7978. (cl-mapcar #'list
  7979. (org--insert-structure-template-unique-keys keys)
  7980. (mapcar #'cdr elms)
  7981. (make-list (length elms) ""))))))
  7982. superlist))
  7983. "Select a key\n============"
  7984. "Key: ")))
  7985. (defun org--insert-structure-template-unique-keys (keys)
  7986. "Make a list of unique, two characters long elements from KEYS.
  7987. Elements of length one have a tab appended. Elements of length
  7988. two are kept as is. Longer elements are truncated to length two.
  7989. If an element cannot be made unique, an error is raised."
  7990. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7991. menu-keys)
  7992. (dolist (key ordered-keys)
  7993. (let ((potential-key
  7994. (cl-case (length key)
  7995. (1 (concat key "\t"))
  7996. (2 key)
  7997. (otherwise
  7998. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  7999. (mapcar (apply-partially #'concat (substring key 0 1))
  8000. (split-string (substring key 1) "" t)))))))
  8001. (if (or (not potential-key) (assoc potential-key menu-keys))
  8002. (user-error "Could not make unique key for `%s'" key)
  8003. (push (cons potential-key key) menu-keys))))
  8004. (mapcar #'car
  8005. (cl-sort menu-keys #'<
  8006. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8007. (defun org-insert-structure-template (type)
  8008. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8009. Select a block from `org-structure-template-alist' then type
  8010. either RET, TAB or SPC to write the block type. With an active
  8011. region, wrap the region in the block. Otherwise, insert an empty
  8012. block.
  8013. When foo is written as FOO, upcase the #+BEGIN/END as well."
  8014. (interactive
  8015. (list (pcase (org--insert-structure-template-mks)
  8016. (`("\t" . ,_) (read-string "Structure type: "))
  8017. (`(,_ ,choice . ,_) choice))))
  8018. (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
  8019. (region? (use-region-p))
  8020. (region-start (and region? (region-beginning)))
  8021. (region-end (and region? (copy-marker (region-end))))
  8022. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8023. (verbatim? (string-match-p
  8024. (concat "\\`" (regexp-opt '("example" "export"
  8025. "src" "comment")))
  8026. type))
  8027. (upcase? (string= (car (split-string type))
  8028. (upcase (car (split-string type))))))
  8029. (when region? (goto-char region-start))
  8030. (let ((column (current-indentation)))
  8031. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8032. (beginning-of-line)
  8033. (insert "\n"))
  8034. (save-excursion
  8035. (indent-to column)
  8036. (insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
  8037. (when region?
  8038. (when verbatim? (org-escape-code-in-region (point) region-end))
  8039. (goto-char region-end)
  8040. ;; Ignore empty lines at the end of the region.
  8041. (skip-chars-backward " \r\t\n")
  8042. (end-of-line))
  8043. (unless (bolp) (insert "\n"))
  8044. (indent-to column)
  8045. (insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
  8046. (if (looking-at "[ \t]*$") (replace-match "")
  8047. (insert "\n"))
  8048. (when (and (eobp) (not (bolp))) (insert "\n")))
  8049. (if extended? (end-of-line)
  8050. (forward-line)
  8051. (skip-chars-forward " \t")))))
  8052. ;;;; TODO, DEADLINE, Comments
  8053. (defun org-toggle-comment ()
  8054. "Change the COMMENT state of an entry."
  8055. (interactive)
  8056. (save-excursion
  8057. (org-back-to-heading)
  8058. (let ((case-fold-search nil))
  8059. (looking-at org-complex-heading-regexp))
  8060. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8061. (skip-chars-forward " \t")
  8062. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8063. (if (org-in-commented-heading-p t)
  8064. (delete-region (point)
  8065. (progn (search-forward " " (line-end-position) 'move)
  8066. (skip-chars-forward " \t")
  8067. (point)))
  8068. (insert org-comment-string)
  8069. (unless (eolp) (insert " ")))))
  8070. (defvar org-last-todo-state-is-todo nil
  8071. "This is non-nil when the last TODO state change led to a TODO state.
  8072. If the last change removed the TODO tag or switched to DONE, then
  8073. this is nil.")
  8074. (defvar org-todo-setup-filter-hook nil
  8075. "Hook for functions that pre-filter todo specs.
  8076. Each function takes a todo spec and returns either nil or the spec
  8077. transformed into canonical form." )
  8078. (defvar org-todo-get-default-hook nil
  8079. "Hook for functions that get a default item for todo.
  8080. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8081. nil or a string to be used for the todo mark." )
  8082. (defvar org-agenda-headline-snapshot-before-repeat)
  8083. (defun org-current-effective-time ()
  8084. "Return current time adjusted for `org-extend-today-until' variable."
  8085. (let* ((ct (org-current-time))
  8086. (dct (decode-time ct))
  8087. (ct1
  8088. (cond
  8089. (org-use-last-clock-out-time-as-effective-time
  8090. (or (org-clock-get-last-clock-out-time) ct))
  8091. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8092. (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8093. (t ct))))
  8094. ct1))
  8095. (defun org-todo-yesterday (&optional arg)
  8096. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8097. (interactive "P")
  8098. (if (eq major-mode 'org-agenda-mode)
  8099. (org-agenda-todo-yesterday arg)
  8100. (let* ((org-use-effective-time t)
  8101. (hour (nth 2 (decode-time (org-current-time))))
  8102. (org-extend-today-until (1+ hour)))
  8103. (org-todo arg))))
  8104. (defvar org-block-entry-blocking ""
  8105. "First entry preventing the TODO state change.")
  8106. (defun org-cancel-repeater ()
  8107. "Cancel a repeater by setting its numeric value to zero."
  8108. (interactive)
  8109. (save-excursion
  8110. (org-back-to-heading t)
  8111. (let ((bound1 (point))
  8112. (bound0 (save-excursion (outline-next-heading) (point))))
  8113. (when (and (re-search-forward
  8114. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8115. org-deadline-time-regexp "\\)\\|\\("
  8116. org-ts-regexp "\\)")
  8117. bound0 t)
  8118. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8119. bound1 t))
  8120. (replace-match "0" t nil nil 1)))))
  8121. (defvar org-state)
  8122. (defvar org-blocked-by-checkboxes)
  8123. (defun org-todo (&optional arg)
  8124. "Change the TODO state of an item.
  8125. The state of an item is given by a keyword at the start of the heading,
  8126. like
  8127. *** TODO Write paper
  8128. *** DONE Call mom
  8129. The different keywords are specified in the variable `org-todo-keywords'.
  8130. By default the available states are \"TODO\" and \"DONE\". So, for this
  8131. example: when the item starts with TODO, it is changed to DONE.
  8132. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8133. DONE are present, add TODO at the beginning of the heading.
  8134. You can set up single-character keys to fast-select the new state. See the
  8135. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8136. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8137. and take a
  8138. logging note.
  8139. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8140. next set of TODO \
  8141. keywords (nextset).
  8142. Another way to achieve this is `S-C-<right>'.
  8143. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8144. prefix, circumvent any state blocking.
  8145. With numeric prefix arg, switch to the Nth state.
  8146. With a numeric prefix arg of 0, inhibit note taking for the change.
  8147. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8148. When called through ELisp, arg is also interpreted in the following way:
  8149. `none' -> empty state
  8150. \"\" -> switch to empty state
  8151. `done' -> switch to DONE
  8152. `nextset' -> switch to the next set of keywords
  8153. `previousset' -> switch to the previous set of keywords
  8154. \"WAITING\" -> switch to the specified keyword, but only if it
  8155. really is a member of `org-todo-keywords'."
  8156. (interactive "P")
  8157. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8158. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8159. 'region-start-level 'region))
  8160. org-loop-over-headlines-in-active-region)
  8161. (org-map-entries
  8162. (lambda () (org-todo arg))
  8163. nil cl
  8164. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8165. (when (equal arg '(16)) (setq arg 'nextset))
  8166. (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
  8167. (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
  8168. (let ((org-blocker-hook org-blocker-hook)
  8169. commentp
  8170. case-fold-search)
  8171. (when (equal arg '(64))
  8172. (setq arg nil org-blocker-hook nil))
  8173. (when (and org-blocker-hook
  8174. (or org-inhibit-blocking
  8175. (org-entry-get nil "NOBLOCKING")))
  8176. (setq org-blocker-hook nil))
  8177. (save-excursion
  8178. (catch 'exit
  8179. (org-back-to-heading t)
  8180. (when (org-in-commented-heading-p t)
  8181. (org-toggle-comment)
  8182. (setq commentp t))
  8183. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8184. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8185. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8186. (let* ((match-data (match-data))
  8187. (startpos (copy-marker (line-beginning-position)))
  8188. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8189. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8190. (org-log-done org-log-done)
  8191. (org-log-repeat org-log-repeat)
  8192. (org-todo-log-states org-todo-log-states)
  8193. (org-inhibit-logging
  8194. (if (equal arg 0)
  8195. (progn (setq arg nil) 'note) org-inhibit-logging))
  8196. (this (match-string 1))
  8197. (hl-pos (match-beginning 0))
  8198. (head (org-get-todo-sequence-head this))
  8199. (ass (assoc head org-todo-kwd-alist))
  8200. (interpret (nth 1 ass))
  8201. (done-word (nth 3 ass))
  8202. (final-done-word (nth 4 ass))
  8203. (org-last-state (or this ""))
  8204. (completion-ignore-case t)
  8205. (member (member this org-todo-keywords-1))
  8206. (tail (cdr member))
  8207. (org-state (cond
  8208. ((eq arg 'right)
  8209. ;; Next state
  8210. (if this
  8211. (if tail (car tail) nil)
  8212. (car org-todo-keywords-1)))
  8213. ((eq arg 'left)
  8214. ;; Previous state
  8215. (unless (equal member org-todo-keywords-1)
  8216. (if this
  8217. (nth (- (length org-todo-keywords-1)
  8218. (length tail) 2)
  8219. org-todo-keywords-1)
  8220. (org-last org-todo-keywords-1))))
  8221. (arg
  8222. ;; User or caller requests a specific state.
  8223. (cond
  8224. ((equal arg "") nil)
  8225. ((eq arg 'none) nil)
  8226. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8227. ((eq arg 'nextset)
  8228. (or (car (cdr (member head org-todo-heads)))
  8229. (car org-todo-heads)))
  8230. ((eq arg 'previousset)
  8231. (let ((org-todo-heads (reverse org-todo-heads)))
  8232. (or (car (cdr (member head org-todo-heads)))
  8233. (car org-todo-heads))))
  8234. ((car (member arg org-todo-keywords-1)))
  8235. ((stringp arg)
  8236. (user-error "State `%s' not valid in this file" arg))
  8237. ((nth (1- (prefix-numeric-value arg))
  8238. org-todo-keywords-1))))
  8239. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8240. ;; Use fast selection.
  8241. (org-fast-todo-selection this))
  8242. ((null member) (or head (car org-todo-keywords-1)))
  8243. ((equal this final-done-word) nil) ;-> make empty
  8244. ((null tail) nil) ;-> first entry
  8245. ((memq interpret '(type priority))
  8246. (if (eq this-command last-command)
  8247. (car tail)
  8248. (if (> (length tail) 0)
  8249. (or done-word (car org-done-keywords))
  8250. nil)))
  8251. (t
  8252. (car tail))))
  8253. (org-state (or
  8254. (run-hook-with-args-until-success
  8255. 'org-todo-get-default-hook org-state org-last-state)
  8256. org-state))
  8257. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8258. (change-plist (list :type 'todo-state-change :from this :to org-state
  8259. :position startpos))
  8260. dolog now-done-p)
  8261. (when org-blocker-hook
  8262. (let (org-blocked-by-checkboxes block-reason)
  8263. (setq org-last-todo-state-is-todo
  8264. (not (member this org-done-keywords)))
  8265. (unless (save-excursion
  8266. (save-match-data
  8267. (org-with-wide-buffer
  8268. (run-hook-with-args-until-failure
  8269. 'org-blocker-hook change-plist))))
  8270. (setq block-reason (if org-blocked-by-checkboxes
  8271. "contained checkboxes"
  8272. (format "\"%s\"" org-block-entry-blocking)))
  8273. (if (called-interactively-p 'interactive)
  8274. (user-error "TODO state change from %s to %s blocked (by %s)"
  8275. this org-state block-reason)
  8276. ;; Fail silently.
  8277. (message "TODO state change from %s to %s blocked (by %s)"
  8278. this org-state block-reason)
  8279. (throw 'exit nil)))))
  8280. (store-match-data match-data)
  8281. (org-fold-core-ignore-modifications
  8282. (goto-char (match-beginning 0))
  8283. (replace-match "")
  8284. ;; We need to use `insert-before-markers-and-inherit'
  8285. ;; because: (1) We want to preserve the folding state
  8286. ;; text properties; (2) We do not want to make point
  8287. ;; move before new todo state when inserting a new todo
  8288. ;; into an empty heading. In (2), the above
  8289. ;; `save-excursion' is relying on markers saved before.
  8290. (insert-before-markers-and-inherit next)
  8291. (unless (org-invisible-p (line-beginning-position))
  8292. (org-fold-region (line-beginning-position)
  8293. (line-end-position)
  8294. nil)))
  8295. (cond ((and org-state (equal this org-state))
  8296. (message "TODO state was already %s" (org-trim next)))
  8297. ((not (pos-visible-in-window-p hl-pos))
  8298. (message "TODO state changed to %s" (org-trim next))))
  8299. (unless head
  8300. (setq head (org-get-todo-sequence-head org-state)
  8301. ass (assoc head org-todo-kwd-alist)
  8302. interpret (nth 1 ass)
  8303. done-word (nth 3 ass)
  8304. final-done-word (nth 4 ass)))
  8305. (when (memq arg '(nextset previousset))
  8306. (message "Keyword-Set %d/%d: %s"
  8307. (- (length org-todo-sets) -1
  8308. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8309. (length org-todo-sets)
  8310. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8311. (setq org-last-todo-state-is-todo
  8312. (not (member org-state org-done-keywords)))
  8313. (setq now-done-p (and (member org-state org-done-keywords)
  8314. (not (member this org-done-keywords))))
  8315. (and logging (org-local-logging logging))
  8316. (when (or (and (or org-todo-log-states org-log-done)
  8317. (not (eq org-inhibit-logging t))
  8318. (not (memq arg '(nextset previousset))))
  8319. force-log)
  8320. ;; We need to look at recording a time and note.
  8321. (setq dolog (or (if force-log 'note)
  8322. (nth 1 (assoc org-state org-todo-log-states))
  8323. (nth 2 (assoc this org-todo-log-states))))
  8324. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8325. (setq dolog 'time))
  8326. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8327. (and org-state
  8328. (member org-state org-not-done-keywords)
  8329. (not (member this org-not-done-keywords))))
  8330. ;; This is now a todo state and was not one before
  8331. ;; If there was a CLOSED time stamp, get rid of it.
  8332. (org-add-planning-info nil nil 'closed))
  8333. (when (and now-done-p org-log-done)
  8334. ;; It is now done, and it was not done before.
  8335. (org-add-planning-info 'closed (org-current-effective-time))
  8336. (when (and (not dolog) (eq 'note org-log-done))
  8337. (org-add-log-setup 'done org-state this 'note)))
  8338. (when (and org-state dolog)
  8339. ;; This is a non-nil state, and we need to log it.
  8340. (org-add-log-setup 'state org-state this dolog)))
  8341. ;; Fixup tag positioning.
  8342. (org-todo-trigger-tag-changes org-state)
  8343. (when org-auto-align-tags (org-align-tags))
  8344. (when org-provide-todo-statistics
  8345. (org-update-parent-todo-statistics))
  8346. (when (bound-and-true-p org-clock-out-when-done)
  8347. (org-clock-out-if-current))
  8348. (run-hooks 'org-after-todo-state-change-hook)
  8349. (when (and arg (not (member org-state org-done-keywords)))
  8350. (setq head (org-get-todo-sequence-head org-state)))
  8351. (put-text-property (line-beginning-position) (line-end-position) 'org-todo-head head)
  8352. ;; Do we need to trigger a repeat?
  8353. (when now-done-p
  8354. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8355. ;; This is for the agenda, take a snapshot of the headline.
  8356. (save-match-data
  8357. (setq org-agenda-headline-snapshot-before-repeat
  8358. (org-get-heading))))
  8359. (org-auto-repeat-maybe org-state))
  8360. ;; Fixup cursor location if close to the keyword.
  8361. (when (and (outline-on-heading-p)
  8362. (not (bolp))
  8363. (save-excursion (beginning-of-line 1)
  8364. (looking-at org-todo-line-regexp))
  8365. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8366. (goto-char (or (match-end 2) (match-end 1)))
  8367. (and (looking-at " ")
  8368. (not (looking-at " *:"))
  8369. (just-one-space)))
  8370. (when org-trigger-hook
  8371. (save-excursion
  8372. (run-hook-with-args 'org-trigger-hook change-plist)))
  8373. (when commentp (org-toggle-comment))))))))
  8374. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8375. "Block turning an entry into a TODO, using the hierarchy.
  8376. This checks whether the current task should be blocked from state
  8377. changes. Such blocking occurs when:
  8378. 1. The task has children which are not all in a completed state.
  8379. 2. A task has a parent with the property :ORDERED:, and there
  8380. are siblings prior to the current task with incomplete
  8381. status.
  8382. 3. The parent of the task is blocked because it has siblings that should
  8383. be done first, or is child of a block grandparent TODO entry."
  8384. (if (not org-enforce-todo-dependencies)
  8385. t ; if locally turned off don't block
  8386. (catch 'dont-block
  8387. ;; If this is not a todo state change, or if this entry is already DONE,
  8388. ;; do not block
  8389. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8390. (member (plist-get change-plist :from)
  8391. (cons 'done org-done-keywords))
  8392. (member (plist-get change-plist :to)
  8393. (cons 'todo org-not-done-keywords))
  8394. (not (plist-get change-plist :to)))
  8395. (throw 'dont-block t))
  8396. ;; If this task has children, and any are undone, it's blocked
  8397. (save-excursion
  8398. (org-back-to-heading t)
  8399. (let ((this-level (funcall outline-level)))
  8400. (outline-next-heading)
  8401. (let ((child-level (funcall outline-level)))
  8402. (while (and (not (eobp))
  8403. (> child-level this-level))
  8404. ;; this todo has children, check whether they are all
  8405. ;; completed
  8406. (when (and (not (org-entry-is-done-p))
  8407. (org-entry-is-todo-p))
  8408. (setq org-block-entry-blocking (org-get-heading))
  8409. (throw 'dont-block nil))
  8410. (outline-next-heading)
  8411. (setq child-level (funcall outline-level))))))
  8412. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8413. ;; any previous siblings are undone, it's blocked
  8414. (save-excursion
  8415. (org-back-to-heading t)
  8416. (let* ((pos (point))
  8417. (parent-pos (and (org-up-heading-safe) (point)))
  8418. (case-fold-search nil))
  8419. (unless parent-pos (throw 'dont-block t)) ; no parent
  8420. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8421. (forward-line 1)
  8422. (re-search-forward org-not-done-heading-regexp pos t))
  8423. (setq org-block-entry-blocking (match-string 0))
  8424. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8425. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8426. (while t
  8427. (goto-char parent-pos)
  8428. (unless (looking-at org-not-done-heading-regexp)
  8429. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8430. (setq pos (point))
  8431. (setq parent-pos (and (org-up-heading-safe) (point)))
  8432. (unless parent-pos (throw 'dont-block t)) ; no parent
  8433. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8434. (forward-line 1)
  8435. (re-search-forward org-not-done-heading-regexp pos t)
  8436. (setq org-block-entry-blocking (org-get-heading)))
  8437. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8438. (defcustom org-track-ordered-property-with-tag nil
  8439. "Should the ORDERED property also be shown as a tag?
  8440. The ORDERED property decides if an entry should require subtasks to be
  8441. completed in sequence. Since a property is not very visible, setting
  8442. this option means that toggling the ORDERED property with the command
  8443. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8444. not relevant for the behavior, but it makes things more visible.
  8445. Note that toggling the tag with tags commands will not change the property
  8446. and therefore not influence behavior!
  8447. This can be t, meaning the tag ORDERED should be used. It can also be a
  8448. string to select a different tag for this task."
  8449. :group 'org-todo
  8450. :type '(choice
  8451. (const :tag "No tracking" nil)
  8452. (const :tag "Track with ORDERED tag" t)
  8453. (string :tag "Use other tag")))
  8454. (defun org-toggle-ordered-property ()
  8455. "Toggle the ORDERED property of the current entry.
  8456. For better visibility, you can track the value of this property with a tag.
  8457. See variable `org-track-ordered-property-with-tag'."
  8458. (interactive)
  8459. (let* ((t1 org-track-ordered-property-with-tag)
  8460. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8461. (save-excursion
  8462. (org-back-to-heading)
  8463. (if (org-entry-get nil "ORDERED")
  8464. (progn
  8465. (org-delete-property "ORDERED")
  8466. (and tag (org-toggle-tag tag 'off))
  8467. (message "Subtasks can be completed in arbitrary order"))
  8468. (org-entry-put nil "ORDERED" "t")
  8469. (and tag (org-toggle-tag tag 'on))
  8470. (message "Subtasks must be completed in sequence")))))
  8471. (defun org-block-todo-from-checkboxes (change-plist)
  8472. "Block turning an entry into a TODO, using checkboxes.
  8473. This checks whether the current task should be blocked from state
  8474. changes because there are unchecked boxes in this entry."
  8475. (if (not org-enforce-todo-checkbox-dependencies)
  8476. t ; if locally turned off don't block
  8477. (catch 'dont-block
  8478. ;; If this is not a todo state change, or if this entry is already DONE,
  8479. ;; do not block
  8480. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8481. (member (plist-get change-plist :from)
  8482. (cons 'done org-done-keywords))
  8483. (member (plist-get change-plist :to)
  8484. (cons 'todo org-not-done-keywords))
  8485. (not (plist-get change-plist :to)))
  8486. (throw 'dont-block t))
  8487. ;; If this task has checkboxes that are not checked, it's blocked
  8488. (save-excursion
  8489. (org-back-to-heading t)
  8490. (let ((beg (point)) end)
  8491. (outline-next-heading)
  8492. (setq end (point))
  8493. (goto-char beg)
  8494. (when (org-list-search-forward
  8495. (concat (org-item-beginning-re)
  8496. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8497. "\\[[- ]\\]")
  8498. end t)
  8499. (when (boundp 'org-blocked-by-checkboxes)
  8500. (setq org-blocked-by-checkboxes t))
  8501. (throw 'dont-block nil))))
  8502. t))) ; do not block
  8503. (defun org-entry-blocked-p ()
  8504. "Non-nil if entry at point is blocked."
  8505. (and (not (org-entry-get nil "NOBLOCKING"))
  8506. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8507. (not (run-hook-with-args-until-failure
  8508. 'org-blocker-hook
  8509. (list :type 'todo-state-change
  8510. :position (point)
  8511. :from 'todo
  8512. :to 'done)))))
  8513. (defun org-update-statistics-cookies (all)
  8514. "Update the statistics cookie, either from TODO or from checkboxes.
  8515. This should be called with the cursor in a line with a statistics
  8516. cookie. When called with a \\[universal-argument] prefix, update
  8517. all statistics cookies in the buffer."
  8518. (interactive "P")
  8519. (if all
  8520. (progn
  8521. (org-update-checkbox-count 'all)
  8522. (org-map-region 'org-update-parent-todo-statistics
  8523. (point-min) (point-max)))
  8524. (if (not (org-at-heading-p))
  8525. (org-update-checkbox-count)
  8526. (let ((pos (point-marker))
  8527. end l1 l2)
  8528. (ignore-errors (org-back-to-heading t))
  8529. (if (not (org-at-heading-p))
  8530. (org-update-checkbox-count)
  8531. (setq l1 (org-outline-level))
  8532. (setq end
  8533. (save-excursion
  8534. (outline-next-heading)
  8535. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8536. (point)))
  8537. (if (and (save-excursion
  8538. (re-search-forward
  8539. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8540. (not (save-excursion
  8541. (re-search-forward
  8542. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8543. (org-update-checkbox-count)
  8544. (if (and l2 (> l2 l1))
  8545. (progn
  8546. (goto-char end)
  8547. (org-update-parent-todo-statistics))
  8548. (goto-char pos)
  8549. (beginning-of-line 1)
  8550. (while (re-search-forward
  8551. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8552. (line-end-position) t)
  8553. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8554. (goto-char pos)
  8555. (move-marker pos nil)))))
  8556. (defvar org-entry-property-inherited-from) ;; defined below
  8557. (defun org-update-parent-todo-statistics ()
  8558. "Update any statistics cookie in the parent of the current headline.
  8559. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8560. the entire subtree and this will travel up the hierarchy and update
  8561. statistics everywhere."
  8562. (let* ((prop (save-excursion
  8563. (org-up-heading-safe)
  8564. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8565. (recursive (or (not org-hierarchical-todo-statistics)
  8566. (and prop (string-match "\\<recursive\\>" prop))))
  8567. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8568. 0))
  8569. (first t)
  8570. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8571. level ltoggle l1 new ndel
  8572. (cnt-all 0) (cnt-done 0) is-percent kwd
  8573. checkbox-beg cookie-present)
  8574. (catch 'exit
  8575. (save-excursion
  8576. (beginning-of-line 1)
  8577. (setq ltoggle (funcall outline-level))
  8578. ;; Three situations are to consider:
  8579. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8580. ;; to the top-level ancestor on the headline;
  8581. ;; 2. If parent has "recursive" property, repeat up to the
  8582. ;; headline setting that property, taking inheritance into
  8583. ;; account;
  8584. ;; 3. Else, move up to direct parent and proceed only once.
  8585. (while (and (setq level (org-up-heading-safe))
  8586. (or recursive first)
  8587. (>= (point) lim))
  8588. (setq first nil cookie-present nil)
  8589. (unless (and level
  8590. (not (string-match
  8591. "\\<checkbox\\>"
  8592. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8593. "")))))
  8594. (throw 'exit nil))
  8595. (while (re-search-forward box-re (line-end-position) t)
  8596. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8597. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8598. (save-match-data
  8599. (unless (outline-next-heading) (throw 'exit nil))
  8600. (while (and (looking-at org-complex-heading-regexp)
  8601. (> (setq l1 (length (match-string 1))) level))
  8602. (setq kwd (and (or recursive (= l1 ltoggle))
  8603. (match-string 2)))
  8604. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8605. (and (eq org-provide-todo-statistics t)
  8606. (or (member kwd org-done-keywords)))
  8607. (and (listp org-provide-todo-statistics)
  8608. (stringp (car org-provide-todo-statistics))
  8609. (or (member kwd org-provide-todo-statistics)
  8610. (member kwd org-done-keywords)))
  8611. (and (listp org-provide-todo-statistics)
  8612. (listp (car org-provide-todo-statistics))
  8613. (or (member kwd (car org-provide-todo-statistics))
  8614. (and (member kwd org-done-keywords)
  8615. (member kwd (cadr org-provide-todo-statistics))))))
  8616. (setq cnt-all (1+ cnt-all))
  8617. (and (eq org-provide-todo-statistics t)
  8618. kwd
  8619. (setq cnt-all (1+ cnt-all))))
  8620. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8621. (member kwd org-done-keywords))
  8622. (and (listp org-provide-todo-statistics)
  8623. (listp (car org-provide-todo-statistics))
  8624. (member kwd org-done-keywords)
  8625. (member kwd (cadr org-provide-todo-statistics)))
  8626. (and (listp org-provide-todo-statistics)
  8627. (stringp (car org-provide-todo-statistics))
  8628. (member kwd org-done-keywords)))
  8629. (setq cnt-done (1+ cnt-done)))
  8630. (outline-next-heading)))
  8631. (setq new
  8632. (if is-percent
  8633. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8634. (max 1 cnt-all)))
  8635. (format "[%d/%d]" cnt-done cnt-all))
  8636. ndel (- (match-end 0) checkbox-beg))
  8637. (goto-char checkbox-beg)
  8638. (insert new)
  8639. (delete-region (point) (+ (point) ndel))
  8640. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8641. (when cookie-present
  8642. (run-hook-with-args 'org-after-todo-statistics-hook
  8643. cnt-done (- cnt-all cnt-done))))))
  8644. (run-hooks 'org-todo-statistics-hook)))
  8645. (defvar org-after-todo-statistics-hook nil
  8646. "Hook that is called after a TODO statistics cookie has been updated.
  8647. Each function is called with two arguments: the number of not-done entries
  8648. and the number of done entries.
  8649. For example, the following function, when added to this hook, will switch
  8650. an entry to DONE when all children are done, and back to TODO when new
  8651. entries are set to a TODO status. Note that this hook is only called
  8652. when there is a statistics cookie in the headline!
  8653. (defun org-summary-todo (n-done n-not-done)
  8654. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8655. (let (org-log-done org-log-states) ; turn off logging
  8656. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8657. (defvar org-todo-statistics-hook nil
  8658. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8659. This hook runs even if there is no statistics cookie present, in which case
  8660. `org-after-todo-statistics-hook' would not run.")
  8661. (defun org-todo-trigger-tag-changes (state)
  8662. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8663. (let ((l org-todo-state-tags-triggers)
  8664. changes)
  8665. (when (or (not state) (equal state ""))
  8666. (setq changes (append changes (cdr (assoc "" l)))))
  8667. (when (and (stringp state) (> (length state) 0))
  8668. (setq changes (append changes (cdr (assoc state l)))))
  8669. (when (member state org-not-done-keywords)
  8670. (setq changes (append changes (cdr (assq 'todo l)))))
  8671. (when (member state org-done-keywords)
  8672. (setq changes (append changes (cdr (assq 'done l)))))
  8673. (dolist (c changes)
  8674. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8675. (defun org-local-logging (value)
  8676. "Get logging settings from a property VALUE."
  8677. ;; Directly set the variables, they are already local.
  8678. (setq org-log-done nil
  8679. org-log-repeat nil
  8680. org-todo-log-states nil)
  8681. (dolist (w (split-string value))
  8682. (let (a)
  8683. (cond
  8684. ((setq a (assoc w org-startup-options))
  8685. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8686. (set (nth 1 a) (nth 2 a))))
  8687. ((setq a (org-extract-log-state-settings w))
  8688. (and (member (car a) org-todo-keywords-1)
  8689. (push a org-todo-log-states)))))))
  8690. (defun org-get-todo-sequence-head (kwd)
  8691. "Return the head of the TODO sequence to which KWD belongs.
  8692. If KWD is not set, check if there is a text property remembering the
  8693. right sequence."
  8694. (let (p)
  8695. (cond
  8696. ((not kwd)
  8697. (or (get-text-property (line-beginning-position) 'org-todo-head)
  8698. (progn
  8699. (setq p (next-single-property-change (line-beginning-position) 'org-todo-head
  8700. nil (line-end-position)))
  8701. (get-text-property p 'org-todo-head))))
  8702. ((not (member kwd org-todo-keywords-1))
  8703. (car org-todo-keywords-1))
  8704. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8705. (defun org-fast-todo-selection (&optional current-state)
  8706. "Fast TODO keyword selection with single keys.
  8707. Returns the new TODO keyword, or nil if no state change should occur.
  8708. When CURRENT-STATE is given and selection letters are not unique globally,
  8709. prefer a state in the current sequence over on in another sequence."
  8710. (let* ((fulltable org-todo-key-alist)
  8711. (head (org-get-todo-sequence-head current-state))
  8712. (done-keywords org-done-keywords) ;; needed for the faces.
  8713. (maxlen (apply 'max (mapcar
  8714. (lambda (x)
  8715. (if (stringp (car x)) (string-width (car x)) 0))
  8716. fulltable)))
  8717. (expert (equal org-use-fast-todo-selection 'expert))
  8718. (prompt "")
  8719. (fwidth (+ maxlen 3 1 3))
  8720. (ncol (/ (- (window-width) 4) fwidth))
  8721. tg cnt e c tbl subtable
  8722. groups ingroup in-current-sequence)
  8723. (save-excursion
  8724. (save-window-excursion
  8725. (if expert
  8726. (set-buffer (get-buffer-create " *Org todo*"))
  8727. (delete-other-windows)
  8728. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8729. (org-switch-to-buffer-other-window " *Org todo*"))
  8730. (erase-buffer)
  8731. (setq-local org-done-keywords done-keywords)
  8732. (setq tbl fulltable cnt 0)
  8733. (while (setq e (pop tbl))
  8734. (cond
  8735. ((equal e '(:startgroup))
  8736. (push '() groups) (setq ingroup t)
  8737. (unless (= cnt 0)
  8738. (setq cnt 0)
  8739. (insert "\n"))
  8740. (setq prompt (concat prompt "{"))
  8741. (insert "{ "))
  8742. ((equal e '(:endgroup))
  8743. (setq ingroup nil cnt 0 in-current-sequence nil)
  8744. (setq prompt (concat prompt "}"))
  8745. (insert "}\n"))
  8746. ((equal e '(:newline))
  8747. (unless (= cnt 0)
  8748. (setq cnt 0)
  8749. (insert "\n")
  8750. (setq e (car tbl))
  8751. (while (equal (car tbl) '(:newline))
  8752. (insert "\n")
  8753. (setq tbl (cdr tbl)))))
  8754. (t
  8755. (setq tg (car e) c (cdr e))
  8756. (if (equal tg head) (setq in-current-sequence t))
  8757. (when ingroup (push tg (car groups)))
  8758. (when in-current-sequence (push e subtable))
  8759. (setq tg (org-add-props tg nil 'face
  8760. (org-get-todo-face tg)))
  8761. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8762. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8763. (insert "[" c "] " tg (make-string
  8764. (- fwidth 4 (length tg)) ?\ ))
  8765. (when (and (= (setq cnt (1+ cnt)) ncol)
  8766. ;; Avoid lines with just a closing delimiter.
  8767. (not (equal (car tbl) '(:endgroup))))
  8768. (insert "\n")
  8769. (when ingroup (insert " "))
  8770. (setq cnt 0)))))
  8771. (insert "\n")
  8772. (goto-char (point-min))
  8773. (unless expert (org-fit-window-to-buffer))
  8774. (message (concat "[a-z..]:Set [SPC]:clear"
  8775. (if expert (concat "\n" prompt) "")))
  8776. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8777. (setq subtable (nreverse subtable))
  8778. (cond
  8779. ((or (= c ?\C-g)
  8780. (and (= c ?q) (not (rassoc c fulltable))))
  8781. (setq quit-flag t))
  8782. ((= c ?\ ) nil)
  8783. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8784. tg (car e))
  8785. tg)
  8786. (t (setq quit-flag t)))))))
  8787. (defun org-entry-is-todo-p ()
  8788. (member (org-get-todo-state) org-not-done-keywords))
  8789. (defun org-entry-is-done-p ()
  8790. (member (org-get-todo-state) org-done-keywords))
  8791. (defun org-get-todo-state ()
  8792. "Return the TODO keyword of the current subtree."
  8793. (save-excursion
  8794. (org-back-to-heading t)
  8795. (and (let ((case-fold-search nil))
  8796. (looking-at org-todo-line-regexp))
  8797. (match-end 2)
  8798. (match-string 2))))
  8799. (defun org-at-date-range-p (&optional inactive-ok)
  8800. "Non-nil if point is inside a date range.
  8801. When optional argument INACTIVE-OK is non-nil, also consider
  8802. inactive time ranges.
  8803. When this function returns a non-nil value, match data is set
  8804. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8805. on INACTIVE-OK."
  8806. (interactive)
  8807. (save-excursion
  8808. (catch 'exit
  8809. (let ((pos (point)))
  8810. (skip-chars-backward "^[<\r\n")
  8811. (skip-chars-backward "<[")
  8812. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8813. (>= (match-end 0) pos)
  8814. (throw 'exit t))
  8815. (skip-chars-backward "^<[\r\n")
  8816. (skip-chars-backward "<[")
  8817. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8818. (>= (match-end 0) pos)
  8819. (throw 'exit t)))
  8820. nil)))
  8821. (defun org-get-repeat (&optional timestamp)
  8822. "Check if there is a time-stamp with repeater in this entry.
  8823. Return the repeater, as a string, or nil. Also return nil when
  8824. this function is called before first heading.
  8825. When optional argument TIMESTAMP is a string, extract the
  8826. repeater from there instead."
  8827. (save-match-data
  8828. (cond
  8829. (timestamp
  8830. (and (string-match org-repeat-re timestamp)
  8831. (match-string-no-properties 1 timestamp)))
  8832. ((org-before-first-heading-p) nil)
  8833. (t
  8834. (save-excursion
  8835. (org-back-to-heading t)
  8836. (let ((end (org-entry-end-position)))
  8837. (catch :repeat
  8838. (while (re-search-forward org-repeat-re end t)
  8839. (when (save-match-data (org-at-timestamp-p 'agenda))
  8840. (throw :repeat (match-string-no-properties 1)))))))))))
  8841. (defvar org-last-changed-timestamp)
  8842. (defvar org-last-inserted-timestamp)
  8843. (defvar org-log-post-message)
  8844. (defvar org-log-note-purpose)
  8845. (defvar org-log-note-how nil)
  8846. (defvar org-log-note-extra)
  8847. (defvar org-log-setup nil)
  8848. (defun org-auto-repeat-maybe (done-word)
  8849. "Check if the current headline contains a repeated time-stamp.
  8850. If yes, set TODO state back to what it was and change the base date
  8851. of repeating deadline/scheduled time stamps to new date.
  8852. This function is run automatically after each state change to a DONE state."
  8853. (let* ((repeat (org-get-repeat))
  8854. (aa (assoc org-last-state org-todo-kwd-alist))
  8855. (interpret (nth 1 aa))
  8856. (head (nth 2 aa))
  8857. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8858. (msg "Entry repeats: ")
  8859. (org-log-done nil)
  8860. (org-todo-log-states nil)
  8861. (end (copy-marker (org-entry-end-position))))
  8862. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8863. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8864. (let ((to-state
  8865. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8866. (and (stringp org-todo-repeat-to-state)
  8867. org-todo-repeat-to-state)
  8868. (and org-todo-repeat-to-state org-last-state))))
  8869. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8870. to-state)
  8871. ((eq interpret 'type) org-last-state)
  8872. (head)
  8873. (t 'none))))
  8874. (org-back-to-heading t)
  8875. (org-add-planning-info nil nil 'closed)
  8876. ;; When `org-log-repeat' is non-nil or entry contains
  8877. ;; a clock, set LAST_REPEAT property.
  8878. (when (or org-log-repeat
  8879. (catch :clock
  8880. (save-excursion
  8881. (while (re-search-forward org-clock-line-re end t)
  8882. (when (org-at-clock-log-p) (throw :clock t))))))
  8883. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8884. (org-time-stamp-format t t)
  8885. (org-current-effective-time))))
  8886. (when org-log-repeat
  8887. (if org-log-setup
  8888. ;; We are already setup for some record.
  8889. (when (eq org-log-repeat 'note)
  8890. ;; Make sure we take a note, not only a time stamp.
  8891. (setq org-log-note-how 'note))
  8892. ;; Set up for taking a record.
  8893. (org-add-log-setup 'state
  8894. (or done-word (car org-done-keywords))
  8895. org-last-state
  8896. org-log-repeat)))
  8897. ;; Time-stamps without a repeater are usually skipped. However,
  8898. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8899. ;; longer relevant.
  8900. (save-excursion
  8901. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8902. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8903. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8904. ;; Update every time-stamp with a repeater in the entry.
  8905. (let ((planning-re (regexp-opt
  8906. (list org-scheduled-string org-deadline-string))))
  8907. (while (re-search-forward org-repeat-re end t)
  8908. (let* ((ts (match-string 0))
  8909. (type (if (not (org-at-planning-p)) "Plain:"
  8910. (save-excursion
  8911. (re-search-backward
  8912. planning-re (line-beginning-position) t)
  8913. (match-string 0)))))
  8914. (when (and (org-at-timestamp-p 'agenda)
  8915. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8916. (let ((n (string-to-number (match-string 2 ts)))
  8917. (what (match-string 3 ts)))
  8918. (when (equal what "w") (setq n (* n 7) what "d"))
  8919. (when (and (equal what "h")
  8920. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8921. ts)))
  8922. (user-error
  8923. "Cannot repeat in %d hour(s) because no hour has been set"
  8924. n))
  8925. ;; Preparation, see if we need to modify the start
  8926. ;; date for the change.
  8927. (when (match-end 1)
  8928. (let ((time (save-match-data (org-time-string-to-time ts)))
  8929. (repeater-type (match-string 1 ts)))
  8930. (cond
  8931. ((equal "." repeater-type)
  8932. ;; Shift starting date to today, or now if
  8933. ;; repeater is by hours.
  8934. (if (equal what "h")
  8935. (org-timestamp-change
  8936. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8937. (org-timestamp-change
  8938. (- (org-today) (time-to-days time)) 'day)))
  8939. ((equal "+" repeater-type)
  8940. (let ((nshiftmax 10)
  8941. (nshift 0))
  8942. (while (or (= nshift 0)
  8943. (not (time-less-p nil time)))
  8944. (when (= nshiftmax (cl-incf nshift))
  8945. (or (y-or-n-p
  8946. (format "%d repeater intervals were not \
  8947. enough to shift date past today. Continue? "
  8948. nshift))
  8949. (user-error "Abort")))
  8950. (org-timestamp-change n (cdr (assoc what whata)))
  8951. (org-in-regexp org-ts-regexp3)
  8952. (setq ts (match-string 1))
  8953. (setq time
  8954. (save-match-data
  8955. (org-time-string-to-time ts)))))
  8956. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8957. ;; Rematch, so that we have everything in place
  8958. ;; for the real shift.
  8959. (org-in-regexp org-ts-regexp3)
  8960. (setq ts (match-string 1))
  8961. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8962. ts)))))
  8963. (save-excursion
  8964. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8965. (setq msg
  8966. (concat msg type " " org-last-changed-timestamp " ")))))))
  8967. (run-hooks 'org-todo-repeat-hook)
  8968. (setq org-log-post-message msg)
  8969. (message msg))))
  8970. (defun org-show-todo-tree (arg)
  8971. "Make a compact tree which shows all headlines marked with TODO.
  8972. The tree will show the lines where the regexp matches, and all higher
  8973. headlines above the match.
  8974. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8975. With a numeric prefix N, construct a sparse tree for the Nth element
  8976. of `org-todo-keywords-1'."
  8977. (interactive "P")
  8978. (let ((case-fold-search nil)
  8979. (kwd-re
  8980. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8981. ((equal arg '(4))
  8982. (let ((kwd
  8983. (completing-read "Keyword (or KWD1|KWD2|...): "
  8984. (mapcar #'list org-todo-keywords-1))))
  8985. (concat "\\("
  8986. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8987. "\\)\\>")))
  8988. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8989. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8990. org-todo-keywords-1)))
  8991. (t (user-error "Invalid prefix argument: %s" arg)))))
  8992. (message "%d TODO entries found"
  8993. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8994. (defun org--deadline-or-schedule (arg type time)
  8995. "Insert DEADLINE or SCHEDULE information in current entry.
  8996. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8997. `org-schedule' for information about ARG and TIME arguments."
  8998. (org-fold-core-ignore-modifications
  8999. (let* ((deadline? (eq type 'deadline))
  9000. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9001. (log (if deadline? org-log-redeadline org-log-reschedule))
  9002. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9003. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9004. ;; Save repeater cookie from either TIME or current scheduled
  9005. ;; time stamp. We are going to insert it back at the end of
  9006. ;; the process.
  9007. (repeater (or (and (org-string-nw-p time)
  9008. ;; We use `org-ts-regexp-both' because we
  9009. ;; need to tell the difference between a
  9010. ;; real repeater and a time delta, e.g.
  9011. ;; "+2d".
  9012. (string-match-p org-ts-regexp-both time)
  9013. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9014. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9015. time)
  9016. (match-string 1 time))
  9017. (and (org-string-nw-p old-date)
  9018. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9019. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9020. old-date)
  9021. (match-string 1 old-date)))))
  9022. (pcase arg
  9023. (`(4)
  9024. (if (not old-date)
  9025. (message (if deadline? "Entry had no deadline to remove"
  9026. "Entry was not scheduled"))
  9027. (when (and old-date log)
  9028. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9029. nil old-date log))
  9030. (org-remove-timestamp-with-keyword keyword)
  9031. (message (if deadline? "Entry no longer has a deadline."
  9032. "Entry is no longer scheduled."))))
  9033. (`(16)
  9034. (save-excursion
  9035. (org-back-to-heading t)
  9036. (let ((regexp (if deadline? org-deadline-time-regexp
  9037. org-scheduled-time-regexp)))
  9038. (if (not (re-search-forward regexp (line-end-position 2) t))
  9039. (user-error (if deadline? "No deadline information to update"
  9040. "No scheduled information to update"))
  9041. (let* ((rpl0 (match-string 1))
  9042. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9043. (msg (if deadline? "Warn starting from" "Delay until")))
  9044. (replace-match
  9045. (concat keyword
  9046. " <" rpl
  9047. (format " -%dd"
  9048. (abs (- (time-to-days
  9049. (save-match-data
  9050. (org-read-date
  9051. nil t nil msg old-date-time)))
  9052. (time-to-days old-date-time))))
  9053. ">") t t))))))
  9054. (_
  9055. (org-add-planning-info type time 'closed)
  9056. (when (and old-date
  9057. log
  9058. (not (equal old-date org-last-inserted-timestamp)))
  9059. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9060. org-last-inserted-timestamp
  9061. old-date
  9062. log))
  9063. (when repeater
  9064. (save-excursion
  9065. (org-back-to-heading t)
  9066. (when (re-search-forward
  9067. (concat keyword " " org-last-inserted-timestamp)
  9068. (line-end-position 2)
  9069. t)
  9070. (goto-char (1- (match-end 0)))
  9071. (insert-and-inherit " " repeater)
  9072. (setq org-last-inserted-timestamp
  9073. (concat (substring org-last-inserted-timestamp 0 -1)
  9074. " " repeater
  9075. (substring org-last-inserted-timestamp -1))))))
  9076. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9077. org-last-inserted-timestamp))))))
  9078. (defun org-deadline (arg &optional time)
  9079. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9080. When called interactively, this command pops up the Emacs calendar to let
  9081. the user select a date.
  9082. With one universal prefix argument, remove any deadline from the item.
  9083. With two universal prefix arguments, prompt for a warning delay.
  9084. With argument TIME, set the deadline at the corresponding date. TIME
  9085. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9086. (interactive "P")
  9087. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9088. (org-map-entries
  9089. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9090. nil
  9091. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9092. 'region-start-level
  9093. 'region)
  9094. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9095. (org--deadline-or-schedule arg 'deadline time)))
  9096. (defun org-schedule (arg &optional time)
  9097. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9098. When called interactively, this command pops up the Emacs calendar to let
  9099. the user select a date.
  9100. With one universal prefix argument, remove any scheduling date from the item.
  9101. With two universal prefix arguments, prompt for a delay cookie.
  9102. With argument TIME, scheduled at the corresponding date. TIME can
  9103. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9104. (interactive "P")
  9105. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9106. (org-map-entries
  9107. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9108. nil
  9109. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9110. 'region-start-level
  9111. 'region)
  9112. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9113. (org--deadline-or-schedule arg 'scheduled time)))
  9114. (defun org-get-scheduled-time (pom &optional inherit)
  9115. "Get the scheduled time as a time tuple, of a format suitable
  9116. for calling org-schedule with, or if there is no scheduling,
  9117. returns nil."
  9118. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9119. (when time
  9120. (org-time-string-to-time time))))
  9121. (defun org-get-deadline-time (pom &optional inherit)
  9122. "Get the deadline as a time tuple, of a format suitable for
  9123. calling org-deadline with, or if there is no scheduling, returns
  9124. nil."
  9125. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9126. (when time
  9127. (org-time-string-to-time time))))
  9128. (defun org-remove-timestamp-with-keyword (keyword)
  9129. "Remove all time stamps with KEYWORD in the current entry."
  9130. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9131. beg)
  9132. (save-excursion
  9133. (org-back-to-heading t)
  9134. (setq beg (point))
  9135. (outline-next-heading)
  9136. (while (re-search-backward re beg t)
  9137. (replace-match "")
  9138. (if (and (string-match "\\S-" (buffer-substring (line-beginning-position) (point)))
  9139. (equal (char-before) ?\ ))
  9140. (backward-delete-char 1)
  9141. (when (string-match "^[ \t]*$" (buffer-substring
  9142. (line-beginning-position) (line-end-position)))
  9143. (delete-region (line-beginning-position)
  9144. (min (point-max) (1+ (line-end-position))))))))))
  9145. (defvar org-time-was-given) ; dynamically scoped parameter
  9146. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9147. (defun org-at-planning-p ()
  9148. "Non-nil when point is on a planning info line."
  9149. ;; This is as accurate and faster than `org-element-at-point' since
  9150. ;; planning info location is fixed in the section.
  9151. (or (let ((cached (org-element-at-point nil 'cached)))
  9152. (and cached
  9153. (eq 'planning (org-element-type cached))))
  9154. (org-with-wide-buffer
  9155. (beginning-of-line)
  9156. (and (looking-at-p org-planning-line-re)
  9157. (eq (point)
  9158. (ignore-errors
  9159. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9160. (org-back-to-heading t)
  9161. (org-with-limited-levels (org-back-to-heading t)))
  9162. (line-beginning-position 2)))))))
  9163. (defun org-add-planning-info (what &optional time &rest remove)
  9164. "Insert new timestamp with keyword in the planning line.
  9165. WHAT indicates what kind of time stamp to add. It is a symbol
  9166. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9167. the time to use. If none is given, the user is prompted for
  9168. a date. REMOVE indicates what kind of entries to remove. An old
  9169. WHAT entry will also be removed."
  9170. (org-fold-core-ignore-modifications
  9171. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9172. (when (and (memq what '(scheduled deadline))
  9173. (or (not time)
  9174. (and (stringp time)
  9175. (string-match "^[-+]+[0-9]" time))))
  9176. ;; Try to get a default date/time from existing timestamp
  9177. (save-excursion
  9178. (org-back-to-heading t)
  9179. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9180. (when (re-search-forward (if (eq what 'scheduled)
  9181. org-scheduled-time-regexp
  9182. org-deadline-time-regexp)
  9183. end t)
  9184. (setq ts (match-string 1)
  9185. default-time (org-time-string-to-time ts)
  9186. default-input (and ts (org-get-compact-tod ts)))))))
  9187. (when what
  9188. (setq time
  9189. (if (stringp time)
  9190. ;; This is a string (relative or absolute), set
  9191. ;; proper date.
  9192. (org-encode-time
  9193. (org-read-date-analyze
  9194. time default-time (decode-time default-time)))
  9195. ;; If necessary, get the time from the user
  9196. (or time (org-read-date nil 'to-time nil
  9197. (cl-case what
  9198. (deadline "DEADLINE")
  9199. (scheduled "SCHEDULED")
  9200. (otherwise nil))
  9201. default-time default-input)))))
  9202. (org-with-wide-buffer
  9203. (org-back-to-heading t)
  9204. (let ((planning? (save-excursion
  9205. (forward-line)
  9206. (looking-at-p org-planning-line-re))))
  9207. (cond
  9208. (planning?
  9209. (forward-line)
  9210. ;; Move to current indentation.
  9211. (skip-chars-forward " \t")
  9212. ;; Check if we have to remove something.
  9213. (dolist (type (if what (cons what remove) remove))
  9214. (save-excursion
  9215. (when (re-search-forward
  9216. (cl-case type
  9217. (closed org-closed-time-regexp)
  9218. (deadline org-deadline-time-regexp)
  9219. (scheduled org-scheduled-time-regexp)
  9220. (otherwise (error "Invalid planning type: %s" type)))
  9221. (line-end-position)
  9222. t)
  9223. ;; Delete until next keyword or end of line.
  9224. (delete-region
  9225. (match-beginning 0)
  9226. (if (re-search-forward org-keyword-time-not-clock-regexp
  9227. (line-end-position)
  9228. t)
  9229. (match-beginning 0)
  9230. (line-end-position))))))
  9231. ;; If there is nothing more to add and no more keyword is
  9232. ;; left, remove the line completely.
  9233. (if (and (looking-at-p "[ \t]*$") (not what))
  9234. (delete-region (line-end-position 0)
  9235. (line-end-position))
  9236. ;; If we removed last keyword, do not leave trailing white
  9237. ;; space at the end of line.
  9238. (let ((p (point)))
  9239. (save-excursion
  9240. (end-of-line)
  9241. (unless (= (skip-chars-backward " \t" p) 0)
  9242. (delete-region (point) (line-end-position)))))))
  9243. (what
  9244. (end-of-line)
  9245. (insert-and-inherit "\n")
  9246. (when org-adapt-indentation
  9247. (indent-to-column (1+ (org-outline-level)))))
  9248. (t nil)))
  9249. (when what
  9250. ;; Insert planning keyword.
  9251. (insert-and-inherit (cl-case what
  9252. (closed org-closed-string)
  9253. (deadline org-deadline-string)
  9254. (scheduled org-scheduled-string)
  9255. (otherwise (error "Invalid planning type: %s" what)))
  9256. " ")
  9257. ;; Insert associated timestamp.
  9258. (let ((ts (org-insert-time-stamp
  9259. time
  9260. (or org-time-was-given
  9261. (and (eq what 'closed) org-log-done-with-time))
  9262. (eq what 'closed)
  9263. nil nil (list org-end-time-was-given))))
  9264. (unless (eolp) (insert " "))
  9265. ts))))))
  9266. (defvar org-log-note-marker (make-marker)
  9267. "Marker pointing at the entry where the note is to be inserted.")
  9268. (defvar org-log-note-purpose nil)
  9269. (defvar org-log-note-state nil)
  9270. (defvar org-log-note-previous-state nil)
  9271. (defvar org-log-note-extra nil)
  9272. (defvar org-log-note-window-configuration nil)
  9273. (defvar org-log-note-return-to (make-marker))
  9274. (defvar org-log-note-effective-time nil
  9275. "Remembered current time.
  9276. So that dynamically scoped `org-extend-today-until' affects
  9277. timestamps in state change log.")
  9278. (defvar org-log-post-message nil
  9279. "Message to be displayed after a log note has been stored.
  9280. The auto-repeater uses this.")
  9281. (defun org-add-note ()
  9282. "Add a note to the current entry.
  9283. This is done in the same way as adding a state change note."
  9284. (interactive)
  9285. (org-add-log-setup 'note))
  9286. (defun org-log-beginning (&optional create)
  9287. "Return expected start of log notes in current entry.
  9288. When optional argument CREATE is non-nil, the function creates
  9289. a drawer to store notes, if necessary. Returned position ignores
  9290. narrowing."
  9291. (org-with-wide-buffer
  9292. (let ((drawer (org-log-into-drawer)))
  9293. (cond
  9294. (drawer
  9295. (org-end-of-meta-data)
  9296. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9297. (end (if (org-at-heading-p) (point)
  9298. (save-excursion (outline-next-heading) (point))))
  9299. (case-fold-search t))
  9300. (catch 'exit
  9301. ;; Try to find existing drawer.
  9302. (while (re-search-forward regexp end t)
  9303. (let ((element (org-element-at-point)))
  9304. (when (eq (org-element-type element) 'drawer)
  9305. (let ((cend (org-element-property :contents-end element)))
  9306. (when (and (not org-log-states-order-reversed) cend)
  9307. (goto-char cend)))
  9308. (throw 'exit nil))))
  9309. ;; No drawer found. Create one, if permitted.
  9310. (when create
  9311. ;; Unless current heading is the last heading in buffer
  9312. ;; and does not have a newline, `org-end-of-meta-data'
  9313. ;; should move us somewhere below the heading.
  9314. ;; Avoid situation when we insert drawer right before
  9315. ;; first "*". Otherwise, if the previous heading is
  9316. ;; folded, we are inserting after visible newline at
  9317. ;; the end of the fold, thus breaking the fold
  9318. ;; continuity.
  9319. (unless (eobp)
  9320. (when (org-at-heading-p) (backward-char)))
  9321. (org-fold-core-ignore-modifications
  9322. (unless (bolp) (insert-and-inherit "\n"))
  9323. (let ((beg (point)))
  9324. (insert-and-inherit ":" drawer ":\n:END:\n")
  9325. (org-indent-region beg (point))
  9326. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9327. (end-of-line -1))))
  9328. (t
  9329. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9330. (let ((endpos (point)))
  9331. (skip-chars-forward " \t\n")
  9332. (beginning-of-line)
  9333. (unless org-log-states-order-reversed
  9334. (org-skip-over-state-notes)
  9335. (skip-chars-backward " \t\n")
  9336. (beginning-of-line 2))
  9337. ;; When current headline is at the end of buffer and does not
  9338. ;; end with trailing newline the above can move to the
  9339. ;; beginning of the headline.
  9340. (when (< (point) endpos) (goto-char endpos))))))
  9341. (if (bolp) (point) (line-beginning-position 2))))
  9342. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9343. "Set up the post command hook to take a note.
  9344. If this is about to TODO state change, the new state is expected in STATE.
  9345. HOW is an indicator what kind of note should be created.
  9346. EXTRA is additional text that will be inserted into the notes buffer."
  9347. (move-marker org-log-note-marker (point))
  9348. (setq org-log-note-purpose purpose
  9349. org-log-note-state state
  9350. org-log-note-previous-state prev-state
  9351. org-log-note-how how
  9352. org-log-note-extra extra
  9353. org-log-note-effective-time (org-current-effective-time)
  9354. org-log-setup t)
  9355. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9356. (defun org-skip-over-state-notes ()
  9357. "Skip past the list of State notes in an entry."
  9358. (when (ignore-errors (goto-char (org-in-item-p)))
  9359. (let* ((struct (org-list-struct))
  9360. (prevs (org-list-prevs-alist struct))
  9361. (regexp
  9362. (concat "[ \t]*- +"
  9363. (replace-regexp-in-string
  9364. " +" " +"
  9365. (org-replace-escapes
  9366. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9367. `(("%d" . ,org-ts-regexp-inactive)
  9368. ("%D" . ,org-ts-regexp)
  9369. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9370. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9371. ("%t" . ,org-ts-regexp-inactive)
  9372. ("%T" . ,org-ts-regexp)
  9373. ("%u" . ".*?")
  9374. ("%U" . ".*?")))))))
  9375. (while (looking-at-p regexp)
  9376. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9377. (org-list-get-item-end (point) struct)))))))
  9378. (defun org-add-log-note (&optional _purpose)
  9379. "Pop up a window for taking a note, and add this note later."
  9380. (remove-hook 'post-command-hook 'org-add-log-note)
  9381. (setq org-log-setup nil)
  9382. (setq org-log-note-window-configuration (current-window-configuration))
  9383. (delete-other-windows)
  9384. (move-marker org-log-note-return-to (point))
  9385. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9386. (goto-char org-log-note-marker)
  9387. (org-switch-to-buffer-other-window "*Org Note*")
  9388. (erase-buffer)
  9389. (if (memq org-log-note-how '(time state))
  9390. (org-store-log-note)
  9391. (let ((org-inhibit-startup t)) (org-mode))
  9392. (insert (format "# Insert note for %s.
  9393. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9394. (cl-case org-log-note-purpose
  9395. (clock-out "stopped clock")
  9396. (done "closed todo item")
  9397. (reschedule "rescheduling")
  9398. (delschedule "no longer scheduled")
  9399. (redeadline "changing deadline")
  9400. (deldeadline "removing deadline")
  9401. (refile "refiling")
  9402. (note "this entry")
  9403. (state
  9404. (format "state change from \"%s\" to \"%s\""
  9405. (or org-log-note-previous-state "")
  9406. (or org-log-note-state "")))
  9407. (t (error "This should not happen")))))
  9408. (when org-log-note-extra (insert org-log-note-extra))
  9409. (setq-local org-finish-function 'org-store-log-note)
  9410. (run-hooks 'org-log-buffer-setup-hook)))
  9411. (defvar org-note-abort nil) ; dynamically scoped
  9412. (defun org-store-log-note ()
  9413. "Finish taking a log note, and insert it to where it belongs."
  9414. (let ((txt (prog1 (buffer-string)
  9415. (kill-buffer)))
  9416. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9417. lines)
  9418. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9419. (setq txt (replace-match "" t t txt)))
  9420. (when (string-match "\\s-+\\'" txt)
  9421. (setq txt (replace-match "" t t txt)))
  9422. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9423. (when (org-string-nw-p note)
  9424. (setq note
  9425. (org-replace-escapes
  9426. note
  9427. (list (cons "%u" (user-login-name))
  9428. (cons "%U" user-full-name)
  9429. (cons "%t" (format-time-string
  9430. (org-time-stamp-format 'long 'inactive)
  9431. org-log-note-effective-time))
  9432. (cons "%T" (format-time-string
  9433. (org-time-stamp-format 'long nil)
  9434. org-log-note-effective-time))
  9435. (cons "%d" (format-time-string
  9436. (org-time-stamp-format nil 'inactive)
  9437. org-log-note-effective-time))
  9438. (cons "%D" (format-time-string
  9439. (org-time-stamp-format nil nil)
  9440. org-log-note-effective-time))
  9441. (cons "%s" (cond
  9442. ((not org-log-note-state) "")
  9443. ((string-match-p org-ts-regexp
  9444. org-log-note-state)
  9445. (format "\"[%s]\""
  9446. (substring org-log-note-state 1 -1)))
  9447. (t (format "\"%s\"" org-log-note-state))))
  9448. (cons "%S"
  9449. (cond
  9450. ((not org-log-note-previous-state) "")
  9451. ((string-match-p org-ts-regexp
  9452. org-log-note-previous-state)
  9453. (format "\"[%s]\""
  9454. (substring
  9455. org-log-note-previous-state 1 -1)))
  9456. (t (format "\"%s\""
  9457. org-log-note-previous-state)))))))
  9458. (when lines (setq note (concat note " \\\\")))
  9459. (push note lines))
  9460. (when (and lines (not org-note-abort))
  9461. (with-current-buffer (marker-buffer org-log-note-marker)
  9462. (org-fold-core-ignore-modifications
  9463. (org-with-wide-buffer
  9464. ;; Find location for the new note.
  9465. (goto-char org-log-note-marker)
  9466. (set-marker org-log-note-marker nil)
  9467. ;; Note associated to a clock is to be located right after
  9468. ;; the clock. Do not move point.
  9469. (unless (eq org-log-note-purpose 'clock-out)
  9470. (goto-char (org-log-beginning t)))
  9471. ;; Make sure point is at the beginning of an empty line.
  9472. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9473. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9474. ;; In an existing list, add a new item at the top level.
  9475. ;; Otherwise, indent line like a regular one.
  9476. (let ((itemp (org-in-item-p)))
  9477. (if itemp
  9478. (indent-line-to
  9479. (let ((struct (save-excursion
  9480. (goto-char itemp) (org-list-struct))))
  9481. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9482. (org-indent-line)))
  9483. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9484. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9485. (dolist (line lines)
  9486. (insert-and-inherit "\n")
  9487. (unless (string-empty-p line)
  9488. (indent-line-to ind)
  9489. (insert-and-inherit line))))
  9490. (message "Note stored")
  9491. (org-back-to-heading t))))))
  9492. ;; Don't add undo information when called from `org-agenda-todo'.
  9493. (set-window-configuration org-log-note-window-configuration)
  9494. (with-current-buffer (marker-buffer org-log-note-return-to)
  9495. (goto-char org-log-note-return-to))
  9496. (move-marker org-log-note-return-to nil)
  9497. (when org-log-post-message (message "%s" org-log-post-message)))
  9498. (defun org-remove-empty-drawer-at (pos)
  9499. "Remove an empty drawer at position POS.
  9500. POS may also be a marker."
  9501. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9502. (org-with-wide-buffer
  9503. (goto-char pos)
  9504. (let ((drawer (org-element-at-point)))
  9505. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9506. (not (org-element-property :contents-begin drawer)))
  9507. (delete-region (org-element-property :begin drawer)
  9508. (progn (goto-char (org-element-property :end drawer))
  9509. (skip-chars-backward " \r\t\n")
  9510. (forward-line)
  9511. (point))))))))
  9512. (defvar org-ts-type nil)
  9513. (defun org-sparse-tree (&optional arg type)
  9514. "Create a sparse tree, prompt for the details.
  9515. This command can create sparse trees. You first need to select the type
  9516. of match used to create the tree:
  9517. t Show all TODO entries.
  9518. T Show entries with a specific TODO keyword.
  9519. m Show entries selected by a tags/property match.
  9520. p Enter a property name and its value (both with completion on existing
  9521. names/values) and show entries with that property.
  9522. r Show entries matching a regular expression (`/' can be used as well).
  9523. b Show deadlines and scheduled items before a date.
  9524. a Show deadlines and scheduled items after a date.
  9525. d Show deadlines due within `org-deadline-warning-days'.
  9526. D Show deadlines and scheduled items between a date range."
  9527. (interactive "P")
  9528. (setq type (or type org-sparse-tree-default-date-type))
  9529. (setq org-ts-type type)
  9530. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9531. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9532. [c]ycle through date types: %s"
  9533. (cl-case type
  9534. (all "all timestamps")
  9535. (scheduled "only scheduled")
  9536. (deadline "only deadline")
  9537. (active "only active timestamps")
  9538. (inactive "only inactive timestamps")
  9539. (closed "with a closed time-stamp")
  9540. (otherwise "scheduled/deadline")))
  9541. (let ((answer (read-char-exclusive)))
  9542. (cl-case answer
  9543. (?c
  9544. (org-sparse-tree
  9545. arg
  9546. (cadr
  9547. (memq type '(nil all scheduled deadline active inactive closed)))))
  9548. (?d (call-interactively 'org-check-deadlines))
  9549. (?b (call-interactively 'org-check-before-date))
  9550. (?a (call-interactively 'org-check-after-date))
  9551. (?D (call-interactively 'org-check-dates-range))
  9552. (?t (call-interactively 'org-show-todo-tree))
  9553. (?T (org-show-todo-tree '(4)))
  9554. (?m (call-interactively 'org-match-sparse-tree))
  9555. ((?p ?P)
  9556. (let* ((kwd (completing-read
  9557. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9558. (value (completing-read
  9559. "Value: " (mapcar #'list (org-property-values kwd)))))
  9560. (unless (string-match "\\`{.*}\\'" value)
  9561. (setq value (concat "\"" value "\"")))
  9562. (org-match-sparse-tree arg (concat kwd "=" value))))
  9563. ((?r ?R ?/) (call-interactively 'org-occur))
  9564. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9565. (defvar-local org-occur-highlights nil
  9566. "List of overlays used for occur matches.")
  9567. (defvar-local org-occur-parameters nil
  9568. "Parameters of the active org-occur calls.
  9569. This is a list, each call to org-occur pushes as cons cell,
  9570. containing the regular expression and the callback, onto the list.
  9571. The list can contain several entries if `org-occur' has been called
  9572. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9573. will only contain one set of parameters. When the highlights are
  9574. removed (for example with `C-c C-c', or with the next edit (depending
  9575. on `org-remove-highlights-with-change'), this variable is emptied
  9576. as well.")
  9577. (defun org-occur (regexp &optional keep-previous callback)
  9578. "Make a compact tree showing all matches of REGEXP.
  9579. The tree will show the lines where the regexp matches, and any other context
  9580. defined in `org-fold-show-context-detail', which see.
  9581. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9582. done by a previous call to `org-occur' will be kept, to allow stacking of
  9583. calls to this command.
  9584. Optional argument CALLBACK can be a function of no argument. In this case,
  9585. it is called with point at the end of the match, match data being set
  9586. accordingly. Current match is shown only if the return value is non-nil.
  9587. The function must neither move point nor alter narrowing."
  9588. (interactive "sRegexp: \nP")
  9589. (when (equal regexp "")
  9590. (user-error "Regexp cannot be empty"))
  9591. (unless keep-previous
  9592. (org-remove-occur-highlights nil nil t))
  9593. (push (cons regexp callback) org-occur-parameters)
  9594. (let ((cnt 0))
  9595. (save-excursion
  9596. (goto-char (point-min))
  9597. (when (or (not keep-previous) ; do not want to keep
  9598. (not org-occur-highlights)) ; no previous matches
  9599. ;; hide everything
  9600. (org-cycle-overview))
  9601. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9602. (isearch-no-upper-case-p regexp t)
  9603. org-occur-case-fold-search)))
  9604. (while (re-search-forward regexp nil t)
  9605. (when (or (not callback)
  9606. (save-match-data (funcall callback)))
  9607. (setq cnt (1+ cnt))
  9608. (when org-highlight-sparse-tree-matches
  9609. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9610. (org-fold-show-context 'occur-tree)))))
  9611. (when org-remove-highlights-with-change
  9612. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9613. nil 'local))
  9614. (unless org-sparse-tree-open-archived-trees
  9615. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9616. (run-hooks 'org-occur-hook)
  9617. (when (called-interactively-p 'interactive)
  9618. (message "%d match(es) for regexp %s" cnt regexp))
  9619. cnt))
  9620. (defun org-occur-next-match (&optional n _reset)
  9621. "Function for `next-error-function' to find sparse tree matches.
  9622. N is the number of matches to move, when negative move backwards.
  9623. This function always goes back to the starting point when no
  9624. match is found."
  9625. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9626. (search-func (if (< n 0)
  9627. 'previous-single-char-property-change
  9628. 'next-single-char-property-change))
  9629. (n (abs n))
  9630. (pos (point))
  9631. p1)
  9632. (catch 'exit
  9633. (while (setq p1 (funcall search-func (point) 'org-type))
  9634. (when (equal p1 limit)
  9635. (goto-char pos)
  9636. (user-error "No more matches"))
  9637. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9638. (setq n (1- n))
  9639. (when (= n 0)
  9640. (goto-char p1)
  9641. (throw 'exit (point))))
  9642. (goto-char p1))
  9643. (goto-char p1)
  9644. (user-error "No more matches"))))
  9645. (defun org-highlight-new-match (beg end)
  9646. "Highlight from BEG to END and mark the highlight is an occur headline."
  9647. (let ((ov (make-overlay beg end)))
  9648. (overlay-put ov 'face 'secondary-selection)
  9649. (overlay-put ov 'org-type 'org-occur)
  9650. (push ov org-occur-highlights)))
  9651. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9652. "Remove the occur highlights from the buffer.
  9653. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9654. from the `before-change-functions' in the current buffer."
  9655. (interactive)
  9656. (unless org-inhibit-highlight-removal
  9657. (mapc #'delete-overlay org-occur-highlights)
  9658. (setq org-occur-highlights nil)
  9659. (setq org-occur-parameters nil)
  9660. (unless noremove
  9661. (remove-hook 'before-change-functions
  9662. 'org-remove-occur-highlights 'local))))
  9663. ;;;; Priorities
  9664. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9665. "Regular expression matching the priority indicator.
  9666. A priority indicator can be e.g. [#A] or [#1].
  9667. This regular expression matches these groups:
  9668. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9669. 1 : the priority cookie, e.g. \"[#A]\"
  9670. 2 : the value of the priority cookie, e.g. \"A\".")
  9671. (defun org-priority-up ()
  9672. "Increase the priority of the current item."
  9673. (interactive)
  9674. (org-priority 'up))
  9675. (defun org-priority-down ()
  9676. "Decrease the priority of the current item."
  9677. (interactive)
  9678. (org-priority 'down))
  9679. (defun org-priority (&optional action show)
  9680. "Change the priority of an item.
  9681. When called interactively with a `\\[universal-argument]' prefix,
  9682. show the priority in the minibuffer instead of changing it.
  9683. When called programmatically, ACTION can be `set', `up', `down',
  9684. or a character."
  9685. (interactive "P")
  9686. (when show
  9687. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9688. ;; passed the SHOW argument should be removed.
  9689. (warn "`org-priority' called with deprecated SHOW argument"))
  9690. (if (equal action '(4))
  9691. (org-priority-show)
  9692. (unless org-priority-enable-commands
  9693. (user-error "Priority commands are disabled"))
  9694. (setq action (or action 'set))
  9695. (let ((nump (< org-priority-lowest 65))
  9696. current new news have remove)
  9697. (save-excursion
  9698. (org-back-to-heading t)
  9699. (when (looking-at org-priority-regexp)
  9700. (let ((ms (match-string 2)))
  9701. (setq current (org-priority-to-value ms)
  9702. have t)))
  9703. (cond
  9704. ((eq action 'remove)
  9705. (setq remove t new ?\ ))
  9706. ((or (eq action 'set)
  9707. (integerp action))
  9708. (if (not (eq action 'set))
  9709. (setq new action)
  9710. (setq
  9711. new
  9712. (if nump
  9713. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9714. (number-to-string org-priority-highest)
  9715. (number-to-string org-priority-lowest)))
  9716. (s (if (< 9 org-priority-lowest)
  9717. (read-string msg)
  9718. (message msg)
  9719. (char-to-string (read-char-exclusive)))))
  9720. (if (equal s " ") ?\s (string-to-number s)))
  9721. (progn (message "Priority %c-%c, SPC to remove: "
  9722. org-priority-highest org-priority-lowest)
  9723. (save-match-data
  9724. (setq new (read-char-exclusive)))))))
  9725. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9726. (= (upcase org-priority-lowest) org-priority-lowest))
  9727. (setq new (upcase new)))
  9728. (cond ((equal new ?\s) (setq remove t))
  9729. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9730. (user-error
  9731. (if nump
  9732. "Priority must be between `%s' and `%s'"
  9733. "Priority must be between `%c' and `%c'")
  9734. org-priority-highest org-priority-lowest))))
  9735. ((eq action 'up)
  9736. (setq new (if have
  9737. (1- current) ; normal cycling
  9738. ;; last priority was empty
  9739. (if (eq last-command this-command)
  9740. org-priority-lowest ; wrap around empty to lowest
  9741. ;; default
  9742. (if org-priority-start-cycle-with-default
  9743. org-priority-default
  9744. (1- org-priority-default))))))
  9745. ((eq action 'down)
  9746. (setq new (if have
  9747. (1+ current) ; normal cycling
  9748. ;; last priority was empty
  9749. (if (eq last-command this-command)
  9750. org-priority-highest ; wrap around empty to highest
  9751. ;; default
  9752. (if org-priority-start-cycle-with-default
  9753. org-priority-default
  9754. (1+ org-priority-default))))))
  9755. (t (user-error "Invalid action")))
  9756. (when (or (< (upcase new) org-priority-highest)
  9757. (> (upcase new) org-priority-lowest))
  9758. (if (and (memq action '(up down))
  9759. (not have) (not (eq last-command this-command)))
  9760. ;; `new' is from default priority
  9761. (error
  9762. "The default can not be set, see `org-priority-default' why")
  9763. ;; normal cycling: `new' is beyond highest/lowest priority
  9764. ;; and is wrapped around to the empty priority
  9765. (setq remove t)))
  9766. ;; Numerical priorities are limited to 64, beyond that number,
  9767. ;; assume the priority cookie is a character.
  9768. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9769. (if have
  9770. (if remove
  9771. (replace-match "" t t nil 1)
  9772. (replace-match news t t nil 2))
  9773. (if remove
  9774. (user-error "No priority cookie found in line")
  9775. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9776. (if (match-end 2)
  9777. (progn
  9778. (goto-char (match-end 2))
  9779. (insert " [#" news "]"))
  9780. (goto-char (match-beginning 3))
  9781. (insert "[#" news "] "))))
  9782. (org-align-tags))
  9783. (if remove
  9784. (message "Priority removed")
  9785. (message "Priority of current item set to %s" news)))))
  9786. (defalias 'org-show-priority 'org-priority-show)
  9787. (defun org-priority-show ()
  9788. "Show the priority of the current item.
  9789. This priority is composed of the main priority given with the [#A] cookies,
  9790. and by additional input from the age of a schedules or deadline entry."
  9791. (interactive)
  9792. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9793. (org-get-at-bol 'priority)
  9794. (save-excursion
  9795. (save-match-data
  9796. (beginning-of-line)
  9797. (and (looking-at org-heading-regexp)
  9798. (org-get-priority (match-string 0))))))))
  9799. (message "Priority is %d" (if pri pri -1000))))
  9800. (defun org-get-priority (s)
  9801. "Find priority cookie and return priority.
  9802. S is a string against which you can match `org-priority-regexp'.
  9803. If `org-priority-get-priority-function' is set to a custom
  9804. function, use it. Otherwise process S and output the priority
  9805. value, an integer."
  9806. (save-match-data
  9807. (if (functionp org-priority-get-priority-function)
  9808. (funcall org-priority-get-priority-function s)
  9809. (if (not (string-match org-priority-regexp s))
  9810. (* 1000 (- org-priority-lowest org-priority-default))
  9811. (* 1000 (- org-priority-lowest
  9812. (org-priority-to-value (match-string 2 s))))))))
  9813. ;;;; Tags
  9814. (defvar org-agenda-archives-mode)
  9815. (defvar org-map-continue-from nil
  9816. "Position from where mapping should continue.
  9817. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9818. (defvar org-scanner-tags nil
  9819. "The current tag list while the tags scanner is running.")
  9820. (defvar org-trust-scanner-tags nil
  9821. "Should `org-get-tags' use the tags for the scanner.
  9822. This is for internal dynamical scoping only.
  9823. When this is non-nil, the function `org-get-tags' will return the value
  9824. of `org-scanner-tags' instead of building the list by itself. This
  9825. can lead to large speed-ups when the tags scanner is used in a file with
  9826. many entries, and when the list of tags is retrieved, for example to
  9827. obtain a list of properties. Building the tags list for each entry in such
  9828. a file becomes an N^2 operation - but with this variable set, it scales
  9829. as N.")
  9830. (defvar org--matcher-tags-todo-only nil)
  9831. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9832. "Scan headline tags with inheritance and produce output ACTION.
  9833. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9834. or `agenda' to produce an entry list for an agenda view. It can also be
  9835. a Lisp form or a function that should be called at each matched headline, in
  9836. this case the return value is a list of all return values from these calls.
  9837. MATCHER is a function accepting three arguments, returning
  9838. a non-nil value whenever a given set of tags qualifies a headline
  9839. for inclusion. See `org-make-tags-matcher' for more information.
  9840. As a special case, it can also be set to t (respectively nil) in
  9841. order to match all (respectively none) headline.
  9842. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9843. included in the output.
  9844. START-LEVEL can be a string with asterisks, reducing the scope to
  9845. headlines matching this string."
  9846. (require 'org-agenda)
  9847. (let* ((re (concat "^"
  9848. (if start-level
  9849. ;; Get the correct level to match
  9850. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9851. org-outline-regexp)
  9852. " *\\(?:\\(" (regexp-opt org-todo-keywords-1 t) "\\) \\)?"
  9853. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9854. (props (list 'face 'default
  9855. 'done-face 'org-agenda-done
  9856. 'undone-face 'default
  9857. 'mouse-face 'highlight
  9858. 'org-not-done-regexp org-not-done-regexp
  9859. 'org-todo-regexp org-todo-regexp
  9860. 'org-complex-heading-regexp org-complex-heading-regexp
  9861. 'help-echo
  9862. (format "mouse-2 or RET jump to Org file %S"
  9863. (abbreviate-file-name
  9864. (or (buffer-file-name (buffer-base-buffer))
  9865. (buffer-name (buffer-base-buffer)))))))
  9866. (org-map-continue-from nil)
  9867. lspos tags tags-list
  9868. (tags-alist (list (cons 0 org-file-tags)))
  9869. (llast 0) rtn rtn1 level category i txt
  9870. todo marker entry priority
  9871. ts-date ts-date-type ts-date-pair)
  9872. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9873. (setq action (list 'lambda nil action)))
  9874. (save-excursion
  9875. (goto-char (point-min))
  9876. (when (eq action 'sparse-tree)
  9877. (org-cycle-overview)
  9878. (org-remove-occur-highlights))
  9879. (if (org-element--cache-active-p)
  9880. (let ((fast-re (concat "^"
  9881. (if start-level
  9882. ;; Get the correct level to match
  9883. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9884. org-outline-regexp))))
  9885. (org-element-cache-map
  9886. (lambda (el)
  9887. (goto-char (org-element-property :begin el))
  9888. (setq todo (org-element-property :todo-keyword el)
  9889. level (org-element-property :level el)
  9890. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9891. tags-list (org-get-tags el)
  9892. org-scanner-tags tags-list)
  9893. (when (eq action 'agenda)
  9894. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9895. ts-date (car ts-date-pair)
  9896. ts-date-type (cdr ts-date-pair)))
  9897. (catch :skip
  9898. (when (and
  9899. ;; eval matcher only when the todo condition is OK
  9900. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9901. (if (functionp matcher)
  9902. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9903. (funcall matcher todo tags-list level))
  9904. matcher))
  9905. ;; Call the skipper, but return t if it does not
  9906. ;; skip, so that the `and' form continues evaluating.
  9907. (progn
  9908. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9909. t)
  9910. ;; Check if timestamps are deselecting this entry
  9911. (or (not todo-only)
  9912. (and (member todo org-todo-keywords-1)
  9913. (or (not org-agenda-tags-todo-honor-ignore-options)
  9914. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9915. ;; select this headline
  9916. (cond
  9917. ((eq action 'sparse-tree)
  9918. (and org-highlight-sparse-tree-matches
  9919. (org-get-heading) (match-end 0)
  9920. (org-highlight-new-match
  9921. (match-beginning 1) (match-end 1)))
  9922. (org-fold-show-context 'tags-tree))
  9923. ((eq action 'agenda)
  9924. (let* ((effort (org-entry-get (point) org-effort-property))
  9925. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9926. (setq txt (org-agenda-format-item
  9927. ""
  9928. ;; Add `effort' and `effort-minutes'
  9929. ;; properties for prefix format.
  9930. (org-add-props
  9931. (concat
  9932. (if (eq org-tags-match-list-sublevels 'indented)
  9933. (make-string (1- level) ?.) "")
  9934. (org-get-heading))
  9935. nil
  9936. 'effort effort
  9937. 'effort-minutes effort-minutes)
  9938. (make-string level ?\s)
  9939. category
  9940. tags-list)
  9941. priority (org-get-priority txt))
  9942. ;; Now add `effort' and `effort-minutes' to
  9943. ;; full agenda line.
  9944. (setq txt (org-add-props txt nil
  9945. 'effort effort
  9946. 'effort-minutes effort-minutes)))
  9947. (goto-char (org-element-property :begin el))
  9948. (setq marker (org-agenda-new-marker))
  9949. (org-add-props txt props
  9950. 'org-marker marker 'org-hd-marker marker 'org-category category
  9951. 'todo-state todo
  9952. 'ts-date ts-date
  9953. 'priority priority
  9954. 'type (concat "tagsmatch" ts-date-type))
  9955. (push txt rtn))
  9956. ((functionp action)
  9957. (setq org-map-continue-from nil)
  9958. (save-excursion
  9959. (setq rtn1 (funcall action))
  9960. (push rtn1 rtn)))
  9961. (t (user-error "Invalid action")))
  9962. ;; if we are to skip sublevels, jump to end of subtree
  9963. (unless org-tags-match-list-sublevels
  9964. (goto-char (1- (org-element-property :end el))))))
  9965. ;; Get the correct position from where to continue
  9966. (when org-map-continue-from
  9967. (setq org-element-cache-map-continue-from org-map-continue-from)
  9968. (goto-char org-map-continue-from))
  9969. ;; Return nil.
  9970. nil)
  9971. :next-re fast-re
  9972. :fail-re fast-re
  9973. :narrow t))
  9974. (while (let (case-fold-search)
  9975. (re-search-forward re nil t))
  9976. (setq org-map-continue-from nil)
  9977. (catch :skip
  9978. ;; Ignore closing parts of inline tasks.
  9979. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9980. (throw :skip t))
  9981. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9982. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9983. (goto-char (setq lspos (match-beginning 0)))
  9984. (setq level (org-reduced-level (org-outline-level))
  9985. category (org-get-category))
  9986. (when (eq action 'agenda)
  9987. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9988. ts-date (car ts-date-pair)
  9989. ts-date-type (cdr ts-date-pair)))
  9990. (setq i llast llast level)
  9991. ;; remove tag lists from same and sublevels
  9992. (while (>= i level)
  9993. (when (setq entry (assoc i tags-alist))
  9994. (setq tags-alist (delete entry tags-alist)))
  9995. (setq i (1- i)))
  9996. ;; add the next tags
  9997. (when tags
  9998. (setq tags (org-split-string tags ":")
  9999. tags-alist
  10000. (cons (cons level tags) tags-alist)))
  10001. ;; compile tags for current headline
  10002. (setq tags-list
  10003. (if org-use-tag-inheritance
  10004. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10005. tags)
  10006. org-scanner-tags tags-list)
  10007. (when org-use-tag-inheritance
  10008. (setcdr (car tags-alist)
  10009. (mapcar (lambda (x)
  10010. (setq x (copy-sequence x))
  10011. (org-add-prop-inherited x))
  10012. (cdar tags-alist))))
  10013. (when (and tags org-use-tag-inheritance
  10014. (or (not (eq t org-use-tag-inheritance))
  10015. org-tags-exclude-from-inheritance))
  10016. ;; Selective inheritance, remove uninherited ones.
  10017. (setcdr (car tags-alist)
  10018. (org-remove-uninherited-tags (cdar tags-alist))))
  10019. (when (and
  10020. ;; eval matcher only when the todo condition is OK
  10021. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10022. (if (functionp matcher)
  10023. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10024. (funcall matcher todo tags-list level))
  10025. matcher))
  10026. ;; Call the skipper, but return t if it does not
  10027. ;; skip, so that the `and' form continues evaluating.
  10028. (progn
  10029. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10030. t)
  10031. ;; Check if timestamps are deselecting this entry
  10032. (or (not todo-only)
  10033. (and (member todo org-todo-keywords-1)
  10034. (or (not org-agenda-tags-todo-honor-ignore-options)
  10035. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10036. ;; select this headline
  10037. (cond
  10038. ((eq action 'sparse-tree)
  10039. (and org-highlight-sparse-tree-matches
  10040. (org-get-heading) (match-end 0)
  10041. (org-highlight-new-match
  10042. (match-beginning 1) (match-end 1)))
  10043. (org-fold-show-context 'tags-tree))
  10044. ((eq action 'agenda)
  10045. (setq txt (org-agenda-format-item
  10046. ""
  10047. (concat
  10048. (if (eq org-tags-match-list-sublevels 'indented)
  10049. (make-string (1- level) ?.) "")
  10050. (org-get-heading))
  10051. (make-string level ?\s)
  10052. category
  10053. tags-list)
  10054. priority (org-get-priority txt))
  10055. (goto-char lspos)
  10056. (setq marker (org-agenda-new-marker))
  10057. (org-add-props txt props
  10058. 'org-marker marker 'org-hd-marker marker 'org-category category
  10059. 'todo-state todo
  10060. 'ts-date ts-date
  10061. 'priority priority
  10062. 'type (concat "tagsmatch" ts-date-type))
  10063. (push txt rtn))
  10064. ((functionp action)
  10065. (setq org-map-continue-from nil)
  10066. (save-excursion
  10067. (setq rtn1 (funcall action))
  10068. (push rtn1 rtn)))
  10069. (t (user-error "Invalid action")))
  10070. ;; if we are to skip sublevels, jump to end of subtree
  10071. (unless org-tags-match-list-sublevels
  10072. (org-end-of-subtree t)
  10073. (backward-char 1))))
  10074. ;; Get the correct position from where to continue
  10075. (if org-map-continue-from
  10076. (goto-char org-map-continue-from)
  10077. (and (= (point) lspos) (end-of-line 1))))))
  10078. (when (and (eq action 'sparse-tree)
  10079. (not org-sparse-tree-open-archived-trees))
  10080. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  10081. (nreverse rtn)))
  10082. (defun org-remove-uninherited-tags (tags)
  10083. "Remove all tags that are not inherited from the list TAGS."
  10084. (cond
  10085. ((eq org-use-tag-inheritance t)
  10086. (if org-tags-exclude-from-inheritance
  10087. (org-delete-all org-tags-exclude-from-inheritance tags)
  10088. tags))
  10089. ((not org-use-tag-inheritance) nil)
  10090. ((stringp org-use-tag-inheritance)
  10091. (delq nil (mapcar
  10092. (lambda (x)
  10093. (if (and (string-match org-use-tag-inheritance x)
  10094. (not (member x org-tags-exclude-from-inheritance)))
  10095. x nil))
  10096. tags)))
  10097. ((listp org-use-tag-inheritance)
  10098. (delq nil (mapcar
  10099. (lambda (x)
  10100. (if (member x org-use-tag-inheritance) x nil))
  10101. tags)))))
  10102. (defun org-match-sparse-tree (&optional todo-only match)
  10103. "Create a sparse tree according to tags string MATCH.
  10104. MATCH is a string with match syntax. It can contain a selection
  10105. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10106. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10107. those. See the manual for details.
  10108. If optional argument TODO-ONLY is non-nil, only select lines that
  10109. are also TODO tasks."
  10110. (interactive "P")
  10111. (org-agenda-prepare-buffers (list (current-buffer)))
  10112. (let ((org--matcher-tags-todo-only todo-only))
  10113. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10114. org--matcher-tags-todo-only)))
  10115. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10116. (defvar org-cached-props nil)
  10117. (defun org-cached-entry-get (pom property)
  10118. (if (or (eq t org-use-property-inheritance)
  10119. (and (stringp org-use-property-inheritance)
  10120. (let ((case-fold-search t))
  10121. (string-match-p org-use-property-inheritance property)))
  10122. (and (listp org-use-property-inheritance)
  10123. (member-ignore-case property org-use-property-inheritance)))
  10124. ;; Caching is not possible, check it directly.
  10125. (org-entry-get pom property 'inherit)
  10126. ;; Get all properties, so we can do complicated checks easily.
  10127. (cdr (assoc-string property
  10128. (or org-cached-props
  10129. (setq org-cached-props (org-entry-properties pom)))
  10130. t))))
  10131. (defun org-global-tags-completion-table (&optional files)
  10132. "Return the list of all tags in all agenda buffer/files.
  10133. Optional FILES argument is a list of files which can be used
  10134. instead of the agenda files."
  10135. (save-excursion
  10136. (org-uniquify
  10137. (delq nil
  10138. (apply #'append
  10139. (mapcar
  10140. (lambda (file)
  10141. (set-buffer (find-file-noselect file))
  10142. (org--tag-add-to-alist
  10143. (org-get-buffer-tags)
  10144. (mapcar (lambda (x)
  10145. (and (stringp (car-safe x))
  10146. (list (car-safe x))))
  10147. org-current-tag-alist)))
  10148. (if (car-safe files) files
  10149. (org-agenda-files))))))))
  10150. (defun org-make-tags-matcher (match &optional only-local-tags)
  10151. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10152. Returns a cons of the selection string MATCH and a function
  10153. implementing the matcher.
  10154. The matcher is to be called at an Org entry, with point on the
  10155. headline, and returns non-nil if the entry matches the selection
  10156. string MATCH. It must be called with three arguments: the TODO
  10157. keyword at the entry (or nil if none), the list of all tags at
  10158. the entry including inherited ones and the reduced level of the
  10159. headline. Additionally, the category of the entry, if any, must
  10160. be specified as the text property `org-category' on the headline.
  10161. This function sets the variable `org--matcher-tags-todo-only' to
  10162. a non-nil value if the matcher restricts matching to TODO
  10163. entries, otherwise it is not touched.
  10164. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10165. table, only get buffer tags.
  10166. See also `org-scan-tags'."
  10167. (unless match
  10168. ;; Get a new match request, with completion against the global
  10169. ;; tags table and the local tags in current buffer.
  10170. (let ((org-last-tags-completion-table
  10171. (org--tag-add-to-alist
  10172. (org-get-buffer-tags)
  10173. (unless only-local-tags
  10174. (org-global-tags-completion-table)))))
  10175. (setq match
  10176. (completing-read
  10177. "Match: "
  10178. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10179. (let ((match0 match)
  10180. (re (concat
  10181. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10182. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10183. "\\([<>=]\\{1,2\\}\\)"
  10184. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10185. "\\|" org-tag-re "\\)"))
  10186. (start 0)
  10187. tagsmatch todomatch tagsmatcher todomatcher)
  10188. ;; Expand group tags.
  10189. (setq match (org-tags-expand match))
  10190. ;; Check if there is a TODO part of this match, which would be the
  10191. ;; part after a "/". To make sure that this slash is not part of
  10192. ;; a property value to be matched against, we also check that
  10193. ;; there is no / after that slash. First, find the last slash.
  10194. (let ((s 0))
  10195. (while (string-match "/+" match s)
  10196. (setq start (match-beginning 0))
  10197. (setq s (match-end 0))))
  10198. (if (and (string-match "/+" match start)
  10199. (not (string-match-p "\"" match start)))
  10200. ;; Match contains also a TODO-matching request.
  10201. (progn
  10202. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10203. (setq todomatch (substring match (match-end 0)))
  10204. (when (string-prefix-p "!" todomatch)
  10205. (setq org--matcher-tags-todo-only t)
  10206. (setq todomatch (substring todomatch 1)))
  10207. (when (string-match "\\`\\s-*\\'" todomatch)
  10208. (setq todomatch nil)))
  10209. ;; Only matching tags.
  10210. (setq tagsmatch match)
  10211. (setq todomatch nil))
  10212. ;; Make the tags matcher.
  10213. (when (org-string-nw-p tagsmatch)
  10214. (let ((orlist nil)
  10215. (orterms (org-split-string tagsmatch "|"))
  10216. term)
  10217. (while (setq term (pop orterms))
  10218. (while (and (equal (substring term -1) "\\") orterms)
  10219. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10220. (while (string-match re term)
  10221. (let* ((rest (substring term (match-end 0)))
  10222. (minus (and (match-end 1)
  10223. (equal (match-string 1 term) "-")))
  10224. (tag (save-match-data
  10225. (replace-regexp-in-string
  10226. "\\\\-" "-" (match-string 2 term))))
  10227. (regexp (eq (string-to-char tag) ?{))
  10228. (levelp (match-end 4))
  10229. (propp (match-end 5))
  10230. (mm
  10231. (cond
  10232. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10233. (levelp
  10234. `(,(org-op-to-function (match-string 3 term))
  10235. level
  10236. ,(string-to-number (match-string 4 term))))
  10237. (propp
  10238. (let* ((gv (pcase (upcase (match-string 5 term))
  10239. ("CATEGORY"
  10240. '(org-get-category (point)))
  10241. ("TODO" 'todo)
  10242. (p `(org-cached-entry-get nil ,p))))
  10243. (pv (match-string 7 term))
  10244. (regexp (eq (string-to-char pv) ?{))
  10245. (strp (eq (string-to-char pv) ?\"))
  10246. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10247. (po (org-op-to-function (match-string 6 term)
  10248. (if timep 'time strp))))
  10249. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10250. (when timep (setq pv (org-matcher-time pv)))
  10251. (cond ((and regexp (eq po '/=))
  10252. `(not (string-match ,pv (or ,gv ""))))
  10253. (regexp `(string-match ,pv (or ,gv "")))
  10254. (strp `(,po (or ,gv "") ,pv))
  10255. (t
  10256. `(,po
  10257. (string-to-number (or ,gv ""))
  10258. ,(string-to-number pv))))))
  10259. (t `(member ,tag tags-list)))))
  10260. (push (if minus `(not ,mm) mm) tagsmatcher)
  10261. (setq term rest)))
  10262. (push `(and ,@tagsmatcher) orlist)
  10263. (setq tagsmatcher nil))
  10264. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10265. ;; Make the TODO matcher.
  10266. (when (org-string-nw-p todomatch)
  10267. (let ((orlist nil))
  10268. (dolist (term (org-split-string todomatch "|"))
  10269. (while (string-match re term)
  10270. (let* ((minus (and (match-end 1)
  10271. (equal (match-string 1 term) "-")))
  10272. (kwd (match-string 2 term))
  10273. (regexp (eq (string-to-char kwd) ?{))
  10274. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10275. `(equal todo ,kwd))))
  10276. (push (if minus `(not ,mm) mm) todomatcher))
  10277. (setq term (substring term (match-end 0))))
  10278. (push (if (> (length todomatcher) 1)
  10279. (cons 'and todomatcher)
  10280. (car todomatcher))
  10281. orlist)
  10282. (setq todomatcher nil))
  10283. (setq todomatcher (cons 'or orlist))))
  10284. ;; Return the string and function of the matcher. If no
  10285. ;; tags-specific or todo-specific matcher exists, match
  10286. ;; everything.
  10287. (let ((matcher (if (and tagsmatcher todomatcher)
  10288. `(and ,tagsmatcher ,todomatcher)
  10289. (or tagsmatcher todomatcher t))))
  10290. (when org--matcher-tags-todo-only
  10291. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10292. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10293. (defun org--tags-expand-group (group tag-groups expanded)
  10294. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10295. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10296. an accumulator used in recursive calls."
  10297. (dolist (tag group)
  10298. (unless (member tag expanded)
  10299. (let ((group (assoc tag tag-groups)))
  10300. (push tag expanded)
  10301. (when group
  10302. (setq expanded
  10303. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10304. expanded)
  10305. (defun org-tags-expand (match &optional single-as-list)
  10306. "Expand group tags in MATCH.
  10307. This replaces every group tag in MATCH with a regexp tag search.
  10308. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10309. will be replaced like this:
  10310. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10311. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10312. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10313. Replacing by a regexp preserves the structure of the match.
  10314. E.g., this expansion
  10315. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10316. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10317. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10318. A group tag in MATCH can contain regular expressions of its own.
  10319. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10320. will be replaced like this:
  10321. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10322. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10323. assumed to be a single group tag, and the function will return
  10324. the list of tags in this group."
  10325. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10326. (let ((tag-groups
  10327. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10328. (cond
  10329. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10330. (org-group-tags
  10331. (let* ((case-fold-search t)
  10332. (tag-syntax org-mode-syntax-table)
  10333. (group-keys (mapcar #'car tag-groups))
  10334. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10335. (return-match match))
  10336. ;; Mark regexp-expressions in the match-expression so that we
  10337. ;; do not replace them later on.
  10338. (let ((s 0))
  10339. (while (string-match "{.+?}" return-match s)
  10340. (setq s (match-end 0))
  10341. (add-text-properties
  10342. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10343. ;; @ and _ are allowed as word-components in tags.
  10344. (modify-syntax-entry ?@ "w" tag-syntax)
  10345. (modify-syntax-entry ?_ "w" tag-syntax)
  10346. ;; For each tag token found in MATCH, compute a regexp and it
  10347. (with-syntax-table tag-syntax
  10348. (replace-regexp-in-string
  10349. key-regexp
  10350. (lambda (m)
  10351. (if (get-text-property (match-beginning 2) 'regexp m)
  10352. m ;regexp tag: ignore
  10353. (let* ((operator (match-string 1 m))
  10354. (tag-token (let ((tag (match-string 2 m)))
  10355. (list tag)))
  10356. regexp-tags regular-tags)
  10357. ;; Partition tags between regexp and regular tags.
  10358. ;; Remove curly bracket syntax from regexp tags.
  10359. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10360. (save-match-data
  10361. (if (string-match "{\\(.+?\\)}" tag)
  10362. (push (match-string 1 tag) regexp-tags)
  10363. (push tag regular-tags))))
  10364. ;; Replace tag token by the appropriate regexp.
  10365. ;; Regular tags need to be regexp-quoted, whereas
  10366. ;; regexp-tags are inserted as-is.
  10367. (let ((regular (regexp-opt regular-tags))
  10368. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10369. (concat operator
  10370. (cond
  10371. ((null regular-tags) (format "{%s}" regexp))
  10372. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10373. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10374. return-match
  10375. t t))))
  10376. (t match))))
  10377. (defun org-op-to-function (op &optional stringp)
  10378. "Turn an operator into the appropriate function."
  10379. (setq op
  10380. (cond
  10381. ((equal op "<" ) '(< org-string< org-time<))
  10382. ((equal op ">" ) '(> org-string> org-time>))
  10383. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10384. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10385. ((member op '("=" "==")) '(= string= org-time=))
  10386. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10387. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10388. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10389. (defvar org-tags-overlay (make-overlay 1 1))
  10390. (delete-overlay org-tags-overlay)
  10391. (defun org-add-prop-inherited (s)
  10392. (add-text-properties 0 (length s) '(inherited t) s)
  10393. s)
  10394. (defun org-toggle-tag (tag &optional onoff)
  10395. "Toggle the tag TAG for the current line.
  10396. If ONOFF is `on' or `off', don't toggle but set to this state."
  10397. (save-excursion
  10398. (org-back-to-heading t)
  10399. (let ((current
  10400. ;; Reverse the tags list so any new tag is appended to the
  10401. ;; current list of tags.
  10402. (nreverse (org-get-tags nil t)))
  10403. res)
  10404. (pcase onoff
  10405. (`off (setq current (delete tag current)))
  10406. ((or `on (guard (not (member tag current))))
  10407. (setq res t)
  10408. (cl-pushnew tag current :test #'equal))
  10409. (_ (setq current (delete tag current))))
  10410. (org-set-tags (nreverse current))
  10411. res)))
  10412. (defun org--align-tags-here (to-col)
  10413. "Align tags on the current headline to TO-COL.
  10414. Assume point is on a headline. Preserve point when aligning
  10415. tags."
  10416. (when (org-match-line org-tag-line-re)
  10417. (let* ((tags-start (match-beginning 1))
  10418. (blank-start (save-excursion
  10419. (goto-char tags-start)
  10420. (skip-chars-backward " \t")
  10421. (point)))
  10422. (new (max (if (>= to-col 0) to-col
  10423. (- (abs to-col) (string-width (match-string 1))))
  10424. ;; Introduce at least one space after the heading
  10425. ;; or the stars.
  10426. (save-excursion
  10427. (goto-char blank-start)
  10428. (1+ (current-column)))))
  10429. (current
  10430. (save-excursion (goto-char tags-start) (current-column)))
  10431. (origin (point-marker))
  10432. (column (current-column))
  10433. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10434. (when (/= new current)
  10435. (delete-region blank-start tags-start)
  10436. (goto-char blank-start)
  10437. (let ((indent-tabs-mode nil)) (indent-to new))
  10438. ;; Try to move back to original position. If point was in the
  10439. ;; blanks before the tags, ORIGIN marker is of no use because
  10440. ;; it now points to BLANK-START. Use COLUMN instead.
  10441. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10442. (defun org-set-tags-command (&optional arg)
  10443. "Set the tags for the current visible entry.
  10444. When called with `\\[universal-argument]' prefix argument ARG, \
  10445. realign all tags
  10446. in the current buffer.
  10447. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10448. unconditionally do not
  10449. offer the fast tag selection interface.
  10450. If a region is active, set tags in the region according to the
  10451. setting of `org-loop-over-headlines-in-active-region'.
  10452. This function is for interactive use only;
  10453. in Lisp code use `org-set-tags' instead."
  10454. (interactive "P")
  10455. (let ((org-use-fast-tag-selection
  10456. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10457. (cond
  10458. ((equal '(4) arg) (org-align-tags t))
  10459. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10460. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10461. (org-map-entries
  10462. #'org-set-tags-command
  10463. nil
  10464. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10465. 'region-start-level
  10466. 'region)
  10467. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10468. (t
  10469. (save-excursion
  10470. (org-back-to-heading)
  10471. (let* ((all-tags (org-get-tags))
  10472. (local-table (or org-current-tag-alist (org-get-buffer-tags)))
  10473. (table (setq org-last-tags-completion-table
  10474. (append
  10475. ;; Put local tags in front.
  10476. local-table
  10477. (cl-set-difference
  10478. (org--tag-add-to-alist
  10479. (and org-complete-tags-always-offer-all-agenda-tags
  10480. (org-global-tags-completion-table
  10481. (org-agenda-files)))
  10482. local-table)
  10483. local-table))))
  10484. (current-tags
  10485. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10486. all-tags))
  10487. (inherited-tags
  10488. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10489. all-tags))
  10490. (tags
  10491. (replace-regexp-in-string
  10492. ;; Ignore all forbidden characters in tags.
  10493. "[^[:alnum:]_@#%]+" ":"
  10494. (if (or (eq t org-use-fast-tag-selection)
  10495. (and org-use-fast-tag-selection
  10496. (delq nil (mapcar #'cdr table))))
  10497. (org-fast-tag-selection
  10498. current-tags
  10499. inherited-tags
  10500. table
  10501. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10502. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10503. (crm-separator "[ \t]*:[ \t]*"))
  10504. (mapconcat #'identity
  10505. (completing-read-multiple
  10506. "Tags: "
  10507. org-last-tags-completion-table
  10508. nil nil (org-make-tag-string current-tags)
  10509. 'org-tags-history)
  10510. ":"))))))
  10511. (org-set-tags tags)))))
  10512. ;; `save-excursion' may not replace the point at the right
  10513. ;; position.
  10514. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10515. (looking-at-p " "))
  10516. (forward-char))))
  10517. (defun org-align-tags (&optional all)
  10518. "Align tags in current entry.
  10519. When optional argument ALL is non-nil, align all tags in the
  10520. visible part of the buffer."
  10521. (let ((get-indent-column
  10522. (lambda ()
  10523. (let ((offset (if (bound-and-true-p org-indent-mode)
  10524. (save-excursion
  10525. (org-back-to-heading-or-point-min)
  10526. (length
  10527. (get-text-property
  10528. (line-end-position)
  10529. 'line-prefix)))
  10530. 0)))
  10531. (+ org-tags-column
  10532. (if (> org-tags-column 0) (- offset) offset))))))
  10533. (if (and (not all) (org-at-heading-p))
  10534. (org--align-tags-here (funcall get-indent-column))
  10535. (save-excursion
  10536. (if all
  10537. (progn
  10538. (goto-char (point-min))
  10539. (while (re-search-forward org-tag-line-re nil t)
  10540. (org--align-tags-here (funcall get-indent-column))))
  10541. (org-back-to-heading t)
  10542. (org--align-tags-here (funcall get-indent-column)))))))
  10543. (defun org-set-tags (tags)
  10544. "Set the tags of the current entry to TAGS, replacing current tags.
  10545. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10546. If TAGS is nil or the empty string, all tags are removed.
  10547. This function assumes point is on a headline."
  10548. (org-with-wide-buffer
  10549. (org-fold-core-ignore-modifications
  10550. (let ((tags (pcase tags
  10551. ((pred listp) tags)
  10552. ((pred stringp) (split-string (org-trim tags) ":" t))
  10553. (_ (error "Invalid tag specification: %S" tags))))
  10554. (old-tags (org-get-tags nil t))
  10555. (tags-change? nil))
  10556. (when (functionp org-tags-sort-function)
  10557. (setq tags (sort tags org-tags-sort-function)))
  10558. (setq tags-change? (not (equal tags old-tags)))
  10559. (when tags-change?
  10560. ;; Delete previous tags and any trailing white space.
  10561. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10562. (line-end-position)))
  10563. (skip-chars-backward " \t")
  10564. (delete-region (point) (line-end-position))
  10565. ;; Deleting white spaces may break an otherwise empty headline.
  10566. ;; Re-introduce one space in this case.
  10567. (unless (org-at-heading-p) (insert " "))
  10568. (when tags
  10569. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10570. ;; When text is being inserted on an invisible region
  10571. ;; boundary, it can be inadvertently sucked into
  10572. ;; invisibility.
  10573. (unless (org-invisible-p (line-beginning-position))
  10574. (org-fold-region (point) (line-end-position) nil 'outline))))
  10575. ;; Align tags, if any.
  10576. (when tags (org-align-tags))
  10577. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10578. (defun org-change-tag-in-region (beg end tag off)
  10579. "Add or remove TAG for each entry in the region.
  10580. This works in the agenda, and also in an Org buffer."
  10581. (interactive
  10582. (list (region-beginning) (region-end)
  10583. (let ((org-last-tags-completion-table
  10584. (if (derived-mode-p 'org-mode)
  10585. (org--tag-add-to-alist
  10586. (org-get-buffer-tags)
  10587. (org-global-tags-completion-table))
  10588. (org-global-tags-completion-table))))
  10589. (completing-read
  10590. "Tag: " org-last-tags-completion-table nil nil nil
  10591. 'org-tags-history))
  10592. (progn
  10593. (message "[s]et or [r]emove? ")
  10594. (equal (read-char-exclusive) ?r))))
  10595. (deactivate-mark)
  10596. (let ((agendap (equal major-mode 'org-agenda-mode))
  10597. l1 l2 m buf pos newhead (cnt 0))
  10598. (goto-char end)
  10599. (setq l2 (1- (org-current-line)))
  10600. (goto-char beg)
  10601. (setq l1 (org-current-line))
  10602. (cl-loop for l from l1 to l2 do
  10603. (org-goto-line l)
  10604. (setq m (get-text-property (point) 'org-hd-marker))
  10605. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10606. (and agendap m))
  10607. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10608. pos (if agendap m (point)))
  10609. (with-current-buffer buf
  10610. (save-excursion
  10611. (save-restriction
  10612. (goto-char pos)
  10613. (setq cnt (1+ cnt))
  10614. (org-toggle-tag tag (if off 'off 'on))
  10615. (setq newhead (org-get-heading)))))
  10616. (and agendap (org-agenda-change-all-lines newhead m))))
  10617. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10618. (defun org-tags-completion-function (string _predicate &optional flag)
  10619. "Complete tag STRING.
  10620. FLAG specifies the type of completion operation to perform. This
  10621. function is passed as a collection function to `completing-read',
  10622. which see."
  10623. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10624. (confirm (lambda (x) (stringp (car x))))
  10625. (prefix ""))
  10626. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10627. (setq prefix (match-string 1 string))
  10628. (setq string (match-string 2 string)))
  10629. (pcase flag
  10630. (`t (all-completions string org-last-tags-completion-table confirm))
  10631. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10632. (`nil
  10633. (pcase (try-completion string org-last-tags-completion-table confirm)
  10634. ((and completion (pred stringp))
  10635. (concat prefix
  10636. completion
  10637. (if (and org-add-colon-after-tag-completion
  10638. (assoc completion org-last-tags-completion-table))
  10639. ":"
  10640. "")))
  10641. (completion completion)))
  10642. (_ nil))))
  10643. (defun org-fast-tag-insert (kwd tags face &optional end)
  10644. "Insert KWD, and the TAGS, the latter with face FACE.
  10645. Also insert END."
  10646. (insert (format "%-12s" (concat kwd ":"))
  10647. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10648. (or end "")))
  10649. (defun org-fast-tag-show-exit (flag)
  10650. (save-excursion
  10651. (org-goto-line 3)
  10652. (when (re-search-forward "[ \t]+Next change exits" (line-end-position) t)
  10653. (replace-match ""))
  10654. (when flag
  10655. (end-of-line 1)
  10656. (org-move-to-column (- (window-width) 19) t)
  10657. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10658. (defun org-set-current-tags-overlay (current prefix)
  10659. "Add an overlay to CURRENT tag with PREFIX."
  10660. (let ((s (org-make-tag-string current)))
  10661. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10662. (org-overlay-display org-tags-overlay (concat prefix s))))
  10663. (defvar org-last-tag-selection-key nil)
  10664. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10665. "Fast tag selection with single keys.
  10666. CURRENT is the current list of tags in the headline, INHERITED is the
  10667. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10668. possibly with grouping information. TODO-TABLE is a similar table with
  10669. TODO keywords, should these have keys assigned to them.
  10670. If the keys are nil, a-z are automatically assigned.
  10671. Returns the new tags string, or nil to not change the current settings."
  10672. (let* ((fulltable (append table todo-table))
  10673. (maxlen (if (null fulltable) 0
  10674. (apply #'max
  10675. (mapcar (lambda (x)
  10676. (if (stringp (car x)) (string-width (car x))
  10677. 0))
  10678. fulltable))))
  10679. (buf (current-buffer))
  10680. (expert (eq org-fast-tag-selection-single-key 'expert))
  10681. (tab-tags nil)
  10682. (fwidth (+ maxlen 3 1 3))
  10683. (ncol (/ (- (window-width) 4) fwidth))
  10684. (i-face 'org-done)
  10685. (c-face 'org-todo)
  10686. tg cnt e c char c1 c2 ntable tbl rtn
  10687. ov-start ov-end ov-prefix
  10688. (exit-after-next org-fast-tag-selection-single-key)
  10689. (done-keywords org-done-keywords)
  10690. groups ingroup intaggroup)
  10691. (save-excursion
  10692. (beginning-of-line)
  10693. (if (looking-at org-tag-line-re)
  10694. (setq ov-start (match-beginning 1)
  10695. ov-end (match-end 1)
  10696. ov-prefix "")
  10697. (setq ov-start (1- (line-end-position))
  10698. ov-end (1+ ov-start))
  10699. (skip-chars-forward "^\n\r")
  10700. (setq ov-prefix
  10701. (concat
  10702. (buffer-substring (1- (point)) (point))
  10703. (if (> (current-column) org-tags-column)
  10704. " "
  10705. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10706. (move-overlay org-tags-overlay ov-start ov-end)
  10707. (save-excursion
  10708. (save-window-excursion
  10709. (if expert
  10710. (set-buffer (get-buffer-create " *Org tags*"))
  10711. (delete-other-windows)
  10712. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10713. (org-switch-to-buffer-other-window " *Org tags*"))
  10714. (erase-buffer)
  10715. (setq-local org-done-keywords done-keywords)
  10716. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10717. (org-fast-tag-insert "Current" current c-face "\n\n")
  10718. (org-fast-tag-show-exit exit-after-next)
  10719. (org-set-current-tags-overlay current ov-prefix)
  10720. (setq tbl fulltable char ?a cnt 0)
  10721. (while (setq e (pop tbl))
  10722. (cond
  10723. ((eq (car e) :startgroup)
  10724. (push '() groups) (setq ingroup t)
  10725. (unless (zerop cnt)
  10726. (setq cnt 0)
  10727. (insert "\n"))
  10728. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10729. ((eq (car e) :endgroup)
  10730. (setq ingroup nil cnt 0)
  10731. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10732. ((eq (car e) :startgrouptag)
  10733. (setq intaggroup t)
  10734. (unless (zerop cnt)
  10735. (setq cnt 0)
  10736. (insert "\n"))
  10737. (insert "[ "))
  10738. ((eq (car e) :endgrouptag)
  10739. (setq intaggroup nil cnt 0)
  10740. (insert "]\n"))
  10741. ((equal e '(:newline))
  10742. (unless (zerop cnt)
  10743. (setq cnt 0)
  10744. (insert "\n")
  10745. (setq e (car tbl))
  10746. (while (equal (car tbl) '(:newline))
  10747. (insert "\n")
  10748. (setq tbl (cdr tbl)))))
  10749. ((equal e '(:grouptags))
  10750. (delete-char -3)
  10751. (insert " : "))
  10752. (t
  10753. (setq tg (copy-sequence (car e)) c2 nil)
  10754. (if (cdr e)
  10755. (setq c (cdr e))
  10756. ;; automatically assign a character.
  10757. (setq c1 (string-to-char
  10758. (downcase (substring
  10759. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10760. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10761. (while (or (rassoc char ntable) (rassoc char table))
  10762. (setq char (1+ char)))
  10763. (setq c2 c1))
  10764. (setq c (or c2
  10765. (if (> char ?~)
  10766. ?\s
  10767. char)))
  10768. ;; Consider characters A-Z after a-z.
  10769. (if (equal char ?z)
  10770. (setq char ?A)))
  10771. (when ingroup (push tg (car groups)))
  10772. (setq tg (org-add-props tg nil 'face
  10773. (cond
  10774. ((not (assoc tg table))
  10775. (org-get-todo-face tg))
  10776. ((member tg current) c-face)
  10777. ((member tg inherited) i-face))))
  10778. (when (equal (caar tbl) :grouptags)
  10779. (org-add-props tg nil 'face 'org-tag-group))
  10780. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10781. (insert "[" c "] " tg (make-string
  10782. (- fwidth 4 (length tg)) ?\ ))
  10783. (push (cons tg c) ntable)
  10784. (when (= (cl-incf cnt) ncol)
  10785. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10786. (insert "\n")
  10787. (when (or ingroup intaggroup) (insert " ")))
  10788. (setq cnt 0)))))
  10789. (setq ntable (nreverse ntable))
  10790. (insert "\n")
  10791. (goto-char (point-min))
  10792. (unless expert (org-fit-window-to-buffer))
  10793. (setq rtn
  10794. (catch 'exit
  10795. (while t
  10796. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10797. (if (not groups) "no " "")
  10798. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10799. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10800. (setq org-last-tag-selection-key c)
  10801. (cond
  10802. ((= c ?\r) (throw 'exit t))
  10803. ((= c ?!)
  10804. (setq groups (not groups))
  10805. (goto-char (point-min))
  10806. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10807. ((= c ?\C-c)
  10808. (if (not expert)
  10809. (org-fast-tag-show-exit
  10810. (setq exit-after-next (not exit-after-next)))
  10811. (setq expert nil)
  10812. (delete-other-windows)
  10813. (set-window-buffer (split-window-vertically) " *Org tags*")
  10814. (org-switch-to-buffer-other-window " *Org tags*")
  10815. (org-fit-window-to-buffer)))
  10816. ((or (= c ?\C-g)
  10817. (and (= c ?q) (not (rassoc c ntable))))
  10818. (delete-overlay org-tags-overlay)
  10819. (setq quit-flag t))
  10820. ((= c ?\ )
  10821. (setq current nil)
  10822. (when exit-after-next (setq exit-after-next 'now)))
  10823. ((= c ?\t)
  10824. (condition-case nil
  10825. (unless tab-tags
  10826. (setq tab-tags
  10827. (delq nil
  10828. (mapcar (lambda (x)
  10829. (let ((item (car-safe x)))
  10830. (and (stringp item)
  10831. (list item))))
  10832. (org--tag-add-to-alist
  10833. (with-current-buffer buf
  10834. (org-get-buffer-tags))
  10835. table))))))
  10836. (setq tg (completing-read "Tag: " tab-tags))
  10837. (when (string-match "\\S-" tg)
  10838. (cl-pushnew (list tg) tab-tags :test #'equal)
  10839. (if (member tg current)
  10840. (setq current (delete tg current))
  10841. (push tg current)))
  10842. (when exit-after-next (setq exit-after-next 'now)))
  10843. ((setq e (rassoc c todo-table) tg (car e))
  10844. (with-current-buffer buf
  10845. (save-excursion (org-todo tg)))
  10846. (when exit-after-next (setq exit-after-next 'now)))
  10847. ((setq e (rassoc c ntable) tg (car e))
  10848. (if (member tg current)
  10849. (setq current (delete tg current))
  10850. (cl-loop for g in groups do
  10851. (when (member tg g)
  10852. (dolist (x g) (setq current (delete x current)))))
  10853. (push tg current))
  10854. (when exit-after-next (setq exit-after-next 'now))))
  10855. ;; Create a sorted list
  10856. (setq current
  10857. (sort current
  10858. (lambda (a b)
  10859. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10860. (when (eq exit-after-next 'now) (throw 'exit t))
  10861. (goto-char (point-min))
  10862. (beginning-of-line 2)
  10863. (delete-region (point) (line-end-position))
  10864. (org-fast-tag-insert "Current" current c-face)
  10865. (org-set-current-tags-overlay current ov-prefix)
  10866. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10867. (while (re-search-forward tag-re nil t)
  10868. (let ((tag (match-string 1)))
  10869. (add-text-properties
  10870. (match-beginning 1) (match-end 1)
  10871. (list 'face
  10872. (cond
  10873. ((member tag current) c-face)
  10874. ((member tag inherited) i-face)
  10875. (t 'default)))))))
  10876. (goto-char (point-min)))))
  10877. (delete-overlay org-tags-overlay)
  10878. (if rtn
  10879. (mapconcat 'identity current ":")
  10880. nil)))))
  10881. (defun org-make-tag-string (tags)
  10882. "Return string associated to TAGS.
  10883. TAGS is a list of strings."
  10884. (if (null tags) ""
  10885. (format ":%s:" (mapconcat #'identity tags ":"))))
  10886. (defun org--get-local-tags ()
  10887. "Return list of tags for the current headline.
  10888. Assume point is at the beginning of the headline."
  10889. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10890. (cached-tags (org-element-property :tags cached)))
  10891. (if cached
  10892. ;; If we do not explicitly copy the result, reference would
  10893. ;; be returned and cache element might be modified directly.
  10894. (mapcar #'copy-sequence cached-tags)
  10895. ;; Parse tags manually.
  10896. (and (looking-at org-tag-line-re)
  10897. (split-string (match-string-no-properties 2) ":" t)))))
  10898. (defun org-get-tags (&optional pos-or-element local)
  10899. "Get the list of tags specified in the current headline.
  10900. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10901. POS.
  10902. According to `org-use-tag-inheritance', tags may be inherited
  10903. from parent headlines, and from the whole document, through
  10904. `org-file-tags'. In this case, the returned list of tags
  10905. contains tags in this order: file tags, tags inherited from
  10906. parent headlines, local tags. If a tag appears multiple times,
  10907. only the most local tag is returned.
  10908. However, when optional argument LOCAL is non-nil, only return
  10909. tags specified at the headline.
  10910. Inherited tags have the `inherited' text property."
  10911. (save-match-data
  10912. (if (and org-trust-scanner-tags
  10913. (or (not pos-or-element) (eq pos-or-element (point)))
  10914. (not local))
  10915. org-scanner-tags
  10916. (org-with-point-at (unless (org-element-type pos-or-element)
  10917. (or pos-or-element (point)))
  10918. (unless (or (org-element-type pos-or-element)
  10919. (org-before-first-heading-p))
  10920. (org-back-to-heading t))
  10921. (let ((ltags (if (org-element-type pos-or-element)
  10922. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10923. (org--get-local-tags)))
  10924. itags)
  10925. (if (or local (not org-use-tag-inheritance)) ltags
  10926. (let ((cached (and (org-element--cache-active-p)
  10927. (if (org-element-type pos-or-element)
  10928. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10929. (org-element-at-point nil 'cached)))))
  10930. (if cached
  10931. (while (setq cached (org-element-property :parent cached))
  10932. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10933. ;; If we do explicitly copy the result, reference would
  10934. ;; be returned and cache element might be modified directly.
  10935. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10936. itags)))
  10937. (while (org-up-heading-safe)
  10938. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10939. (org--get-local-tags))
  10940. itags)))))
  10941. (setq itags (append org-file-tags itags))
  10942. (nreverse
  10943. (delete-dups
  10944. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10945. (defun org-get-buffer-tags ()
  10946. "Get a table of all tags used in the buffer, for completion."
  10947. (if (org-element--cache-active-p)
  10948. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10949. ;; search.
  10950. (let ((hashed (make-hash-table :test #'equal)))
  10951. (org-element-cache-map
  10952. (lambda (el)
  10953. (dolist (tag (org-element-property :tags el))
  10954. ;; Do not carry over the text properties. They may look
  10955. ;; ugly in the completion.
  10956. (puthash (list (substring-no-properties tag)) t hashed))))
  10957. (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  10958. (hash-table-keys hashed))
  10959. (org-with-point-at 1
  10960. (let (tags)
  10961. (while (re-search-forward org-tag-line-re nil t)
  10962. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10963. tags)))
  10964. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10965. ;;;; The mapping API
  10966. (defvar org-agenda-skip-comment-trees)
  10967. (defvar org-agenda-skip-function)
  10968. (defun org-map-entries (func &optional match scope &rest skip)
  10969. "Call FUNC at each headline selected by MATCH in SCOPE.
  10970. FUNC is a function or a Lisp form. The function will be called without
  10971. arguments, with the cursor positioned at the beginning of the headline.
  10972. The return values of all calls to the function will be collected and
  10973. returned as a list.
  10974. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10975. does not need to preserve point. After evaluation, the cursor will be
  10976. moved to the end of the line (presumably of the headline of the
  10977. processed entry) and search continues from there. Under some
  10978. circumstances, this may not produce the wanted results. For example,
  10979. if you have removed (e.g. archived) the current (sub)tree it could
  10980. mean that the next entry will be skipped entirely. In such cases, you
  10981. can specify the position from where search should continue by making
  10982. FUNC set the variable `org-map-continue-from' to the desired buffer
  10983. position.
  10984. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10985. Only headlines that are matched by this query will be considered during
  10986. the iteration. When MATCH is nil or t, all headlines will be
  10987. visited by the iteration.
  10988. SCOPE determines the scope of this command. It can be any of:
  10989. nil The current buffer, respecting the restriction if any
  10990. tree The subtree started with the entry at point
  10991. region The entries within the active region, if any
  10992. region-start-level
  10993. The entries within the active region, but only those at
  10994. the same level than the first one.
  10995. file The current buffer, without restriction
  10996. file-with-archives
  10997. The current buffer, and any archives associated with it
  10998. agenda All agenda files
  10999. agenda-with-archives
  11000. All agenda files with any archive files associated with them
  11001. \(file1 file2 ...)
  11002. If this is a list, all files in the list will be scanned
  11003. The remaining args are treated as settings for the skipping facilities of
  11004. the scanner. The following items can be given here:
  11005. archive skip trees with the archive tag
  11006. comment skip trees with the COMMENT keyword
  11007. function or Emacs Lisp form:
  11008. will be used as value for `org-agenda-skip-function', so
  11009. whenever the function returns a position, FUNC will not be
  11010. called for that entry and search will continue from the
  11011. position returned
  11012. If your function needs to retrieve the tags including inherited tags
  11013. at the *current* entry, you can use the value of the variable
  11014. `org-scanner-tags' which will be much faster than getting the value
  11015. with `org-get-tags'. If your function gets properties with
  11016. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11017. to t around the call to `org-entry-properties' to get the same speedup.
  11018. Note that if your function moves around to retrieve tags and properties at
  11019. a *different* entry, you cannot use these techniques."
  11020. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11021. (not (org-region-active-p)))
  11022. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11023. (org-agenda-skip-archived-trees (memq 'archive skip))
  11024. (org-agenda-skip-comment-trees (memq 'comment skip))
  11025. (org-agenda-skip-function
  11026. (car (org-delete-all '(comment archive) skip)))
  11027. (org-tags-match-list-sublevels t)
  11028. (start-level (eq scope 'region-start-level))
  11029. matcher res
  11030. org-todo-keywords-for-agenda
  11031. org-done-keywords-for-agenda
  11032. org-todo-keyword-alist-for-agenda
  11033. org-tag-alist-for-agenda
  11034. org--matcher-tags-todo-only)
  11035. (cond
  11036. ((eq match t) (setq matcher t))
  11037. ((eq match nil) (setq matcher t))
  11038. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11039. (save-excursion
  11040. (save-restriction
  11041. (cond ((eq scope 'tree)
  11042. (org-back-to-heading t)
  11043. (org-narrow-to-subtree)
  11044. (setq scope nil))
  11045. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11046. (org-region-active-p))
  11047. ;; If needed, set start-level to a string like "2"
  11048. (when start-level
  11049. (save-excursion
  11050. (goto-char (region-beginning))
  11051. (unless (org-at-heading-p) (outline-next-heading))
  11052. (setq start-level (org-current-level))))
  11053. (narrow-to-region (region-beginning)
  11054. (save-excursion
  11055. (goto-char (region-end))
  11056. (unless (and (bolp) (org-at-heading-p))
  11057. (outline-next-heading))
  11058. (point)))
  11059. (setq scope nil)))
  11060. (if (not scope)
  11061. (progn
  11062. (org-agenda-prepare-buffers
  11063. (and buffer-file-name (list buffer-file-name)))
  11064. (setq res
  11065. (org-scan-tags
  11066. func matcher org--matcher-tags-todo-only start-level)))
  11067. ;; Get the right scope
  11068. (cond
  11069. ((and scope (listp scope) (symbolp (car scope)))
  11070. (setq scope (eval scope t)))
  11071. ((eq scope 'agenda)
  11072. (setq scope (org-agenda-files t)))
  11073. ((eq scope 'agenda-with-archives)
  11074. (setq scope (org-agenda-files t))
  11075. (setq scope (org-add-archive-files scope)))
  11076. ((eq scope 'file)
  11077. (setq scope (and buffer-file-name (list buffer-file-name))))
  11078. ((eq scope 'file-with-archives)
  11079. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11080. (org-agenda-prepare-buffers scope)
  11081. (dolist (file scope)
  11082. (with-current-buffer (org-find-base-buffer-visiting file)
  11083. (org-with-wide-buffer
  11084. (goto-char (point-min))
  11085. (setq res
  11086. (append
  11087. res
  11088. (org-scan-tags
  11089. func matcher org--matcher-tags-todo-only)))))))))
  11090. res)))
  11091. ;;; Properties API
  11092. (defconst org-special-properties
  11093. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11094. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11095. "The special properties valid in Org mode.
  11096. These are properties that are not defined in the property drawer,
  11097. but in some other way.")
  11098. (defconst org-default-properties
  11099. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11100. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11101. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11102. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11103. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11104. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11105. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS"
  11106. "ORG-IMAGE-ACTUAL-WIDTH")
  11107. "Some properties that are used by Org mode for various purposes.
  11108. Being in this list makes sure that they are offered for completion.")
  11109. (defun org--valid-property-p (property)
  11110. "Non-nil when string PROPERTY is a valid property name."
  11111. (not
  11112. (or (equal property "")
  11113. (string-match-p "\\s-" property))))
  11114. (defun org--update-property-plist (key val props)
  11115. "Associate KEY to VAL in alist PROPS.
  11116. Modifications are made by side-effect. Return new alist."
  11117. (let* ((appending (string= (substring key -1) "+"))
  11118. (key (if appending (substring key 0 -1) key))
  11119. (old (assoc-string key props t)))
  11120. (if (not old) (cons (cons key val) props)
  11121. (setcdr old (if appending (concat (cdr old) " " val) val))
  11122. props)))
  11123. (defun org-get-property-block (&optional beg force)
  11124. "Return the (beg . end) range of the body of the property drawer.
  11125. BEG is the beginning of the current subtree or the beginning of
  11126. the document if before the first headline. If it is not given,
  11127. it will be found. If the drawer does not exist, create it if
  11128. FORCE is non-nil, or return nil."
  11129. (org-with-wide-buffer
  11130. (let ((beg (cond (beg (goto-char beg))
  11131. ((or (not (featurep 'org-inlinetask))
  11132. (org-inlinetask-in-task-p))
  11133. (org-back-to-heading-or-point-min t) (point))
  11134. (t (org-with-limited-levels
  11135. (org-back-to-heading-or-point-min t))
  11136. (point)))))
  11137. ;; Move point to its position according to its positional rules.
  11138. (cond ((org-before-first-heading-p)
  11139. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11140. (t (forward-line)
  11141. (when (looking-at-p org-planning-line-re) (forward-line))))
  11142. (cond ((looking-at org-property-drawer-re)
  11143. (forward-line)
  11144. (cons (point) (progn (goto-char (match-end 0))
  11145. (line-beginning-position))))
  11146. (force
  11147. (goto-char beg)
  11148. (org-insert-property-drawer)
  11149. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11150. (line-beginning-position))))
  11151. (cons pos pos)))))))
  11152. (defun org-at-property-drawer-p ()
  11153. "Non-nil when point is at the first line of a property drawer."
  11154. (org-with-wide-buffer
  11155. (beginning-of-line)
  11156. (and (looking-at org-property-drawer-re)
  11157. (or (bobp)
  11158. (progn
  11159. (forward-line -1)
  11160. (cond ((org-at-heading-p))
  11161. ((looking-at org-planning-line-re)
  11162. (forward-line -1)
  11163. (org-at-heading-p))
  11164. ((looking-at org-comment-regexp)
  11165. (forward-line -1)
  11166. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11167. (forward-line -1))
  11168. (looking-at org-comment-regexp))
  11169. (t nil)))))))
  11170. (defun org-at-property-p ()
  11171. "Non-nil when point is inside a property drawer.
  11172. See `org-property-re' for match data, if applicable."
  11173. (save-excursion
  11174. (beginning-of-line)
  11175. (and (looking-at org-property-re)
  11176. (let ((property-drawer (save-match-data (org-get-property-block))))
  11177. (and property-drawer
  11178. (>= (point) (car property-drawer))
  11179. (< (point) (cdr property-drawer)))))))
  11180. (defun org-property-action ()
  11181. "Do an action on properties."
  11182. (interactive)
  11183. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11184. (let ((c (read-char-exclusive)))
  11185. (cl-case c
  11186. (?s (call-interactively #'org-set-property))
  11187. (?d (call-interactively #'org-delete-property))
  11188. (?D (call-interactively #'org-delete-property-globally))
  11189. (?c (call-interactively #'org-compute-property-at-point))
  11190. (otherwise (user-error "No such property action %c" c)))))
  11191. (defun org-inc-effort ()
  11192. "Increment the value of the effort property in the current entry."
  11193. (interactive)
  11194. (org-set-effort t))
  11195. (defvar org-clock-effort) ; Defined in org-clock.el.
  11196. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11197. (defun org-set-effort (&optional increment value)
  11198. "Set the effort property of the current entry.
  11199. If INCREMENT is non-nil, set the property to the next allowed
  11200. value. Otherwise, if optional argument VALUE is provided, use
  11201. it. Eventually, prompt for the new value if none of the previous
  11202. variables is set."
  11203. (interactive "P")
  11204. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11205. (current (org-entry-get nil org-effort-property))
  11206. (value
  11207. (cond
  11208. (increment
  11209. (unless allowed (user-error "Allowed effort values are not set"))
  11210. (or (cl-caadr (member (list current) allowed))
  11211. (user-error "Unknown value %S among allowed values" current)))
  11212. (value
  11213. (if (stringp value) value
  11214. (error "Invalid effort value: %S" value)))
  11215. (t
  11216. (let ((must-match
  11217. (and allowed
  11218. (not (get-text-property 0 'org-unrestricted
  11219. (caar allowed))))))
  11220. (completing-read "Effort: " allowed nil must-match))))))
  11221. ;; Test whether the value can be interpreted as a duration before
  11222. ;; inserting it in the buffer:
  11223. (org-duration-to-minutes value)
  11224. ;; Maybe update the effort value:
  11225. (unless (equal current value)
  11226. (org-entry-put nil org-effort-property value))
  11227. (unless (org-element--cache-active-p)
  11228. (org-refresh-property '((effort . identity)
  11229. (effort-minutes . org-duration-to-minutes))
  11230. value))
  11231. (when (equal (org-get-heading t t t t)
  11232. (bound-and-true-p org-clock-current-task))
  11233. (setq org-clock-effort value)
  11234. (org-clock-update-mode-line))
  11235. (message "%s is now %s" org-effort-property value)))
  11236. (defun org-entry-properties (&optional pom which)
  11237. "Get all properties of the current entry.
  11238. When POM is a buffer position, get all properties from the entry
  11239. there instead.
  11240. This includes the TODO keyword, the tags, time strings for
  11241. deadline, scheduled, and clocking, and any additional properties
  11242. defined in the entry.
  11243. If WHICH is nil or `all', get all properties. If WHICH is
  11244. `special' or `standard', only get that subclass. If WHICH is
  11245. a string, only get that property.
  11246. Return value is an alist. Keys are properties, as upcased
  11247. strings."
  11248. (org-with-point-at pom
  11249. (when (and (derived-mode-p 'org-mode)
  11250. (org-back-to-heading-or-point-min t))
  11251. (catch 'exit
  11252. (let* ((beg (point))
  11253. (specific (and (stringp which) (upcase which)))
  11254. (which (cond ((not specific) which)
  11255. ((member specific org-special-properties) 'special)
  11256. (t 'standard)))
  11257. props)
  11258. ;; Get the special properties, like TODO and TAGS.
  11259. (when (memq which '(nil all special))
  11260. (when (or (not specific) (string= specific "CLOCKSUM"))
  11261. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11262. (when clocksum
  11263. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11264. props)))
  11265. (when specific (throw 'exit props)))
  11266. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11267. (let ((clocksumt (get-text-property (point)
  11268. :org-clock-minutes-today)))
  11269. (when clocksumt
  11270. (push (cons "CLOCKSUM_T"
  11271. (org-duration-from-minutes clocksumt))
  11272. props)))
  11273. (when specific (throw 'exit props)))
  11274. (when (or (not specific) (string= specific "ITEM"))
  11275. (let ((case-fold-search nil))
  11276. (when (looking-at org-complex-heading-regexp)
  11277. (push (cons "ITEM"
  11278. (let ((title (match-string-no-properties 4)))
  11279. (if (org-string-nw-p title)
  11280. (org-remove-tabs title)
  11281. "")))
  11282. props)))
  11283. (when specific (throw 'exit props)))
  11284. (when (or (not specific) (string= specific "TODO"))
  11285. (let ((case-fold-search nil))
  11286. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11287. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11288. (when specific (throw 'exit props)))
  11289. (when (or (not specific) (string= specific "PRIORITY"))
  11290. (push (cons "PRIORITY"
  11291. (if (looking-at org-priority-regexp)
  11292. (match-string-no-properties 2)
  11293. (char-to-string org-priority-default)))
  11294. props)
  11295. (when specific (throw 'exit props)))
  11296. (when (or (not specific) (string= specific "FILE"))
  11297. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11298. props)
  11299. (when specific (throw 'exit props)))
  11300. (when (or (not specific) (string= specific "TAGS"))
  11301. (let ((tags (org-get-tags nil t)))
  11302. (when tags
  11303. (push (cons "TAGS" (org-make-tag-string tags))
  11304. props)))
  11305. (when specific (throw 'exit props)))
  11306. (when (or (not specific) (string= specific "ALLTAGS"))
  11307. (let ((tags (org-get-tags)))
  11308. (when tags
  11309. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11310. props)))
  11311. (when specific (throw 'exit props)))
  11312. (when (or (not specific) (string= specific "BLOCKED"))
  11313. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11314. (when specific (throw 'exit props)))
  11315. (when (or (not specific)
  11316. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11317. (forward-line)
  11318. (when (looking-at-p org-planning-line-re)
  11319. (end-of-line)
  11320. (let ((bol (line-beginning-position))
  11321. ;; Backward compatibility: time keywords used to
  11322. ;; be configurable (before 8.3). Make sure we
  11323. ;; get the correct keyword.
  11324. (key-assoc `(("CLOSED" . ,org-closed-string)
  11325. ("DEADLINE" . ,org-deadline-string)
  11326. ("SCHEDULED" . ,org-scheduled-string))))
  11327. (dolist (pair (if specific (list (assoc specific key-assoc))
  11328. key-assoc))
  11329. (save-excursion
  11330. (when (search-backward (cdr pair) bol t)
  11331. (goto-char (match-end 0))
  11332. (skip-chars-forward " \t")
  11333. (and (looking-at org-ts-regexp-both)
  11334. (push (cons (car pair)
  11335. (match-string-no-properties 0))
  11336. props)))))))
  11337. (when specific (throw 'exit props)))
  11338. (when (or (not specific)
  11339. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11340. (let ((find-ts
  11341. (lambda (end ts)
  11342. ;; Fix next time-stamp before END. TS is the
  11343. ;; list of time-stamps found so far.
  11344. (let ((ts ts)
  11345. (regexp (cond
  11346. ((string= specific "TIMESTAMP")
  11347. org-ts-regexp)
  11348. ((string= specific "TIMESTAMP_IA")
  11349. org-ts-regexp-inactive)
  11350. ((assoc "TIMESTAMP_IA" ts)
  11351. org-ts-regexp)
  11352. ((assoc "TIMESTAMP" ts)
  11353. org-ts-regexp-inactive)
  11354. (t org-ts-regexp-both))))
  11355. (catch 'next
  11356. (while (re-search-forward regexp end t)
  11357. (backward-char)
  11358. (let ((object (org-element-context)))
  11359. ;; Accept to match timestamps in node
  11360. ;; properties, too.
  11361. (when (memq (org-element-type object)
  11362. '(node-property timestamp))
  11363. (let ((type
  11364. (org-element-property :type object)))
  11365. (cond
  11366. ((and (memq type '(active active-range))
  11367. (not (equal specific "TIMESTAMP_IA")))
  11368. (unless (assoc "TIMESTAMP" ts)
  11369. (push (cons "TIMESTAMP"
  11370. (org-element-property
  11371. :raw-value object))
  11372. ts)
  11373. (when specific (throw 'exit ts))))
  11374. ((and (memq type '(inactive inactive-range))
  11375. (not (string= specific "TIMESTAMP")))
  11376. (unless (assoc "TIMESTAMP_IA" ts)
  11377. (push (cons "TIMESTAMP_IA"
  11378. (org-element-property
  11379. :raw-value object))
  11380. ts)
  11381. (when specific (throw 'exit ts))))))
  11382. ;; Both timestamp types are found,
  11383. ;; move to next part.
  11384. (when (= (length ts) 2) (throw 'next ts)))))
  11385. ts)))))
  11386. (goto-char beg)
  11387. ;; First look for timestamps within headline.
  11388. (let ((ts (funcall find-ts (line-end-position) nil)))
  11389. (if (= (length ts) 2) (setq props (nconc ts props))
  11390. ;; Then find timestamps in the section, skipping
  11391. ;; planning line.
  11392. (let ((end (save-excursion (outline-next-heading))))
  11393. (forward-line)
  11394. (when (looking-at-p org-planning-line-re) (forward-line))
  11395. (setq props (nconc (funcall find-ts end ts) props))))))))
  11396. ;; Get the standard properties, like :PROP:.
  11397. (when (memq which '(nil all standard))
  11398. ;; If we are looking after a specific property, delegate
  11399. ;; to `org-entry-get', which is faster. However, make an
  11400. ;; exception for "CATEGORY", since it can be also set
  11401. ;; through keywords (i.e. #+CATEGORY).
  11402. (if (and specific (not (equal specific "CATEGORY")))
  11403. (let ((value (org-entry-get beg specific nil t)))
  11404. (throw 'exit (and value (list (cons specific value)))))
  11405. (let ((range (org-get-property-block beg)))
  11406. (when range
  11407. (let ((end (cdr range)) seen-base)
  11408. (goto-char (car range))
  11409. ;; Unlike to `org--update-property-plist', we
  11410. ;; handle the case where base values is found
  11411. ;; after its extension. We also forbid standard
  11412. ;; properties to be named as special properties.
  11413. (while (re-search-forward org-property-re end t)
  11414. (let* ((key (upcase (match-string-no-properties 2)))
  11415. (extendp (string-match-p "\\+\\'" key))
  11416. (key-base (if extendp (substring key 0 -1) key))
  11417. (value (match-string-no-properties 3)))
  11418. (cond
  11419. ((member-ignore-case key-base org-special-properties))
  11420. (extendp
  11421. (setq props
  11422. (org--update-property-plist key value props)))
  11423. ((member key seen-base))
  11424. (t (push key seen-base)
  11425. (let ((p (assoc-string key props t)))
  11426. (if p (setcdr p (concat value " " (cdr p)))
  11427. (push (cons key value) props))))))))))))
  11428. (unless (assoc "CATEGORY" props)
  11429. (push (cons "CATEGORY" (org-get-category beg)) props)
  11430. (when (string= specific "CATEGORY") (throw 'exit props)))
  11431. ;; Return value.
  11432. props)))))
  11433. (defun org--property-local-values (property literal-nil &optional element)
  11434. "Return value for PROPERTY in current entry or ELEMENT.
  11435. Value is a list whose car is the base value for PROPERTY and cdr
  11436. a list of accumulated values. Return nil if neither is found in
  11437. the entry. Also return nil when PROPERTY is set to \"nil\",
  11438. unless LITERAL-NIL is non-nil."
  11439. (let ((element (or element
  11440. (and (org-element--cache-active-p)
  11441. (org-element-at-point nil 'cached)))))
  11442. (if element
  11443. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11444. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11445. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11446. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11447. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11448. (value (cons base-value extra-value)))
  11449. (and (not (equal value '(nil))) value))
  11450. (let ((range (org-get-property-block)))
  11451. (when range
  11452. (goto-char (car range))
  11453. (let* ((case-fold-search t)
  11454. (end (cdr range))
  11455. (value
  11456. ;; Base value.
  11457. (save-excursion
  11458. (let ((v (and (re-search-forward
  11459. (org-re-property property nil t) end t)
  11460. (match-string-no-properties 3))))
  11461. (list (if literal-nil v (org-not-nil v)))))))
  11462. ;; Find additional values.
  11463. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11464. (while (re-search-forward property+ end t)
  11465. (push (match-string-no-properties 3) value)))
  11466. ;; Return final values.
  11467. (and (not (equal value '(nil))) (nreverse value))))))))
  11468. (defun org--property-global-or-keyword-value (property literal-nil)
  11469. "Return value for PROPERTY as defined by global properties or by keyword.
  11470. Return value is a string. Return nil if property is not set
  11471. globally or by keyword. Also return nil when PROPERTY is set to
  11472. \"nil\", unless LITERAL-NIL is non-nil."
  11473. (let ((global
  11474. (cdr (or (assoc-string property org-keyword-properties t)
  11475. (assoc-string property org-global-properties t)
  11476. (assoc-string property org-global-properties-fixed t)))))
  11477. (if literal-nil global (org-not-nil global))))
  11478. (defun org-entry-get (pom property &optional inherit literal-nil)
  11479. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11480. If INHERIT is non-nil and the entry does not have the property,
  11481. then also check higher levels of the hierarchy. If INHERIT is
  11482. the symbol `selective', use inheritance only if the setting in
  11483. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11484. If the property is present but empty, the return value is the
  11485. empty string. If the property is not present at all, nil is
  11486. returned. In any other case, return the value as a string.
  11487. Search is case-insensitive.
  11488. If LITERAL-NIL is set, return the string value \"nil\" as
  11489. a string, do not interpret it as the list atom nil. This is used
  11490. for inheritance when a \"nil\" value can supersede a non-nil
  11491. value higher up the hierarchy."
  11492. (org-with-point-at pom
  11493. (cond
  11494. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11495. ;; We need a special property. Use `org-entry-properties' to
  11496. ;; retrieve it, but specify the wanted property.
  11497. (cdr (assoc-string property (org-entry-properties nil property))))
  11498. ((and inherit
  11499. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11500. (org-entry-get-with-inheritance property literal-nil))
  11501. (t
  11502. (let* ((local (org--property-local-values property literal-nil))
  11503. (value (and local (mapconcat #'identity
  11504. (delq nil local)
  11505. (org--property-get-separator property)))))
  11506. (if literal-nil value (org-not-nil value)))))))
  11507. (defun org-property-or-variable-value (var &optional inherit)
  11508. "Check if there is a property fixing the value of VAR.
  11509. If yes, return this value. If not, return the current value of the variable."
  11510. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11511. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11512. (read prop)
  11513. (symbol-value var))))
  11514. (defun org-entry-delete (pom property)
  11515. "Delete PROPERTY from entry at point-or-marker POM.
  11516. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11517. non-nil when a property was removed."
  11518. (org-with-point-at pom
  11519. (pcase (org-get-property-block)
  11520. (`(,begin . ,origin)
  11521. (let* ((end (copy-marker origin))
  11522. (re (org-re-property
  11523. (concat (regexp-quote property) "\\+?") t t)))
  11524. (goto-char begin)
  11525. (while (re-search-forward re end t)
  11526. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11527. ;; If drawer is empty, remove it altogether.
  11528. (when (= begin end)
  11529. (delete-region (line-beginning-position 0)
  11530. (line-beginning-position 2)))
  11531. ;; Return non-nil if some property was removed.
  11532. (prog1 (/= end origin) (set-marker end nil))))
  11533. (_ nil))))
  11534. ;; Multi-values properties are properties that contain multiple values
  11535. ;; These values are assumed to be single words, separated by whitespace.
  11536. (defun org-entry-add-to-multivalued-property (pom property value)
  11537. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11538. (let* ((old (org-entry-get pom property))
  11539. (values (and old (split-string old))))
  11540. (setq value (org-entry-protect-space value))
  11541. (unless (member value values)
  11542. (setq values (append values (list value)))
  11543. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11544. (defun org-entry-remove-from-multivalued-property (pom property value)
  11545. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11546. (let* ((old (org-entry-get pom property))
  11547. (values (and old (split-string old))))
  11548. (setq value (org-entry-protect-space value))
  11549. (when (member value values)
  11550. (setq values (delete value values))
  11551. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11552. (defun org-entry-member-in-multivalued-property (pom property value)
  11553. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11554. (let* ((old (org-entry-get pom property))
  11555. (values (and old (split-string old))))
  11556. (setq value (org-entry-protect-space value))
  11557. (member value values)))
  11558. (defun org-entry-get-multivalued-property (pom property)
  11559. "Return a list of values in a multivalued property."
  11560. (let* ((value (org-entry-get pom property))
  11561. (values (and value (split-string value))))
  11562. (mapcar #'org-entry-restore-space values)))
  11563. (defun org-entry-put-multivalued-property (pom property &rest values)
  11564. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11565. VALUES should be a list of strings. Spaces will be protected."
  11566. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11567. (let* ((value (org-entry-get pom property))
  11568. (values (and value (split-string value))))
  11569. (mapcar #'org-entry-restore-space values)))
  11570. (defun org-entry-protect-space (s)
  11571. "Protect spaces and newline in string S."
  11572. (while (string-match " " s)
  11573. (setq s (replace-match "%20" t t s)))
  11574. (while (string-match "\n" s)
  11575. (setq s (replace-match "%0A" t t s)))
  11576. s)
  11577. (defun org-entry-restore-space (s)
  11578. "Restore spaces and newline in string S."
  11579. (while (string-match "%20" s)
  11580. (setq s (replace-match " " t t s)))
  11581. (while (string-match "%0A" s)
  11582. (setq s (replace-match "\n" t t s)))
  11583. s)
  11584. (defvar org-entry-property-inherited-from (make-marker)
  11585. "Marker pointing to the entry from where a property was inherited.
  11586. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11587. location of the entry where the inheritance search matched. If there was
  11588. no match, the marker will point nowhere.
  11589. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11590. is set.")
  11591. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11592. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11593. The search will stop at the first ancestor which has the property defined.
  11594. If the value found is \"nil\", return nil to show that the property
  11595. should be considered as undefined (this is the meaning of nil here).
  11596. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11597. (move-marker org-entry-property-inherited-from nil)
  11598. (org-with-wide-buffer
  11599. (let (value at-bob-no-heading)
  11600. (catch 'exit
  11601. (let ((element (or element
  11602. (and (org-element--cache-active-p)
  11603. (org-element-at-point nil 'cached))))
  11604. (separator (org--property-get-separator property)))
  11605. (if element
  11606. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11607. (while t
  11608. (let* ((v (org--property-local-values property literal-nil element))
  11609. (v (if (listp v) v (list v))))
  11610. (when v
  11611. (setq value
  11612. (concat (mapconcat #'identity (delq nil v) separator)
  11613. (and value separator)
  11614. value)))
  11615. (cond
  11616. ((car v)
  11617. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11618. (throw 'exit nil))
  11619. ((org-element-property :parent element)
  11620. (setq element (org-element-property :parent element)))
  11621. (t
  11622. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11623. (cond ((not global))
  11624. (value (setq value (concat global separator value)))
  11625. (t (setq value global))))
  11626. (throw 'exit nil))))))
  11627. (while t
  11628. (let ((v (org--property-local-values property literal-nil)))
  11629. (when v
  11630. (setq value
  11631. (concat (mapconcat #'identity (delq nil v) separator)
  11632. (and value separator)
  11633. value)))
  11634. (cond
  11635. ((car v)
  11636. (org-back-to-heading-or-point-min t)
  11637. (move-marker org-entry-property-inherited-from (point))
  11638. (throw 'exit nil))
  11639. ((or (org-up-heading-safe)
  11640. (and (not (bobp))
  11641. (goto-char (point-min))
  11642. nil)
  11643. ;; `org-up-heading-safe' returned nil. We are at low
  11644. ;; level heading or bob. If there is headline
  11645. ;; there, do not try to fetch its properties.
  11646. (and (bobp)
  11647. (not at-bob-no-heading)
  11648. (not (org-at-heading-p))
  11649. (setq at-bob-no-heading t))))
  11650. (t
  11651. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11652. (cond ((not global))
  11653. (value (setq value (concat global separator value)))
  11654. (t (setq value global))))
  11655. (throw 'exit nil))))))))
  11656. (if literal-nil value (org-not-nil value)))))
  11657. (defvar org-property-changed-functions nil
  11658. "Hook called when the value of a property has changed.
  11659. Each hook function should accept two arguments, the name of the property
  11660. and the new value.")
  11661. (defun org-entry-put (pom property value)
  11662. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11663. If the value is nil, it is converted to the empty string. If it
  11664. is not a string, an error is raised. Also raise an error on
  11665. invalid property names.
  11666. PROPERTY can be any regular property (see
  11667. `org-special-properties'). It can also be \"TODO\",
  11668. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11669. For the last two properties, VALUE may have any of the special
  11670. values \"earlier\" and \"later\". The function then increases or
  11671. decreases scheduled or deadline date by one day."
  11672. (cond ((null value) (setq value ""))
  11673. ((not (stringp value)) (error "Properties values should be strings"))
  11674. ((not (org--valid-property-p property))
  11675. (user-error "Invalid property name: \"%s\"" property)))
  11676. (org-no-read-only
  11677. (org-with-point-at pom
  11678. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11679. (org-back-to-heading-or-point-min t)
  11680. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11681. (let ((beg (point)))
  11682. (cond
  11683. ((equal property "TODO")
  11684. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11685. ((not (member value org-todo-keywords-1))
  11686. (user-error "\"%s\" is not a valid TODO state" value)))
  11687. (org-todo value)
  11688. (org-align-tags))
  11689. ((equal property "PRIORITY")
  11690. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11691. (org-align-tags))
  11692. ((equal property "SCHEDULED")
  11693. (forward-line)
  11694. (if (and (looking-at-p org-planning-line-re)
  11695. (re-search-forward
  11696. org-scheduled-time-regexp (line-end-position) t))
  11697. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11698. ((string= value "later") (org-timestamp-change 1 'day))
  11699. ((string= value "") (org-schedule '(4)))
  11700. (t (org-schedule nil value)))
  11701. (if (member value '("earlier" "later" ""))
  11702. (call-interactively #'org-schedule)
  11703. (org-schedule nil value))))
  11704. ((equal property "DEADLINE")
  11705. (forward-line)
  11706. (if (and (looking-at-p org-planning-line-re)
  11707. (re-search-forward
  11708. org-deadline-time-regexp (line-end-position) t))
  11709. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11710. ((string= value "later") (org-timestamp-change 1 'day))
  11711. ((string= value "") (org-deadline '(4)))
  11712. (t (org-deadline nil value)))
  11713. (if (member value '("earlier" "later" ""))
  11714. (call-interactively #'org-deadline)
  11715. (org-deadline nil value))))
  11716. ((member property org-special-properties)
  11717. (error "The %s property cannot be set with `org-entry-put'" property))
  11718. (t
  11719. (org-fold-core-ignore-modifications
  11720. (let* ((range (org-get-property-block beg 'force))
  11721. (end (cdr range))
  11722. (case-fold-search t))
  11723. (goto-char (car range))
  11724. (if (re-search-forward (org-re-property property nil t) end t)
  11725. (progn (delete-region (match-beginning 0) (match-end 0))
  11726. (goto-char (match-beginning 0)))
  11727. (goto-char end)
  11728. (insert-and-inherit "\n")
  11729. (backward-char))
  11730. (insert-and-inherit ":" property ":")
  11731. (when value (insert-and-inherit " " value))
  11732. (org-indent-line))))))
  11733. (run-hook-with-args 'org-property-changed-functions property value))))
  11734. (defun org-buffer-property-keys (&optional specials defaults columns)
  11735. "Get all property keys in the current buffer.
  11736. When SPECIALS is non-nil, also list the special properties that
  11737. reflect things like tags and TODO state.
  11738. When DEFAULTS is non-nil, also include properties that has
  11739. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11740. DESCRIPTION, LOCATION, and LOGGING and others.
  11741. When COLUMNS in non-nil, also include property names given in
  11742. COLUMN formats in the current buffer."
  11743. (let ((case-fold-search t)
  11744. (props (append
  11745. (and specials org-special-properties)
  11746. (and defaults (cons org-effort-property org-default-properties))
  11747. ;; Get property names from #+PROPERTY keywords as well
  11748. (mapcar (lambda (s)
  11749. (nth 0 (split-string s)))
  11750. (cdar (org-collect-keywords '("PROPERTY")))))))
  11751. (org-with-wide-buffer
  11752. (goto-char (point-min))
  11753. (while (re-search-forward org-property-start-re nil t)
  11754. (catch :skip
  11755. (let ((range (org-get-property-block)))
  11756. (unless range (throw :skip nil))
  11757. (goto-char (car range))
  11758. (let ((begin (car range))
  11759. (end (cdr range)))
  11760. ;; Make sure that found property block is not located
  11761. ;; before current point, as it would generate an infloop.
  11762. ;; It can happen, for example, in the following
  11763. ;; situation:
  11764. ;;
  11765. ;; * Headline
  11766. ;; :PROPERTIES:
  11767. ;; ...
  11768. ;; :END:
  11769. ;; *************** Inlinetask
  11770. ;; #+BEGIN_EXAMPLE
  11771. ;; :PROPERTIES:
  11772. ;; #+END_EXAMPLE
  11773. ;;
  11774. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11775. (while (< (point) end)
  11776. (let ((p (progn (looking-at org-property-re)
  11777. (match-string-no-properties 2))))
  11778. ;; Only add true property name, not extension symbol.
  11779. (push (if (not (string-match-p "\\+\\'" p)) p
  11780. (substring p 0 -1))
  11781. props))
  11782. (forward-line))))
  11783. (outline-next-heading)))
  11784. (when columns
  11785. (goto-char (point-min))
  11786. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11787. (let ((element (org-element-at-point)))
  11788. (when (memq (org-element-type element) '(keyword node-property))
  11789. (let ((value (org-element-property :value element))
  11790. (start 0))
  11791. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11792. \\(?:{[^}]+}\\)?"
  11793. value start)
  11794. (setq start (match-end 0))
  11795. (let ((p (match-string-no-properties 1 value)))
  11796. (unless (member-ignore-case p org-special-properties)
  11797. (push p props))))))))))
  11798. (sort (delete-dups
  11799. (append props
  11800. ;; for each xxx_ALL property, make sure the bare
  11801. ;; xxx property is also included
  11802. (delq nil (mapcar (lambda (p)
  11803. (and (string-match-p "._ALL\\'" p)
  11804. (substring p 0 -4)))
  11805. props))))
  11806. (lambda (a b) (string< (upcase a) (upcase b))))))
  11807. (defun org-property-values (key)
  11808. "List all non-nil values of property KEY in current buffer."
  11809. (org-with-wide-buffer
  11810. (goto-char (point-min))
  11811. (let ((case-fold-search t)
  11812. (re (org-re-property key))
  11813. values)
  11814. (while (re-search-forward re nil t)
  11815. (push (org-entry-get (point) key) values))
  11816. (delete-dups values))))
  11817. (defun org-insert-property-drawer ()
  11818. "Insert a property drawer into the current entry.
  11819. Do nothing if the drawer already exists. The newly created
  11820. drawer is immediately hidden."
  11821. (org-with-wide-buffer
  11822. ;; Set point to the position where the drawer should be inserted.
  11823. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11824. (org-back-to-heading-or-point-min t)
  11825. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11826. (if (org-before-first-heading-p)
  11827. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11828. (forward-line)
  11829. (when (looking-at-p org-planning-line-re) (forward-line)))
  11830. (unless (looking-at-p org-property-drawer-re)
  11831. ;; Make sure we start editing a line from current entry, not from
  11832. ;; next one. It prevents extending text properties or overlays
  11833. ;; belonging to the latter.
  11834. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11835. (let ((begin (if (bobp) (point) (1+ (point))))
  11836. (inhibit-read-only t))
  11837. (unless (bobp) (insert "\n"))
  11838. (insert ":PROPERTIES:\n:END:")
  11839. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11840. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11841. (org-indent-region begin (point))))))
  11842. (defun org-insert-drawer (&optional arg drawer)
  11843. "Insert a drawer at point.
  11844. When optional argument ARG is non-nil, insert a property drawer.
  11845. Optional argument DRAWER, when non-nil, is a string representing
  11846. drawer's name. Otherwise, the user is prompted for a name.
  11847. If a region is active, insert the drawer around that region
  11848. instead.
  11849. Point is left between drawer's boundaries."
  11850. (interactive "P")
  11851. (let* ((drawer (if arg "PROPERTIES"
  11852. (or drawer (read-from-minibuffer "Drawer: ")))))
  11853. (cond
  11854. ;; With C-u, fall back on `org-insert-property-drawer'
  11855. (arg (org-insert-property-drawer))
  11856. ;; Check validity of suggested drawer's name.
  11857. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11858. (user-error "Invalid drawer name"))
  11859. ;; With an active region, insert a drawer at point.
  11860. ((not (org-region-active-p))
  11861. (progn
  11862. (unless (bolp) (insert "\n"))
  11863. (insert (format ":%s:\n\n:END:\n" drawer))
  11864. (forward-line -2)))
  11865. ;; Otherwise, insert the drawer at point
  11866. (t
  11867. (let ((rbeg (region-beginning))
  11868. (rend (copy-marker (region-end))))
  11869. (unwind-protect
  11870. (progn
  11871. (goto-char rbeg)
  11872. (beginning-of-line)
  11873. (when (save-excursion
  11874. (re-search-forward org-outline-regexp-bol rend t))
  11875. (user-error "Drawers cannot contain headlines"))
  11876. ;; Position point at the beginning of the first
  11877. ;; non-blank line in region. Insert drawer's opening
  11878. ;; there, then indent it.
  11879. (org-skip-whitespace)
  11880. (beginning-of-line)
  11881. (insert ":" drawer ":\n")
  11882. (forward-line -1)
  11883. (indent-for-tab-command)
  11884. ;; Move point to the beginning of the first blank line
  11885. ;; after the last non-blank line in region. Insert
  11886. ;; drawer's closing, then indent it.
  11887. (goto-char rend)
  11888. (skip-chars-backward " \r\t\n")
  11889. (insert "\n:END:")
  11890. (deactivate-mark t)
  11891. (indent-for-tab-command)
  11892. (unless (eolp) (insert "\n")))
  11893. ;; Clear marker, whatever the outcome of insertion is.
  11894. (set-marker rend nil)))))))
  11895. (defvar org-property-set-functions-alist nil
  11896. "Property set function alist.
  11897. Each entry should have the following format:
  11898. (PROPERTY . READ-FUNCTION)
  11899. The read function will be called with the same argument as
  11900. `org-completing-read'.")
  11901. (defun org-set-property-function (property)
  11902. "Get the function that should be used to set PROPERTY.
  11903. This is computed according to `org-property-set-functions-alist'."
  11904. (or (cdr (assoc property org-property-set-functions-alist))
  11905. 'org-completing-read))
  11906. (defun org-read-property-value (property &optional pom default)
  11907. "Read value for PROPERTY, as a string.
  11908. When optional argument POM is non-nil, completion uses additional
  11909. information, i.e., allowed or existing values at point or marker
  11910. POM.
  11911. Optional argument DEFAULT provides a default value for PROPERTY."
  11912. (let* ((completion-ignore-case t)
  11913. (allowed
  11914. (or (org-property-get-allowed-values nil property 'table)
  11915. (and pom (org-property-get-allowed-values pom property 'table))))
  11916. (current (org-entry-get nil property))
  11917. (prompt (format "%s value%s: "
  11918. property
  11919. (if (org-string-nw-p current)
  11920. (format " [%s]" current)
  11921. "")))
  11922. (set-function (org-set-property-function property)))
  11923. (org-trim
  11924. (if allowed
  11925. (funcall set-function
  11926. prompt allowed nil
  11927. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11928. default nil default)
  11929. (let ((all (mapcar #'list
  11930. (append (org-property-values property)
  11931. (and pom
  11932. (org-with-point-at pom
  11933. (org-property-values property)))))))
  11934. (funcall set-function prompt all nil nil "" nil current))))))
  11935. (defvar org-last-set-property nil)
  11936. (defvar org-last-set-property-value nil)
  11937. (defun org-read-property-name ()
  11938. "Read a property name."
  11939. (let ((completion-ignore-case t)
  11940. (default-prop (or (and (org-at-property-p)
  11941. (match-string-no-properties 2))
  11942. org-last-set-property)))
  11943. (org-completing-read
  11944. (concat "Property"
  11945. (if default-prop (concat " [" default-prop "]") "")
  11946. ": ")
  11947. (mapcar #'list (org-buffer-property-keys nil t t))
  11948. nil nil nil nil default-prop)))
  11949. (defun org-set-property-and-value (use-last)
  11950. "Allow to set [PROPERTY]: [value] direction from prompt.
  11951. When use-default, don't even ask, just use the last
  11952. \"[PROPERTY]: [value]\" string from the history."
  11953. (interactive "P")
  11954. (let* ((completion-ignore-case t)
  11955. (pv (or (and use-last org-last-set-property-value)
  11956. (org-completing-read
  11957. "Enter a \"[Property]: [value]\" pair: "
  11958. nil nil nil nil nil
  11959. org-last-set-property-value)))
  11960. prop val)
  11961. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11962. (setq prop (match-string 1 pv)
  11963. val (match-string 2 pv))
  11964. (org-set-property prop val))))
  11965. (defun org-set-property (property value)
  11966. "In the current entry, set PROPERTY to VALUE.
  11967. When called interactively, this will prompt for a property name, offering
  11968. completion on existing and default properties. And then it will prompt
  11969. for a value, offering completion either on allowed values (via an inherited
  11970. xxx_ALL property) or on existing values in other instances of this property
  11971. in the current file.
  11972. Throw an error when trying to set a property with an invalid name."
  11973. (interactive (list nil nil))
  11974. (let ((property (or property (org-read-property-name))))
  11975. ;; `org-entry-put' also makes the following check, but this one
  11976. ;; avoids polluting `org-last-set-property' and
  11977. ;; `org-last-set-property-value' needlessly.
  11978. (unless (org--valid-property-p property)
  11979. (user-error "Invalid property name: \"%s\"" property))
  11980. (let ((value (or value (org-read-property-value property)))
  11981. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11982. (setq org-last-set-property property)
  11983. (setq org-last-set-property-value (concat property ": " value))
  11984. ;; Possibly postprocess the inserted value:
  11985. (when fn (setq value (funcall fn value)))
  11986. (unless (equal (org-entry-get nil property) value)
  11987. (org-entry-put nil property value)))))
  11988. (defun org-find-property (property &optional value)
  11989. "Find first entry in buffer that sets PROPERTY.
  11990. When optional argument VALUE is non-nil, only consider an entry
  11991. if it contains PROPERTY set to this value. If PROPERTY should be
  11992. explicitly set to nil, use string \"nil\" for VALUE.
  11993. Return position where the entry begins, or nil if there is no
  11994. such entry. If narrowing is in effect, only search the visible
  11995. part of the buffer."
  11996. (save-excursion
  11997. (goto-char (point-min))
  11998. (let ((case-fold-search t)
  11999. (re (org-re-property property nil (not value) value)))
  12000. (catch 'exit
  12001. (while (re-search-forward re nil t)
  12002. (when (if value (org-at-property-p)
  12003. (org-entry-get (point) property nil t))
  12004. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12005. (point)))))))))
  12006. (defun org-delete-property (property)
  12007. "In the current entry, delete PROPERTY."
  12008. (interactive
  12009. (let* ((completion-ignore-case t)
  12010. (cat (org-entry-get (point) "CATEGORY"))
  12011. (props0 (org-entry-properties nil 'standard))
  12012. (props (if cat props0
  12013. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12014. (prop (if (< 1 (length props))
  12015. (completing-read "Property: " props nil t)
  12016. (caar props))))
  12017. (list prop)))
  12018. (if (not property)
  12019. (message "No property to delete in this entry")
  12020. (org-entry-delete nil property)
  12021. (message "Property \"%s\" deleted" property)))
  12022. (defun org-delete-property-globally (property)
  12023. "Remove PROPERTY globally, from all entries.
  12024. This function ignores narrowing, if any."
  12025. (interactive
  12026. (let* ((completion-ignore-case t)
  12027. (prop (completing-read
  12028. "Globally remove property: "
  12029. (mapcar #'list (org-buffer-property-keys)))))
  12030. (list prop)))
  12031. (org-with-wide-buffer
  12032. (goto-char (point-min))
  12033. (let ((count 0)
  12034. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12035. (while (re-search-forward re nil t)
  12036. (when (org-entry-delete (point) property) (cl-incf count)))
  12037. (message "Property \"%s\" removed from %d entries" property count))))
  12038. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12039. (defun org-compute-property-at-point ()
  12040. "Compute the property at point.
  12041. This looks for an enclosing column format, extracts the operator and
  12042. then applies it to the property in the column format's scope."
  12043. (interactive)
  12044. (unless (org-at-property-p)
  12045. (user-error "Not at a property"))
  12046. (let ((prop (match-string-no-properties 2)))
  12047. (org-columns-get-format-and-top-level)
  12048. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12049. (user-error "No operator defined for property %s" prop))
  12050. (org-columns-compute prop)))
  12051. (defvar org-property-allowed-value-functions nil
  12052. "Hook for functions supplying allowed values for a specific property.
  12053. The functions must take a single argument, the name of the property, and
  12054. return a flat list of allowed values. If \":ETC\" is one of
  12055. the values, this means that these values are intended as defaults for
  12056. completion, but that other values should be allowed too.
  12057. The functions must return nil if they are not responsible for this
  12058. property.")
  12059. (defun org-property-get-allowed-values (pom property &optional table)
  12060. "Get allowed values for the property PROPERTY.
  12061. When TABLE is non-nil, return an alist that can directly be used for
  12062. completion."
  12063. (let (vals)
  12064. (cond
  12065. ((equal property "TODO")
  12066. (setq vals (org-with-point-at pom
  12067. (append org-todo-keywords-1 '("")))))
  12068. ((equal property "PRIORITY")
  12069. (let ((n org-priority-lowest))
  12070. (while (>= n org-priority-highest)
  12071. (push (char-to-string n) vals)
  12072. (setq n (1- n)))))
  12073. ((equal property "CATEGORY"))
  12074. ((member property org-special-properties))
  12075. ((setq vals (run-hook-with-args-until-success
  12076. 'org-property-allowed-value-functions property)))
  12077. (t
  12078. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12079. (when (and vals (string-match "\\S-" vals))
  12080. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12081. (setq vals (mapcar (lambda (x)
  12082. (cond ((stringp x) x)
  12083. ((numberp x) (number-to-string x))
  12084. ((symbolp x) (symbol-name x))
  12085. (t "???")))
  12086. vals)))))
  12087. (when (member ":ETC" vals)
  12088. (setq vals (remove ":ETC" vals))
  12089. (org-add-props (car vals) '(org-unrestricted t)))
  12090. (if table (mapcar 'list vals) vals)))
  12091. (defun org-property-previous-allowed-value (&optional _previous)
  12092. "Switch to the next allowed value for this property."
  12093. (interactive)
  12094. (org-property-next-allowed-value t))
  12095. (defun org-property-next-allowed-value (&optional previous)
  12096. "Switch to the next allowed value for this property."
  12097. (interactive)
  12098. (unless (org-at-property-p)
  12099. (user-error "Not at a property"))
  12100. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12101. (key (match-string 2))
  12102. (value (match-string 3))
  12103. (allowed (or (org-property-get-allowed-values (point) key)
  12104. (and (member value '("[ ]" "[-]" "[X]"))
  12105. '("[ ]" "[X]"))))
  12106. (heading (save-match-data (nth 4 (org-heading-components))))
  12107. nval)
  12108. (unless allowed
  12109. (user-error "Allowed values for this property have not been defined"))
  12110. (when previous (setq allowed (reverse allowed)))
  12111. (when (member value allowed)
  12112. (setq nval (car (cdr (member value allowed)))))
  12113. (setq nval (or nval (car allowed)))
  12114. (when (equal nval value)
  12115. (user-error "Only one allowed value for this property"))
  12116. (org-at-property-p)
  12117. (replace-match (concat " :" key ": " nval) t t)
  12118. (org-indent-line)
  12119. (beginning-of-line 1)
  12120. (skip-chars-forward " \t")
  12121. (when (equal prop org-effort-property)
  12122. (unless (org-element--cache-active-p)
  12123. (org-refresh-property
  12124. '((effort . identity)
  12125. (effort-minutes . org-duration-to-minutes))
  12126. nval))
  12127. (when (string= org-clock-current-task heading)
  12128. (setq org-clock-effort nval)
  12129. (org-clock-update-mode-line)))
  12130. (run-hook-with-args 'org-property-changed-functions key nval)))
  12131. (defun org-find-olp (path &optional this-buffer)
  12132. "Return a marker pointing to the entry at outline path OLP.
  12133. If anything goes wrong, throw an error, and if you need to do
  12134. something based on this error, you can catch it with
  12135. `condition-case'.
  12136. If THIS-BUFFER is set, the outline path does not contain a file,
  12137. only headings."
  12138. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12139. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12140. (level 1)
  12141. (lmin 1)
  12142. (lmax 1)
  12143. end found flevel)
  12144. (unless buffer (error "File not found :%s" file))
  12145. (with-current-buffer buffer
  12146. (unless (derived-mode-p 'org-mode)
  12147. (error "Buffer %s needs to be in Org mode" buffer))
  12148. (org-with-wide-buffer
  12149. (goto-char (point-min))
  12150. (dolist (heading path)
  12151. (let ((re (format org-complex-heading-regexp-format
  12152. (regexp-quote heading)))
  12153. (cnt 0))
  12154. (while (re-search-forward re end t)
  12155. (setq level (- (match-end 1) (match-beginning 1)))
  12156. (when (and (>= level lmin) (<= level lmax))
  12157. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12158. (when (= cnt 0)
  12159. (error "Heading not found on level %d: %s" lmax heading))
  12160. (when (> cnt 1)
  12161. (error "Heading not unique on level %d: %s" lmax heading))
  12162. (goto-char found)
  12163. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12164. (setq end (save-excursion (org-end-of-subtree t t)))))
  12165. (when (org-at-heading-p)
  12166. (point-marker))))))
  12167. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12168. "Find node HEADING in BUFFER.
  12169. Return a marker to the heading if it was found, or nil if not.
  12170. If POS-ONLY is set, return just the position instead of a marker.
  12171. The heading text must match exact, but it may have a TODO keyword,
  12172. a priority cookie and tags in the standard locations."
  12173. (with-current-buffer (or buffer (current-buffer))
  12174. (org-with-wide-buffer
  12175. (goto-char (point-min))
  12176. (let (case-fold-search)
  12177. (when (re-search-forward
  12178. (format org-complex-heading-regexp-format
  12179. (regexp-quote heading)) nil t)
  12180. (if pos-only
  12181. (match-beginning 0)
  12182. (move-marker (make-marker) (match-beginning 0))))))))
  12183. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12184. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12185. When the target headline is found, return a marker to this location."
  12186. (let ((files (directory-files (or dir default-directory)
  12187. t "\\`[^.#].*\\.org\\'"))
  12188. visiting m buffer)
  12189. (catch 'found
  12190. (dolist (file files)
  12191. (message "trying %s" file)
  12192. (setq visiting (org-find-base-buffer-visiting file))
  12193. (setq buffer (or visiting (find-file-noselect file)))
  12194. (setq m (org-find-exact-headline-in-buffer
  12195. heading buffer))
  12196. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12197. (and m (throw 'found m))))))
  12198. (defun org-find-entry-with-id (ident)
  12199. "Locate the entry that contains the ID property with exact value IDENT.
  12200. IDENT can be a string, a symbol or a number, this function will search for
  12201. the string representation of it.
  12202. Return the position where this entry starts, or nil if there is no such entry."
  12203. (interactive "sID: ")
  12204. (let ((id (cond
  12205. ((stringp ident) ident)
  12206. ((symbolp ident) (symbol-name ident))
  12207. ((numberp ident) (number-to-string ident))
  12208. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12209. (org-with-wide-buffer (org-find-property "ID" id))))
  12210. ;;;; Timestamps
  12211. (defvar org-last-changed-timestamp nil)
  12212. (defvar org-last-inserted-timestamp nil
  12213. "The last time stamp inserted with `org-insert-time-stamp'.")
  12214. (defun org-time-stamp (arg &optional inactive)
  12215. "Prompt for a date/time and insert a time stamp.
  12216. If the user specifies a time like HH:MM or if this command is
  12217. called with at least one prefix argument, the time stamp contains
  12218. the date and the time. Otherwise, only the date is included.
  12219. All parts of a date not specified by the user are filled in from
  12220. the timestamp at point, if any, or the current date/time
  12221. otherwise.
  12222. If there is already a timestamp at the cursor, it is replaced.
  12223. With two universal prefix arguments, insert an active timestamp
  12224. with the current time without prompting the user.
  12225. When called from Lisp, the timestamp is inactive if INACTIVE is
  12226. non-nil."
  12227. (interactive "P")
  12228. (let* ((ts (cond
  12229. ((org-at-date-range-p t)
  12230. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12231. ((org-at-timestamp-p 'lax) (match-string 0))))
  12232. ;; Default time is either the timestamp at point or today.
  12233. ;; When entering a range, only the range start is considered.
  12234. (default-time (and ts (org-time-string-to-time ts)))
  12235. (default-input (and ts (org-get-compact-tod ts)))
  12236. (repeater (and ts
  12237. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12238. (match-string 0 ts)))
  12239. org-time-was-given
  12240. org-end-time-was-given
  12241. (time
  12242. (if (equal arg '(16)) (current-time)
  12243. ;; Preserve `this-command' and `last-command'.
  12244. (let ((this-command this-command)
  12245. (last-command last-command))
  12246. (org-read-date
  12247. arg 'totime nil nil default-time default-input
  12248. inactive)))))
  12249. (cond
  12250. ((and ts
  12251. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12252. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12253. (insert "--")
  12254. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12255. (ts
  12256. ;; Make sure we're on a timestamp. When in the middle of a date
  12257. ;; range, move arbitrarily to range end.
  12258. (unless (org-at-timestamp-p 'lax)
  12259. (skip-chars-forward "-")
  12260. (org-at-timestamp-p 'lax))
  12261. (replace-match "")
  12262. (setq org-last-changed-timestamp
  12263. (org-insert-time-stamp
  12264. time (or org-time-was-given arg)
  12265. inactive nil nil (list org-end-time-was-given)))
  12266. (when repeater
  12267. (backward-char)
  12268. (insert " " repeater)
  12269. (setq org-last-changed-timestamp
  12270. (concat (substring org-last-inserted-timestamp 0 -1)
  12271. " " repeater ">")))
  12272. (message "Timestamp updated"))
  12273. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12274. (t (org-insert-time-stamp
  12275. time (or org-time-was-given arg) inactive nil nil
  12276. (list org-end-time-was-given))))))
  12277. ;; FIXME: can we use this for something else, like computing time differences?
  12278. (defun org-get-compact-tod (s)
  12279. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12280. (let* ((t1 (match-string 1 s))
  12281. (h1 (string-to-number (match-string 2 s)))
  12282. (m1 (string-to-number (match-string 3 s)))
  12283. (t2 (and (match-end 4) (match-string 5 s)))
  12284. (h2 (and t2 (string-to-number (match-string 6 s))))
  12285. (m2 (and t2 (string-to-number (match-string 7 s))))
  12286. dh dm)
  12287. (if (not t2)
  12288. t1
  12289. (setq dh (- h2 h1) dm (- m2 m1))
  12290. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12291. (concat t1 "+" (number-to-string dh)
  12292. (and (/= 0 dm) (format ":%02d" dm)))))))
  12293. (defun org-time-stamp-inactive (&optional arg)
  12294. "Insert an inactive time stamp.
  12295. An inactive time stamp is enclosed in square brackets instead of
  12296. angle brackets. It is inactive in the sense that it does not
  12297. trigger agenda entries. So these are more for recording a
  12298. certain time/date.
  12299. If the user specifies a time like HH:MM or if this command is called with
  12300. at least one prefix argument, the time stamp contains the date and the time.
  12301. Otherwise, only the date is included.
  12302. When called with two universal prefix arguments, insert an inactive time stamp
  12303. with the current time without prompting the user."
  12304. (interactive "P")
  12305. (org-time-stamp arg 'inactive))
  12306. (defvar org-date-ovl (make-overlay 1 1))
  12307. (overlay-put org-date-ovl 'face 'org-date-selected)
  12308. (delete-overlay org-date-ovl)
  12309. (defvar org-ans1) ; dynamically scoped parameter
  12310. (defvar org-ans2) ; dynamically scoped parameter
  12311. (defvar org-plain-time-of-day-regexp) ; defined below
  12312. (defvar org-overriding-default-time nil) ; dynamically scoped
  12313. (defvar org-read-date-overlay nil)
  12314. (defvar org-read-date-history nil)
  12315. (defvar org-read-date-final-answer nil)
  12316. (defvar org-read-date-analyze-futurep nil)
  12317. (defvar org-read-date-analyze-forced-year nil)
  12318. (defvar org-read-date-inactive)
  12319. (defvar org-def)
  12320. (defvar org-defdecode)
  12321. (defvar org-with-time)
  12322. (defvar calendar-setup) ; Dynamically scoped.
  12323. (defun org-read-date (&optional with-time to-time from-string prompt
  12324. default-time default-input inactive)
  12325. "Read a date, possibly a time, and make things smooth for the user.
  12326. The prompt will suggest to enter an ISO date, but you can also enter anything
  12327. which will at least partially be understood by `parse-time-string'.
  12328. Unrecognized parts of the date will default to the current day, month, year,
  12329. hour and minute. If this command is called to replace a timestamp at point,
  12330. or to enter the second timestamp of a range, the default time is taken
  12331. from the existing stamp. Furthermore, the command prefers the future,
  12332. so if you are giving a date where the year is not given, and the day-month
  12333. combination is already past in the current year, it will assume you
  12334. mean next year. For details, see the manual. A few examples:
  12335. 3-2-5 --> 2003-02-05
  12336. feb 15 --> currentyear-02-15
  12337. 2/15 --> currentyear-02-15
  12338. sep 12 9 --> 2009-09-12
  12339. 12:45 --> today 12:45
  12340. 22 sept 0:34 --> currentyear-09-22 0:34
  12341. 12 --> currentyear-currentmonth-12
  12342. Fri --> nearest Friday after today
  12343. -Tue --> last Tuesday
  12344. etc.
  12345. Furthermore you can specify a relative date by giving, as the *first* thing
  12346. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12347. change in days weeks, months, years.
  12348. With a single plus or minus, the date is relative to today. With a double
  12349. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12350. +4d --> four days from today
  12351. +4 --> same as above
  12352. +2w --> two weeks from today
  12353. ++5 --> five days from default date
  12354. The function understands only English month and weekday abbreviations.
  12355. While prompting, a calendar is popped up - you can also select the
  12356. date with the mouse (button 1). The calendar shows a period of three
  12357. months. To scroll it to other months, use the keys `>' and `<'.
  12358. There are many other calendar navigation commands available, see
  12359. Info node `(org) The date/time prompt' for a full list.
  12360. If you don't like the calendar, turn it off with
  12361. (setq org-read-date-popup-calendar nil)
  12362. With optional argument TO-TIME, the date will immediately be converted
  12363. to an internal time.
  12364. With an optional argument WITH-TIME, the prompt will suggest to
  12365. also insert a time. Note that when WITH-TIME is not set, you can
  12366. still enter a time, and this function will inform the calling routine
  12367. about this change. The calling routine may then choose to change the
  12368. format used to insert the time stamp into the buffer to include the time.
  12369. With optional argument FROM-STRING, read from this string instead from
  12370. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12371. the time/date that is used for everything that is not specified by the
  12372. user."
  12373. (require 'parse-time)
  12374. (let* ((org-with-time with-time)
  12375. (org-time-stamp-rounding-minutes
  12376. (if (equal org-with-time '(16))
  12377. '(0 0)
  12378. org-time-stamp-rounding-minutes))
  12379. (ct (org-current-time))
  12380. (org-def (or org-overriding-default-time default-time ct))
  12381. (org-defdecode (decode-time org-def))
  12382. (cur-frame (selected-frame))
  12383. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12384. (calendar-setup
  12385. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12386. (calendar-move-hook nil)
  12387. (calendar-view-diary-initially-flag nil)
  12388. (calendar-view-holidays-initially-flag nil)
  12389. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12390. ;; Rationalize `org-def' and `org-defdecode', if required.
  12391. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12392. (setf (nth 2 org-defdecode) -1)
  12393. (setf (nth 1 org-defdecode) 59)
  12394. (setq org-def (org-encode-time org-defdecode))
  12395. (setq org-defdecode (decode-time org-def)))
  12396. (let* ((timestr (format-time-string
  12397. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12398. org-def))
  12399. (prompt (concat (if prompt (concat prompt " ") "")
  12400. (format "Date+time [%s]: " timestr))))
  12401. (cond
  12402. (from-string (setq ans from-string))
  12403. (org-read-date-popup-calendar
  12404. (save-excursion
  12405. (save-window-excursion
  12406. (calendar)
  12407. (when (eq calendar-setup 'calendar-only)
  12408. (setq cal-frame
  12409. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12410. (select-frame cal-frame))
  12411. (org-eval-in-calendar '(setq cursor-type nil) t)
  12412. (unwind-protect
  12413. (progn
  12414. (calendar-forward-day (- (time-to-days org-def)
  12415. (calendar-absolute-from-gregorian
  12416. (calendar-current-date))))
  12417. (org-eval-in-calendar nil t)
  12418. (let* ((old-map (current-local-map))
  12419. (map (copy-keymap calendar-mode-map))
  12420. (minibuffer-local-map
  12421. (copy-keymap org-read-date-minibuffer-local-map)))
  12422. (org-defkey map (kbd "RET") 'org-calendar-select)
  12423. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12424. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12425. (unwind-protect
  12426. (progn
  12427. (use-local-map map)
  12428. (setq org-read-date-inactive inactive)
  12429. (add-hook 'post-command-hook 'org-read-date-display)
  12430. (setq org-ans0
  12431. (read-string prompt
  12432. default-input
  12433. 'org-read-date-history
  12434. nil))
  12435. ;; org-ans0: from prompt
  12436. ;; org-ans1: from mouse click
  12437. ;; org-ans2: from calendar motion
  12438. (setq ans
  12439. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12440. (remove-hook 'post-command-hook 'org-read-date-display)
  12441. (use-local-map old-map)
  12442. (when org-read-date-overlay
  12443. (delete-overlay org-read-date-overlay)
  12444. (setq org-read-date-overlay nil)))))
  12445. (bury-buffer "*Calendar*")
  12446. (when cal-frame
  12447. (delete-frame cal-frame)
  12448. (select-frame-set-input-focus cur-frame))))))
  12449. (t ; Naked prompt only
  12450. (unwind-protect
  12451. (setq ans (read-string prompt default-input
  12452. 'org-read-date-history timestr))
  12453. (when org-read-date-overlay
  12454. (delete-overlay org-read-date-overlay)
  12455. (setq org-read-date-overlay nil))))))
  12456. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12457. (when org-read-date-analyze-forced-year
  12458. (message "Year was forced into %s"
  12459. (if org-read-date-force-compatible-dates
  12460. "compatible range (1970-2037)"
  12461. "range representable on this machine"))
  12462. (ding))
  12463. (setq final (org-encode-time final))
  12464. (setq org-read-date-final-answer ans)
  12465. (if to-time
  12466. final
  12467. ;; This round-trip gets rid of 34th of August and stuff like that....
  12468. (setq final (decode-time final))
  12469. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12470. (format "%04d-%02d-%02d %02d:%02d"
  12471. (nth 5 final) (nth 4 final) (nth 3 final)
  12472. (nth 2 final) (nth 1 final))
  12473. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12474. (defun org-read-date-display ()
  12475. "Display the current date prompt interpretation in the minibuffer."
  12476. (when org-read-date-display-live
  12477. (when org-read-date-overlay
  12478. (delete-overlay org-read-date-overlay))
  12479. (when (minibufferp (current-buffer))
  12480. (save-excursion
  12481. (end-of-line 1)
  12482. (while (not (equal (buffer-substring
  12483. (max (point-min) (- (point) 4)) (point))
  12484. " "))
  12485. (insert " ")))
  12486. (let* ((ans (concat (buffer-substring (line-beginning-position) (point-max))
  12487. " " (or org-ans1 org-ans2)))
  12488. (org-end-time-was-given nil)
  12489. (f (org-read-date-analyze ans org-def org-defdecode))
  12490. (fmts (if org-display-custom-times
  12491. org-time-stamp-custom-formats
  12492. org-time-stamp-formats))
  12493. (fmt (if (or org-with-time
  12494. (and (boundp 'org-time-was-given) org-time-was-given))
  12495. (cdr fmts)
  12496. (car fmts)))
  12497. (txt (format-time-string fmt (org-encode-time f)))
  12498. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12499. (txt (concat "=> " txt)))
  12500. (when (and org-end-time-was-given
  12501. (string-match org-plain-time-of-day-regexp txt))
  12502. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12503. org-end-time-was-given
  12504. (substring txt (match-end 0)))))
  12505. (when org-read-date-analyze-futurep
  12506. (setq txt (concat txt " (=>F)")))
  12507. (setq org-read-date-overlay
  12508. (make-overlay (1- (line-end-position)) (line-end-position)))
  12509. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12510. (defun org-read-date-analyze (ans def defdecode)
  12511. "Analyze the combined answer of the date prompt."
  12512. ;; FIXME: cleanup and comment
  12513. (let ((org-def def)
  12514. (org-defdecode defdecode)
  12515. (nowdecode (decode-time))
  12516. delta deltan deltaw deltadef year month day
  12517. hour minute second wday pm h2 m2 tl wday1
  12518. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12519. (setq org-read-date-analyze-futurep nil
  12520. org-read-date-analyze-forced-year nil)
  12521. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12522. (setq ans "+0"))
  12523. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12524. (setq ans (replace-match "" t t ans)
  12525. deltan (car delta)
  12526. deltaw (nth 1 delta)
  12527. deltadef (nth 2 delta)))
  12528. ;; Check if there is an iso week date in there. If yes, store the
  12529. ;; info and postpone interpreting it until the rest of the parsing
  12530. ;; is done.
  12531. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12532. (setq iso-year (when (match-end 1)
  12533. (org-small-year-to-year
  12534. (string-to-number (match-string 1 ans))))
  12535. iso-weekday (when (match-end 3)
  12536. (string-to-number (match-string 3 ans)))
  12537. iso-week (string-to-number (match-string 2 ans)))
  12538. (setq ans (replace-match "" t t ans)))
  12539. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12540. (when (string-match
  12541. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12542. (setq year (if (match-end 2)
  12543. (string-to-number (match-string 2 ans))
  12544. (progn (setq kill-year t)
  12545. (string-to-number (format-time-string "%Y"))))
  12546. month (string-to-number (match-string 3 ans))
  12547. day (string-to-number (match-string 4 ans)))
  12548. (setq year (org-small-year-to-year year))
  12549. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12550. t nil ans)))
  12551. ;; Help matching dotted european dates
  12552. (when (string-match
  12553. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12554. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12555. (setq kill-year t)
  12556. (string-to-number (format-time-string "%Y")))
  12557. day (string-to-number (match-string 1 ans))
  12558. month (string-to-number (match-string 2 ans))
  12559. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12560. t nil ans)))
  12561. ;; Help matching american dates, like 5/30 or 5/30/7
  12562. (when (string-match
  12563. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12564. (setq year (if (match-end 4)
  12565. (string-to-number (match-string 4 ans))
  12566. (progn (setq kill-year t)
  12567. (string-to-number (format-time-string "%Y"))))
  12568. month (string-to-number (match-string 1 ans))
  12569. day (string-to-number (match-string 2 ans)))
  12570. (setq year (org-small-year-to-year year))
  12571. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12572. t nil ans)))
  12573. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12574. ;; If there is a time with am/pm, and *no* time without it, we convert
  12575. ;; so that matching will be successful.
  12576. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12577. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12578. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12579. (setq hour (string-to-number (match-string 1 ans))
  12580. minute (if (match-end 3)
  12581. (string-to-number (match-string 3 ans))
  12582. 0)
  12583. pm (equal ?p
  12584. (string-to-char (downcase (match-string 4 ans)))))
  12585. (if (and (= hour 12) (not pm))
  12586. (setq hour 0)
  12587. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12588. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12589. t t ans))))
  12590. ;; Help matching HHhMM times, similarly as for am/pm times.
  12591. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12592. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12593. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12594. (setq hour (if (match-end 1)
  12595. (string-to-number (match-string 1 ans))
  12596. 0)
  12597. minute (if (match-end 2)
  12598. (string-to-number (match-string 2 ans))
  12599. 0))
  12600. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12601. t t ans))))
  12602. ;; Check if a time range is given as a duration
  12603. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12604. (setq hour (string-to-number (match-string 1 ans))
  12605. h2 (+ hour (string-to-number (match-string 3 ans)))
  12606. minute (string-to-number (match-string 2 ans))
  12607. m2 (+ minute (if (match-end 5) (string-to-number
  12608. (match-string 5 ans))0)))
  12609. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12610. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12611. t t ans)))
  12612. ;; Check if there is a time range
  12613. (when (boundp 'org-end-time-was-given)
  12614. (setq org-time-was-given nil)
  12615. (when (and (string-match org-plain-time-of-day-regexp ans)
  12616. (match-end 8))
  12617. (setq org-end-time-was-given (match-string 8 ans))
  12618. (setq ans (concat (substring ans 0 (match-beginning 7))
  12619. (substring ans (match-end 7))))))
  12620. (setq tl (parse-time-string ans)
  12621. day (or (nth 3 tl) (nth 3 org-defdecode))
  12622. month
  12623. (cond ((nth 4 tl))
  12624. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12625. ;; Day was specified. Make sure DAY+MONTH
  12626. ;; combination happens in the future.
  12627. ((nth 3 tl)
  12628. (setq futurep t)
  12629. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12630. (nth 4 nowdecode)))
  12631. (t (nth 4 org-defdecode)))
  12632. year
  12633. (cond ((and (not kill-year) (nth 5 tl)))
  12634. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12635. ;; Month was guessed in the future and is at least
  12636. ;; equal to NOWDECODE's. Fix year accordingly.
  12637. (futurep
  12638. (if (or (> month (nth 4 nowdecode))
  12639. (>= day (nth 3 nowdecode)))
  12640. (nth 5 nowdecode)
  12641. (1+ (nth 5 nowdecode))))
  12642. ;; Month was specified. Make sure MONTH+YEAR
  12643. ;; combination happens in the future.
  12644. ((nth 4 tl)
  12645. (setq futurep t)
  12646. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12647. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12648. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12649. (t (nth 5 nowdecode))))
  12650. (t (nth 5 org-defdecode)))
  12651. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12652. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12653. second (or (nth 0 tl) 0)
  12654. wday (nth 6 tl))
  12655. (when (and (eq org-read-date-prefer-future 'time)
  12656. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12657. (equal day (nth 3 nowdecode))
  12658. (equal month (nth 4 nowdecode))
  12659. (equal year (nth 5 nowdecode))
  12660. (nth 2 tl)
  12661. (or (< (nth 2 tl) (nth 2 nowdecode))
  12662. (and (= (nth 2 tl) (nth 2 nowdecode))
  12663. (nth 1 tl)
  12664. (< (nth 1 tl) (nth 1 nowdecode)))))
  12665. (setq day (1+ day)
  12666. futurep t))
  12667. ;; Special date definitions below
  12668. (cond
  12669. (iso-week
  12670. ;; There was an iso week
  12671. (require 'cal-iso)
  12672. (setq futurep nil)
  12673. (setq year (or iso-year year)
  12674. day (or iso-weekday wday 1)
  12675. wday nil ; to make sure that the trigger below does not match
  12676. iso-date (calendar-gregorian-from-absolute
  12677. (calendar-iso-to-absolute
  12678. (list iso-week day year))))
  12679. ; FIXME: Should we also push ISO weeks into the future?
  12680. ; (when (and org-read-date-prefer-future
  12681. ; (not iso-year)
  12682. ; (< (calendar-absolute-from-gregorian iso-date)
  12683. ; (time-to-days nil)))
  12684. ; (setq year (1+ year)
  12685. ; iso-date (calendar-gregorian-from-absolute
  12686. ; (calendar-iso-to-absolute
  12687. ; (list iso-week day year)))))
  12688. (setq month (car iso-date)
  12689. year (nth 2 iso-date)
  12690. day (nth 1 iso-date)))
  12691. (deltan
  12692. (setq futurep nil)
  12693. (unless deltadef
  12694. (let ((now (decode-time)))
  12695. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12696. (cond ((member deltaw '("h" ""))
  12697. (when (boundp 'org-time-was-given)
  12698. (setq org-time-was-given t))
  12699. (setq hour (+ hour deltan)))
  12700. ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12701. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12702. ((equal deltaw "m") (setq month (+ month deltan)))
  12703. ((equal deltaw "y") (setq year (+ year deltan)))))
  12704. ((and wday (not (nth 3 tl)))
  12705. ;; Weekday was given, but no day, so pick that day in the week
  12706. ;; on or after the derived date.
  12707. (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
  12708. (unless (equal wday wday1)
  12709. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12710. (when (and (boundp 'org-time-was-given)
  12711. (nth 2 tl))
  12712. (setq org-time-was-given t))
  12713. (when (< year 100) (setq year (+ 2000 year)))
  12714. ;; Check of the date is representable
  12715. (if org-read-date-force-compatible-dates
  12716. (progn
  12717. (when (< year 1970)
  12718. (setq year 1970 org-read-date-analyze-forced-year t))
  12719. (when (> year 2037)
  12720. (setq year 2037 org-read-date-analyze-forced-year t)))
  12721. (condition-case nil
  12722. (ignore (org-encode-time second minute hour day month year))
  12723. (error
  12724. (setq year (nth 5 org-defdecode))
  12725. (setq org-read-date-analyze-forced-year t))))
  12726. (setq org-read-date-analyze-futurep futurep)
  12727. (list second minute hour day month year nil -1 nil)))
  12728. (defvar parse-time-weekdays)
  12729. (defun org-read-date-get-relative (s today default)
  12730. "Check string S for special relative date string.
  12731. TODAY and DEFAULT are internal times, for today and for a default.
  12732. Return shift list (N what def-flag)
  12733. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12734. N is the number of WHATs to shift.
  12735. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12736. the DEFAULT date rather than TODAY."
  12737. (require 'parse-time)
  12738. (when (and
  12739. (string-match
  12740. (concat
  12741. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12742. "\\([0-9]+\\)?"
  12743. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12744. "\\([ \t]\\|$\\)") s)
  12745. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12746. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12747. (string-to-char (substring (match-string 1 s) -1))
  12748. ?+))
  12749. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12750. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12751. (what (if (match-end 3) (match-string 3 s) "d"))
  12752. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12753. (date (if rel default today))
  12754. (wday (nth 6 (decode-time date)))
  12755. delta)
  12756. (if wday1
  12757. (progn
  12758. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12759. (when (= delta 0) (setq delta 7))
  12760. (when (= dir ?-)
  12761. (setq delta (- delta 7))
  12762. (when (= delta 0) (setq delta -7)))
  12763. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12764. (list delta "d" rel))
  12765. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12766. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12767. "Turn a user-specified date into the internal representation.
  12768. The internal representation needed by the calendar is (month day year).
  12769. This is a wrapper to handle the brain-dead convention in calendar that
  12770. user function argument order change dependent on argument order."
  12771. (pcase calendar-date-style
  12772. (`american (list arg1 arg2 arg3))
  12773. (`european (list arg2 arg1 arg3))
  12774. (`iso (list arg2 arg3 arg1))))
  12775. (defun org-eval-in-calendar (form &optional keepdate)
  12776. "Eval FORM in the calendar window and return to current window.
  12777. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12778. (let ((sf (selected-frame))
  12779. (sw (selected-window)))
  12780. (select-window (get-buffer-window "*Calendar*" t))
  12781. (eval form t)
  12782. (when (and (not keepdate) (calendar-cursor-to-date))
  12783. (let* ((date (calendar-cursor-to-date))
  12784. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12785. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12786. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12787. (select-window sw)
  12788. (select-frame-set-input-focus sf)))
  12789. (defun org-calendar-select ()
  12790. "Return to `org-read-date' with the date currently selected.
  12791. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12792. (interactive)
  12793. (when (calendar-cursor-to-date)
  12794. (let* ((date (calendar-cursor-to-date))
  12795. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12796. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12797. (when (active-minibuffer-window) (exit-minibuffer))))
  12798. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12799. "Insert a date stamp for the date given by the internal TIME.
  12800. See `format-time-string' for the format of TIME.
  12801. WITH-HM means use the stamp format that includes the time of the day.
  12802. INACTIVE means use square brackets instead of angular ones, so that the
  12803. stamp will not contribute to the agenda.
  12804. PRE and POST are optional strings to be inserted before and after the
  12805. stamp.
  12806. The command returns the inserted time stamp."
  12807. (org-fold-core-ignore-modifications
  12808. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12809. stamp)
  12810. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12811. (insert-before-markers-and-inherit (or pre ""))
  12812. (when (listp extra)
  12813. (setq extra (car extra))
  12814. (if (and (stringp extra)
  12815. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12816. (setq extra (format "-%02d:%02d"
  12817. (string-to-number (match-string 1 extra))
  12818. (string-to-number (match-string 2 extra))))
  12819. (setq extra nil)))
  12820. (when extra
  12821. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12822. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12823. (insert-before-markers-and-inherit (or post ""))
  12824. (setq org-last-inserted-timestamp stamp))))
  12825. (defun org-toggle-time-stamp-overlays ()
  12826. "Toggle the use of custom time stamp formats."
  12827. (interactive)
  12828. (setq org-display-custom-times (not org-display-custom-times))
  12829. (unless org-display-custom-times
  12830. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12831. (while (setq p (next-single-property-change p 'display))
  12832. (when (and (get-text-property p 'display)
  12833. (eq (get-text-property p 'face) 'org-date))
  12834. (remove-text-properties
  12835. p (setq p (next-single-property-change p 'display))
  12836. '(display t))))
  12837. (set-buffer-modified-p bmp)))
  12838. (org-restart-font-lock)
  12839. (setq org-table-may-need-update t)
  12840. (if org-display-custom-times
  12841. (message "Time stamps are overlaid with custom format")
  12842. (message "Time stamp overlays removed")))
  12843. (defun org-display-custom-time (beg end)
  12844. "Overlay modified time stamp format over timestamp between BEG and END."
  12845. (let* ((ts (buffer-substring beg end))
  12846. t1 with-hm tf time str (off 0))
  12847. (save-match-data
  12848. (setq t1 (org-parse-time-string ts t))
  12849. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12850. (setq off (- (match-end 0) (match-beginning 0)))))
  12851. (setq end (- end off))
  12852. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12853. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12854. time (org-fix-decoded-time t1)
  12855. str (org-add-props
  12856. (format-time-string
  12857. (substring tf 1 -1) (org-encode-time time))
  12858. nil 'mouse-face 'highlight))
  12859. (put-text-property beg end 'display str)))
  12860. (defun org-fix-decoded-time (time)
  12861. "Set 0 instead of nil for the first 6 elements of time.
  12862. Don't touch the rest."
  12863. (let ((n 0))
  12864. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12865. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12866. "Difference between TIMESTAMP-STRING and now in days.
  12867. If SECONDS is non-nil, return the difference in seconds."
  12868. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12869. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12870. (funcall fdiff nil))))
  12871. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12872. "Is the time in TIMESTAMP-STRING close to the current date?"
  12873. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12874. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12875. (not (org-entry-is-done-p))))
  12876. (defun org-get-wdays (ts &optional delay zero-delay)
  12877. "Get the deadline lead time appropriate for timestring TS.
  12878. When DELAY is non-nil, get the delay time for scheduled items
  12879. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12880. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12881. don't try to find the delay cookie in the scheduled timestamp."
  12882. (let ((tv (if delay org-scheduled-delay-days
  12883. org-deadline-warning-days)))
  12884. (cond
  12885. ((or (and delay (< tv 0))
  12886. (and delay zero-delay (<= tv 0))
  12887. (and (not delay) (<= tv 0)))
  12888. ;; Enforce this value no matter what
  12889. (- tv))
  12890. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12891. ;; lead time is specified.
  12892. (floor (* (string-to-number (match-string 1 ts))
  12893. (cdr (assoc (match-string 2 ts)
  12894. '(("d" . 1) ("w" . 7)
  12895. ("m" . 30.4) ("y" . 365.25)
  12896. ("h" . 0.041667)))))))
  12897. ;; go for the default.
  12898. (t tv))))
  12899. (defun org-calendar-select-mouse (ev)
  12900. "Return to `org-read-date' with the date currently selected.
  12901. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12902. (interactive "e")
  12903. (mouse-set-point ev)
  12904. (when (calendar-cursor-to-date)
  12905. (let* ((date (calendar-cursor-to-date))
  12906. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12907. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12908. (when (active-minibuffer-window) (exit-minibuffer))))
  12909. (defun org-check-deadlines (ndays)
  12910. "Check if there are any deadlines due or past due.
  12911. A deadline is considered due if it happens within `org-deadline-warning-days'
  12912. days from today's date. If the deadline appears in an entry marked DONE,
  12913. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12914. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12915. are shown."
  12916. (interactive "P")
  12917. (let* ((org-warn-days
  12918. (cond
  12919. ((equal ndays '(4)) 100000)
  12920. (ndays (prefix-numeric-value ndays))
  12921. (t (abs org-deadline-warning-days))))
  12922. (case-fold-search nil)
  12923. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12924. (callback
  12925. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12926. (message "%d deadlines past-due or due within %d days"
  12927. (org-occur regexp nil callback)
  12928. org-warn-days)))
  12929. (defsubst org-re-timestamp (type)
  12930. "Return a regexp for timestamp TYPE.
  12931. Allowed values for TYPE are:
  12932. all: all timestamps
  12933. active: only active timestamps (<...>)
  12934. inactive: only inactive timestamps ([...])
  12935. scheduled: only scheduled timestamps
  12936. deadline: only deadline timestamps
  12937. closed: only closed time-stamps
  12938. When TYPE is nil, fall back on returning a regexp that matches
  12939. both scheduled and deadline timestamps."
  12940. (cl-case type
  12941. (all org-ts-regexp-both)
  12942. (active org-ts-regexp)
  12943. (inactive org-ts-regexp-inactive)
  12944. (scheduled org-scheduled-time-regexp)
  12945. (deadline org-deadline-time-regexp)
  12946. (closed org-closed-time-regexp)
  12947. (otherwise
  12948. (concat "\\<"
  12949. (regexp-opt (list org-deadline-string org-scheduled-string))
  12950. " *<\\([^>]+\\)>"))))
  12951. (defun org-check-before-date (d)
  12952. "Check if there are deadlines or scheduled entries before date D."
  12953. (interactive (list (org-read-date)))
  12954. (let* ((case-fold-search nil)
  12955. (regexp (org-re-timestamp org-ts-type))
  12956. (ts-type org-ts-type)
  12957. (callback
  12958. (lambda ()
  12959. (let ((match (match-string 1)))
  12960. (and (if (memq ts-type '(active inactive all))
  12961. (eq (org-element-type (save-excursion
  12962. (backward-char)
  12963. (org-element-context)))
  12964. 'timestamp)
  12965. (org-at-planning-p))
  12966. (time-less-p
  12967. (org-time-string-to-time match)
  12968. (org-time-string-to-time d)))))))
  12969. (message "%d entries before %s"
  12970. (org-occur regexp nil callback)
  12971. d)))
  12972. (defun org-check-after-date (d)
  12973. "Check if there are deadlines or scheduled entries after date D."
  12974. (interactive (list (org-read-date)))
  12975. (let* ((case-fold-search nil)
  12976. (regexp (org-re-timestamp org-ts-type))
  12977. (ts-type org-ts-type)
  12978. (callback
  12979. (lambda ()
  12980. (let ((match (match-string 1)))
  12981. (and (if (memq ts-type '(active inactive all))
  12982. (eq (org-element-type (save-excursion
  12983. (backward-char)
  12984. (org-element-context)))
  12985. 'timestamp)
  12986. (org-at-planning-p))
  12987. (not (time-less-p
  12988. (org-time-string-to-time match)
  12989. (org-time-string-to-time d))))))))
  12990. (message "%d entries after %s"
  12991. (org-occur regexp nil callback)
  12992. d)))
  12993. (defun org-check-dates-range (start-date end-date)
  12994. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12995. (interactive (list (org-read-date nil nil nil "Range starts")
  12996. (org-read-date nil nil nil "Range end")))
  12997. (let ((case-fold-search nil)
  12998. (regexp (org-re-timestamp org-ts-type))
  12999. (callback
  13000. (let ((type org-ts-type))
  13001. (lambda ()
  13002. (let ((match (match-string 1)))
  13003. (and
  13004. (if (memq type '(active inactive all))
  13005. (eq (org-element-type (save-excursion
  13006. (backward-char)
  13007. (org-element-context)))
  13008. 'timestamp)
  13009. (org-at-planning-p))
  13010. (not (time-less-p
  13011. (org-time-string-to-time match)
  13012. (org-time-string-to-time start-date)))
  13013. (time-less-p
  13014. (org-time-string-to-time match)
  13015. (org-time-string-to-time end-date))))))))
  13016. (message "%d entries between %s and %s"
  13017. (org-occur regexp nil callback) start-date end-date)))
  13018. (defun org-evaluate-time-range (&optional to-buffer)
  13019. "Evaluate a time range by computing the difference between start and end.
  13020. Normally the result is just printed in the echo area, but with prefix arg
  13021. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13022. If the time range is actually in a table, the result is inserted into the
  13023. next column.
  13024. For time difference computation, a year is assumed to be exactly 365
  13025. days in order to avoid rounding problems."
  13026. (interactive "P")
  13027. (or
  13028. (org-clock-update-time-maybe)
  13029. (save-excursion
  13030. (unless (org-at-date-range-p t)
  13031. (goto-char (line-beginning-position))
  13032. (re-search-forward org-tr-regexp-both (line-end-position) t))
  13033. (unless (org-at-date-range-p t)
  13034. (user-error "Not at a time-stamp range, and none found in current line")))
  13035. (let* ((ts1 (match-string 1))
  13036. (ts2 (match-string 2))
  13037. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13038. (match-end (match-end 0))
  13039. (time1 (org-time-string-to-time ts1))
  13040. (time2 (org-time-string-to-time ts2))
  13041. (diff (abs (float-time (time-subtract time2 time1))))
  13042. (negative (time-less-p time2 time1))
  13043. ;; (ys (floor (* 365 24 60 60)))
  13044. (ds (* 24 60 60))
  13045. (hs (* 60 60))
  13046. (fy "%dy %dd %02d:%02d")
  13047. (fy1 "%dy %dd")
  13048. (fd "%dd %02d:%02d")
  13049. (fd1 "%dd")
  13050. (fh "%02d:%02d")
  13051. y d h m align)
  13052. (if havetime
  13053. (setq ; y (floor diff ys) diff (mod diff ys)
  13054. y 0
  13055. d (floor diff ds) diff (mod diff ds)
  13056. h (floor diff hs) diff (mod diff hs)
  13057. m (floor diff 60))
  13058. (setq ; y (floor diff ys) diff (mod diff ys)
  13059. y 0
  13060. d (round diff ds)
  13061. h 0 m 0))
  13062. (if (not to-buffer)
  13063. (message "%s" (org-make-tdiff-string y d h m))
  13064. (if (org-at-table-p)
  13065. (progn
  13066. (goto-char match-end)
  13067. (setq align t)
  13068. (and (looking-at " *|") (goto-char (match-end 0))))
  13069. (goto-char match-end))
  13070. (when (looking-at
  13071. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13072. (replace-match ""))
  13073. (when negative (insert " -"))
  13074. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13075. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13076. (insert " " (format fh h m))))
  13077. (when align (org-table-align))
  13078. (message "Time difference inserted")))))
  13079. (defun org-make-tdiff-string (y d h m)
  13080. (let ((fmt "")
  13081. (l nil))
  13082. (when (> y 0)
  13083. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13084. (push y l))
  13085. (when (> d 0)
  13086. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13087. (push d l))
  13088. (when (> h 0)
  13089. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13090. (push h l))
  13091. (when (> m 0)
  13092. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13093. (push m l))
  13094. (apply 'format fmt (nreverse l))))
  13095. (defun org-time-string-to-time (s)
  13096. "Convert timestamp string S into internal time."
  13097. (org-encode-time (org-parse-time-string s)))
  13098. (defun org-time-string-to-seconds (s)
  13099. "Convert a timestamp string S into a number of seconds."
  13100. (float-time (org-time-string-to-time s)))
  13101. (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13102. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13103. "Convert time stamp S to an absolute day number.
  13104. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13105. stamp, get the closest date to DAYNR. If PREFER is
  13106. `past' (respectively `future') return a date past (respectively
  13107. after) or equal to DAYNR.
  13108. POS is the location of time stamp S, as a buffer position in
  13109. BUFFER.
  13110. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13111. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13112. signaled."
  13113. (cond
  13114. ((string-match "\\`%%\\((.*)\\)" s)
  13115. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13116. ;; only able to match individual dates. If it fails, raise an
  13117. ;; error.
  13118. (if (and daynr
  13119. (org-diary-sexp-entry
  13120. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13121. daynr
  13122. (signal 'org-diary-sexp-no-match (list s))))
  13123. (daynr (org-closest-date s daynr prefer))
  13124. (t (time-to-days
  13125. (condition-case errdata
  13126. (org-time-string-to-time s)
  13127. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13128. s
  13129. (if (not (and buffer pos)) ""
  13130. (format-message " at %d in buffer `%s'" pos buffer))
  13131. (cdr errdata))))))))
  13132. (defun org-days-to-iso-week (days)
  13133. "Return the ISO week number."
  13134. (require 'cal-iso)
  13135. (car (calendar-iso-from-absolute days)))
  13136. (defun org-small-year-to-year (year)
  13137. "Convert 2-digit years into 4-digit years.
  13138. YEAR is expanded into one of the 30 next years, if possible, or
  13139. into a past one. Any year larger than 99 is returned unchanged."
  13140. (if (>= year 100) year
  13141. (let* ((current (string-to-number (format-time-string "%Y")))
  13142. (century (/ current 100))
  13143. (offset (- year (% current 100))))
  13144. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13145. ((> offset -70) (+ (* century 100) year))
  13146. (t (+ (* (1+ century) 100) year))))))
  13147. (defun org-time-from-absolute (d)
  13148. "Return the time corresponding to date D.
  13149. D may be an absolute day number, or a calendar-type list (month day year)."
  13150. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13151. (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13152. (defvar org-agenda-current-date)
  13153. (defun org-calendar-holiday ()
  13154. "List of holidays, for Diary display in Org mode."
  13155. (require 'holidays)
  13156. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13157. (and hl (mapconcat #'identity hl "; "))))
  13158. (defvar org--diary-sexp-entry-cache (make-hash-table :test #'equal)
  13159. "Hash table holding return values of `org-diary-sexp-entry'.")
  13160. (defun org-diary-sexp-entry (sexp entry d)
  13161. "Process a SEXP diary ENTRY for date D."
  13162. (require 'diary-lib)
  13163. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13164. ;; dynamically.
  13165. (let ((cached (gethash (list sexp entry d) org--diary-sexp-entry-cache 'none)))
  13166. (if (not (eq 'none cached)) cached
  13167. (puthash (list sexp entry d)
  13168. (let* ((sexp `(let ((entry ,entry)
  13169. (date ',d))
  13170. ,(car (read-from-string sexp))))
  13171. ;; FIXME: Do not use (eval ... t) in the following sexp as
  13172. ;; diary vars are still using dynamic scope.
  13173. (result (if calendar-debug-sexp (eval sexp)
  13174. (condition-case nil
  13175. (eval sexp)
  13176. (error
  13177. (beep)
  13178. (message "Bad sexp at line %d in %s: %s"
  13179. (org-current-line)
  13180. (buffer-file-name) sexp)
  13181. (sleep-for 2))))))
  13182. (cond ((stringp result) (split-string result "; "))
  13183. ((and (consp result)
  13184. (not (consp (cdr result)))
  13185. (stringp (cdr result)))
  13186. (cdr result))
  13187. ((and (consp result)
  13188. (stringp (car result)))
  13189. result)
  13190. (result entry)))
  13191. org--diary-sexp-entry-cache))))
  13192. (defun org-diary-to-ical-string (frombuf)
  13193. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13194. This uses the icalendar.el library."
  13195. (let* ((tmpdir temporary-file-directory)
  13196. (tmpfile (make-temp-name
  13197. (expand-file-name "orgics" tmpdir)))
  13198. buf rtn b e)
  13199. (with-current-buffer frombuf
  13200. (icalendar-export-region (point-min) (point-max) tmpfile)
  13201. (setq buf (find-buffer-visiting tmpfile))
  13202. (set-buffer buf)
  13203. (goto-char (point-min))
  13204. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13205. (setq b (match-beginning 0)))
  13206. (goto-char (point-max))
  13207. (when (re-search-backward "^END:VEVENT" nil t)
  13208. (setq e (match-end 0)))
  13209. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13210. (kill-buffer buf)
  13211. (delete-file tmpfile)
  13212. rtn))
  13213. (defun org-closest-date (start current prefer)
  13214. "Return closest date to CURRENT starting from START.
  13215. CURRENT and START are both time stamps.
  13216. When PREFER is `past', return a date that is either CURRENT or
  13217. past. When PREFER is `future', return a date that is either
  13218. CURRENT or future.
  13219. Only time stamps with a repeater are modified. Any other time
  13220. stamp stay unchanged. In any case, return value is an absolute
  13221. day number."
  13222. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13223. ;; No repeater. Do not shift time stamp.
  13224. (time-to-days (org-time-string-to-time start))
  13225. (let ((value (string-to-number (match-string 1 start)))
  13226. (type (match-string 2 start)))
  13227. (if (= 0 value)
  13228. ;; Repeater with a 0-value is considered as void.
  13229. (time-to-days (org-time-string-to-time start))
  13230. (let* ((base (org-date-to-gregorian start))
  13231. (target (org-date-to-gregorian current))
  13232. (sday (calendar-absolute-from-gregorian base))
  13233. (cday (calendar-absolute-from-gregorian target))
  13234. n1 n2)
  13235. ;; If START is already past CURRENT, just return START.
  13236. (if (<= cday sday) sday
  13237. ;; Compute closest date before (N1) and closest date past
  13238. ;; (N2) CURRENT.
  13239. (pcase type
  13240. ("h"
  13241. (let ((missing-hours
  13242. (mod (+ (- (* 24 (- cday sday))
  13243. (nth 2 (org-parse-time-string start)))
  13244. org-extend-today-until)
  13245. value)))
  13246. (setf n1 (if (= missing-hours 0) cday
  13247. (- cday (1+ (/ missing-hours 24)))))
  13248. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13249. ((or "d" "w")
  13250. (let ((value (if (equal type "w") (* 7 value) value)))
  13251. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13252. (setf n2 (+ n1 value))))
  13253. ("m"
  13254. (let* ((add-months
  13255. (lambda (d n)
  13256. ;; Add N months to gregorian date D, i.e.,
  13257. ;; a list (MONTH DAY YEAR). Return a valid
  13258. ;; gregorian date.
  13259. (let ((m (+ (nth 0 d) n)))
  13260. (list (mod m 12)
  13261. (nth 1 d)
  13262. (+ (/ m 12) (nth 2 d))))))
  13263. (months ; Complete months to TARGET.
  13264. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13265. (- (nth 0 target) (nth 0 base))
  13266. ;; If START's day is greater than
  13267. ;; TARGET's, remove incomplete month.
  13268. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13269. value)
  13270. value))
  13271. (before (funcall add-months base months)))
  13272. (setf n1 (calendar-absolute-from-gregorian before))
  13273. (setf n2
  13274. (calendar-absolute-from-gregorian
  13275. (funcall add-months before value)))))
  13276. (_
  13277. (let* ((d (nth 1 base))
  13278. (m (nth 0 base))
  13279. (y (nth 2 base))
  13280. (years ; Complete years to TARGET.
  13281. (* (/ (- (nth 2 target)
  13282. y
  13283. ;; If START's month and day are
  13284. ;; greater than TARGET's, remove
  13285. ;; incomplete year.
  13286. (if (or (> (nth 0 target) m)
  13287. (and (= (nth 0 target) m)
  13288. (> (nth 1 target) d)))
  13289. 0
  13290. 1))
  13291. value)
  13292. value))
  13293. (before (list m d (+ y years))))
  13294. (setf n1 (calendar-absolute-from-gregorian before))
  13295. (setf n2 (calendar-absolute-from-gregorian
  13296. (list m d (+ (nth 2 before) value)))))))
  13297. ;; Handle PREFER parameter, if any.
  13298. (cond
  13299. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13300. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13301. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13302. (defun org-date-to-gregorian (d)
  13303. "Turn any specification of date D into a Gregorian date for the calendar."
  13304. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13305. ((and (listp d) (= (length d) 3)) d)
  13306. ((stringp d)
  13307. (let ((d (org-parse-time-string d)))
  13308. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13309. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13310. (defun org-timestamp-up (&optional arg)
  13311. "Increase the date item at the cursor by one.
  13312. If the cursor is on the year, change the year. If it is on the month,
  13313. the day or the time, change that. If the cursor is on the enclosing
  13314. bracket, change the timestamp type.
  13315. With prefix ARG, change by that many units."
  13316. (interactive "p")
  13317. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13318. (defun org-timestamp-down (&optional arg)
  13319. "Decrease the date item at the cursor by one.
  13320. If the cursor is on the year, change the year. If it is on the month,
  13321. the day or the time, change that. If the cursor is on the enclosing
  13322. bracket, change the timestamp type.
  13323. With prefix ARG, change by that many units."
  13324. (interactive "p")
  13325. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13326. (defun org-timestamp-up-day (&optional arg)
  13327. "Increase the date in the time stamp by one day.
  13328. With prefix ARG, change that many days."
  13329. (interactive "p")
  13330. (if (and (not (org-at-timestamp-p 'lax))
  13331. (org-at-heading-p))
  13332. (org-todo 'up)
  13333. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13334. (defun org-timestamp-down-day (&optional arg)
  13335. "Decrease the date in the time stamp by one day.
  13336. With prefix ARG, change that many days."
  13337. (interactive "p")
  13338. (if (and (not (org-at-timestamp-p 'lax))
  13339. (org-at-heading-p))
  13340. (org-todo 'down)
  13341. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13342. (defun org-at-timestamp-p (&optional extended)
  13343. "Non-nil if point is inside a timestamp.
  13344. By default, the function only consider syntactically valid active
  13345. timestamps. However, the caller may have a broader definition
  13346. for timestamps. As a consequence, optional argument EXTENDED can
  13347. be set to the following values
  13348. `inactive'
  13349. Include also syntactically valid inactive timestamps.
  13350. `agenda'
  13351. Include timestamps allowed in Agenda, i.e., those in
  13352. properties drawers, planning lines and clock lines.
  13353. `lax'
  13354. Ignore context. The function matches any part of the
  13355. document looking like a timestamp. This includes comments,
  13356. example blocks...
  13357. For backward-compatibility with Org 9.0, every other non-nil
  13358. value is equivalent to `inactive'.
  13359. When at a timestamp, return the position of the point as a symbol
  13360. among `bracket', `after', `year', `month', `hour', `minute',
  13361. `day' or a number of character from the last know part of the
  13362. time stamp. If diary sexp timestamps, any point inside the timestamp
  13363. is considered `day' (i.e. only `bracket', `day', and `after' return
  13364. values are possible).
  13365. When matching, the match groups are the following:
  13366. group 1: year, if any
  13367. group 2: month, if any
  13368. group 3: day number, if any
  13369. group 4: day name, if any
  13370. group 5: hours, if any
  13371. group 6: minutes, if any"
  13372. (let* ((regexp
  13373. (if extended
  13374. (if (eq extended 'agenda)
  13375. (rx-to-string
  13376. `(or (regexp ,org-ts-regexp3)
  13377. (regexp ,org-element--timestamp-regexp)))
  13378. org-ts-regexp3)
  13379. org-ts-regexp2))
  13380. (pos (point))
  13381. (match?
  13382. (let ((boundaries (org-in-regexp regexp)))
  13383. (save-match-data
  13384. (cond ((null boundaries) nil)
  13385. ((eq extended 'lax) t)
  13386. (t
  13387. (or (and (eq extended 'agenda)
  13388. (or (org-at-planning-p)
  13389. (org-at-property-p)
  13390. (and (bound-and-true-p
  13391. org-agenda-include-inactive-timestamps)
  13392. (org-at-clock-log-p))))
  13393. (eq 'timestamp
  13394. (save-excursion
  13395. (when (= pos (cdr boundaries)) (forward-char -1))
  13396. (org-element-type (org-element-context)))))))))))
  13397. (cond
  13398. ((not match?) nil)
  13399. ((= pos (match-beginning 0)) 'bracket)
  13400. ;; Distinguish location right before the closing bracket from
  13401. ;; right after it.
  13402. ((= pos (1- (match-end 0))) 'bracket)
  13403. ((= pos (match-end 0)) 'after)
  13404. ((org-pos-in-match-range pos 2) 'year)
  13405. ((org-pos-in-match-range pos 3) 'month)
  13406. ((org-pos-in-match-range pos 7) 'hour)
  13407. ((org-pos-in-match-range pos 8) 'minute)
  13408. ((or (org-pos-in-match-range pos 4)
  13409. (org-pos-in-match-range pos 5)) 'day)
  13410. ((and (or (match-end 8) (match-end 5))
  13411. (> pos (or (match-end 8) (match-end 5)))
  13412. (< pos (match-end 0)))
  13413. (- pos (or (match-end 8) (match-end 5))))
  13414. (t 'day))))
  13415. (defun org-toggle-timestamp-type ()
  13416. "Toggle the type (<active> or [inactive]) of a time stamp."
  13417. (interactive)
  13418. (when (org-at-timestamp-p 'lax)
  13419. (let ((beg (match-beginning 0)) (end (match-end 0))
  13420. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13421. (save-excursion
  13422. (goto-char beg)
  13423. (while (re-search-forward "[][<>]" end t)
  13424. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13425. t t)))
  13426. (message "Timestamp is now %sactive"
  13427. (if (equal (char-after beg) ?<) "" "in")))))
  13428. (defun org-at-clock-log-p ()
  13429. "Non-nil if point is on a clock log line."
  13430. (and (org-match-line org-clock-line-re)
  13431. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13432. (defvar org-clock-history) ; defined in org-clock.el
  13433. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13434. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13435. "Change the date in the time stamp at point.
  13436. The date is changed by N times WHAT. WHAT can be `day', `month',
  13437. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13438. position in the timestamp determines what is changed.
  13439. When optional argument UPDOWN is non-nil, minutes are rounded
  13440. according to `org-time-stamp-rounding-minutes'.
  13441. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13442. \"--2d\"."
  13443. (let ((origin (point))
  13444. (timestamp? (org-at-timestamp-p 'lax))
  13445. origin-cat
  13446. with-hm inactive
  13447. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13448. extra rem
  13449. ts time time0 fixnext clrgx)
  13450. (unless timestamp? (user-error "Not at a timestamp"))
  13451. (if (and (not what) (eq timestamp? 'bracket))
  13452. (org-toggle-timestamp-type)
  13453. ;; Point isn't on brackets. Remember the part of the time-stamp
  13454. ;; the point was in. Indeed, size of time-stamps may change,
  13455. ;; but point must be kept in the same category nonetheless.
  13456. (setq origin-cat timestamp?)
  13457. (when (and (not what) (not (eq timestamp? 'day))
  13458. org-display-custom-times
  13459. (get-text-property (point) 'display)
  13460. (not (get-text-property (1- (point)) 'display)))
  13461. (setq timestamp? 'day))
  13462. (setq timestamp? (or what timestamp?)
  13463. inactive (= (char-after (match-beginning 0)) ?\[)
  13464. ts (match-string 0))
  13465. (replace-match "")
  13466. (when (string-match
  13467. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13468. ts)
  13469. (setq extra (match-string 1 ts))
  13470. (when suppress-tmp-delay
  13471. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13472. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13473. (setq with-hm t))
  13474. (setq time0 (org-parse-time-string ts))
  13475. (when (and updown
  13476. (eq timestamp? 'minute)
  13477. (not current-prefix-arg))
  13478. ;; This looks like s-up and s-down. Change by one rounding step.
  13479. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13480. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13481. (setcar (cdr time0) (+ (nth 1 time0)
  13482. (if (> n 0) (- rem) (- dm rem))))))
  13483. (setq time
  13484. (org-encode-time
  13485. (apply #'list
  13486. (or (car time0) 0)
  13487. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13488. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13489. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13490. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13491. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13492. (nthcdr 6 time0))))
  13493. (when (and (memq timestamp? '(hour minute))
  13494. extra
  13495. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13496. (setq extra (org-modify-ts-extra
  13497. extra
  13498. (if (eq timestamp? 'hour) 2 5)
  13499. n dm)))
  13500. (when (integerp timestamp?)
  13501. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13502. (when (eq what 'calendar)
  13503. (let ((cal-date (org-get-date-from-calendar)))
  13504. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13505. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13506. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13507. (setcar time0 (or (car time0) 0))
  13508. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13509. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13510. (setq time (org-encode-time time0))))
  13511. ;; Insert the new time-stamp, and ensure point stays in the same
  13512. ;; category as before (i.e. not after the last position in that
  13513. ;; category).
  13514. (let ((pos (point)))
  13515. ;; Stay before inserted string. `save-excursion' is of no use.
  13516. (setq org-last-changed-timestamp
  13517. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13518. (goto-char pos))
  13519. (save-match-data
  13520. (looking-at org-ts-regexp3)
  13521. (goto-char
  13522. (pcase origin-cat
  13523. ;; `day' category ends before `hour' if any, or at the end
  13524. ;; of the day name.
  13525. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13526. (`hour (min (match-end 7) origin))
  13527. (`minute (min (1- (match-end 8)) origin))
  13528. ((pred integerp) (min (1- (match-end 0)) origin))
  13529. ;; Point was right after the time-stamp. However, the
  13530. ;; time-stamp length might have changed, so refer to
  13531. ;; (match-end 0) instead.
  13532. (`after (match-end 0))
  13533. ;; `year' and `month' have both fixed size: point couldn't
  13534. ;; have moved into another part.
  13535. (_ origin))))
  13536. ;; Update clock if on a CLOCK line.
  13537. (org-clock-update-time-maybe)
  13538. ;; Maybe adjust the closest clock in `org-clock-history'
  13539. (when org-clock-adjust-closest
  13540. (if (not (and (org-at-clock-log-p)
  13541. (< 1 (length (delq nil (mapcar 'marker-position
  13542. org-clock-history))))))
  13543. (message "No clock to adjust")
  13544. (cond ((save-excursion ; fix previous clock?
  13545. (re-search-backward org-ts-regexp0 nil t)
  13546. (looking-back (concat org-clock-string " \\[")
  13547. (line-beginning-position)))
  13548. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13549. ((save-excursion ; fix next clock?
  13550. (re-search-backward org-ts-regexp0 nil t)
  13551. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13552. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13553. (save-window-excursion
  13554. ;; Find closest clock to point, adjust the previous/next one in history
  13555. (let* ((p (save-excursion (org-back-to-heading t)))
  13556. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13557. (clfixnth
  13558. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13559. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13560. (if (not clfixpos)
  13561. (message "No clock to adjust")
  13562. (save-excursion
  13563. (org-goto-marker-or-bmk clfixpos)
  13564. (org-fold-show-subtree)
  13565. (when (re-search-forward clrgx nil t)
  13566. (goto-char (match-beginning 1))
  13567. (let (org-clock-adjust-closest)
  13568. (org-timestamp-change n timestamp? updown))
  13569. (message "Clock adjusted in %s for heading: %s"
  13570. (file-name-nondirectory (buffer-file-name))
  13571. (org-get-heading t t)))))))))
  13572. ;; Try to recenter the calendar window, if any.
  13573. (when (and org-calendar-follow-timestamp-change
  13574. (get-buffer-window "*Calendar*" t)
  13575. (memq timestamp? '(day month year)))
  13576. (org-recenter-calendar (time-to-days time))))))
  13577. (defun org-modify-ts-extra (s pos n dm)
  13578. "Change the different parts of the lead-time and repeat fields in timestamp."
  13579. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13580. ng h m new rem)
  13581. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13582. (cond
  13583. ((or (org-pos-in-match-range pos 2)
  13584. (org-pos-in-match-range pos 3))
  13585. (setq m (string-to-number (match-string 3 s))
  13586. h (string-to-number (match-string 2 s)))
  13587. (if (org-pos-in-match-range pos 2)
  13588. (setq h (+ h n))
  13589. (setq n (* dm (with-no-warnings (cl-signum n))))
  13590. (unless (= 0 (setq rem (% m dm)))
  13591. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13592. (setq m (+ m n)))
  13593. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13594. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13595. (setq h (mod h 24))
  13596. (setq ng 1 new (format "-%02d:%02d" h m)))
  13597. ((org-pos-in-match-range pos 6)
  13598. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13599. ((org-pos-in-match-range pos 5)
  13600. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13601. ((org-pos-in-match-range pos 9)
  13602. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13603. ((org-pos-in-match-range pos 8)
  13604. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13605. (when ng
  13606. (setq s (concat
  13607. (substring s 0 (match-beginning ng))
  13608. new
  13609. (substring s (match-end ng))))))
  13610. s))
  13611. (defun org-recenter-calendar (d)
  13612. "If the calendar is visible, recenter it to date D."
  13613. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13614. (when cwin
  13615. (let ((calendar-move-hook nil))
  13616. (with-selected-window cwin
  13617. (calendar-goto-date
  13618. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13619. (defun org-goto-calendar (&optional arg)
  13620. "Go to the Emacs calendar at the current date.
  13621. If there is a time stamp in the current line, go to that date.
  13622. A prefix ARG can be used to force the current date."
  13623. (interactive "P")
  13624. (let ((calendar-move-hook nil)
  13625. (calendar-view-holidays-initially-flag nil)
  13626. (calendar-view-diary-initially-flag nil)
  13627. diff)
  13628. (when (or (org-at-timestamp-p 'lax)
  13629. (org-match-line (concat ".*" org-ts-regexp)))
  13630. (let ((d1 (time-to-days nil))
  13631. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13632. (setq diff (- d2 d1))))
  13633. (calendar)
  13634. (calendar-goto-today)
  13635. (when (and diff (not arg)) (calendar-forward-day diff))))
  13636. (defun org-get-date-from-calendar ()
  13637. "Return a list (month day year) of date at point in calendar."
  13638. (with-current-buffer "*Calendar*"
  13639. (save-match-data
  13640. (calendar-cursor-to-date))))
  13641. (defun org-date-from-calendar ()
  13642. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13643. If there is already a time stamp at the cursor position, update it."
  13644. (interactive)
  13645. (if (org-at-timestamp-p 'lax)
  13646. (org-timestamp-change 0 'calendar)
  13647. (let ((cal-date (org-get-date-from-calendar)))
  13648. (org-insert-time-stamp
  13649. (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13650. (defcustom org-image-actual-width t
  13651. "When non-nil, use the actual width of images when inlining them.
  13652. When set to a number, use imagemagick (when available) to set the
  13653. image's width to this value.
  13654. When set to a number in a list, try to get the width from any
  13655. #+ATTR.* keyword if it matches a width specification like
  13656. #+ATTR_HTML: :width 300px
  13657. and fall back on that number if none is found.
  13658. When set to nil, try to get the width from an #+ATTR.* keyword
  13659. and fall back on the original width if none is found.
  13660. When set to any other non-nil value, always use the image width.
  13661. This requires Emacs >= 24.1, built with imagemagick support."
  13662. :group 'org-appearance
  13663. :version "24.4"
  13664. :package-version '(Org . "8.0")
  13665. :type '(choice
  13666. (const :tag "Use the image width" t)
  13667. (integer :tag "Use a number of pixels")
  13668. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13669. (const :tag "Use #+ATTR* or don't resize" nil)))
  13670. (defcustom org-agenda-inhibit-startup nil
  13671. "Inhibit startup when preparing agenda buffers.
  13672. When this variable is t, the initialization of the Org agenda
  13673. buffers is inhibited: e.g. the visibility state is not set, the
  13674. tables are not re-aligned, etc."
  13675. :type 'boolean
  13676. :version "24.3"
  13677. :group 'org-agenda)
  13678. (defcustom org-agenda-ignore-properties nil
  13679. "Avoid updating text properties when building the agenda.
  13680. Properties are used to prepare buffers for effort estimates,
  13681. appointments, statistics and subtree-local categories.
  13682. If you don't use these in the agenda, you can add them to this
  13683. list and agenda building will be a bit faster.
  13684. The value is a list, with zero or more of the symbols `effort', `appt',
  13685. `stats' or `category'."
  13686. :type '(set :greedy t
  13687. (const effort)
  13688. (const appt)
  13689. (const stats)
  13690. (const category))
  13691. :version "26.1"
  13692. :package-version '(Org . "8.3")
  13693. :group 'org-agenda)
  13694. ;;;; Files
  13695. (defun org-save-all-org-buffers ()
  13696. "Save all Org buffers without user confirmation."
  13697. (interactive)
  13698. (message "Saving all Org buffers...")
  13699. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13700. (when (featurep 'org-id) (org-id-locations-save))
  13701. (message "Saving all Org buffers... done"))
  13702. (defun org-revert-all-org-buffers ()
  13703. "Revert all Org buffers.
  13704. Prompt for confirmation when there are unsaved changes.
  13705. Be sure you know what you are doing before letting this function
  13706. overwrite your changes.
  13707. This function is useful in a setup where one tracks Org files
  13708. with a version control system, to revert on one machine after pulling
  13709. changes from another. I believe the procedure must be like this:
  13710. 1. \\[org-save-all-org-buffers]
  13711. 2. Pull changes from the other machine, resolve conflicts
  13712. 3. \\[org-revert-all-org-buffers]"
  13713. (interactive)
  13714. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13715. (user-error "Abort"))
  13716. (save-excursion
  13717. (save-window-excursion
  13718. (dolist (b (buffer-list))
  13719. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13720. (with-current-buffer b buffer-file-name))
  13721. (pop-to-buffer-same-window b)
  13722. (revert-buffer t 'no-confirm)))
  13723. (when (and (featurep 'org-id) org-id-track-globally)
  13724. (org-id-locations-load)))))
  13725. ;;;; Agenda files
  13726. ;;;###autoload
  13727. (defun org-switchb (&optional arg)
  13728. "Switch between Org buffers.
  13729. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13730. With `\\[universal-argument] \\[universal-argument]' \
  13731. prefix, restrict available buffers to agenda files."
  13732. (interactive "P")
  13733. (let ((blist (org-buffer-list
  13734. (cond ((equal arg '(4)) 'files)
  13735. ((equal arg '(16)) 'agenda)))))
  13736. (pop-to-buffer-same-window
  13737. (completing-read "Org buffer: "
  13738. (mapcar #'list (mapcar #'buffer-name blist))
  13739. nil t))))
  13740. (defun org-agenda-files (&optional unrestricted archives)
  13741. "Get the list of agenda files.
  13742. Optional UNRESTRICTED means return the full list even if a restriction
  13743. is currently in place.
  13744. When ARCHIVES is t, include all archive files that are really being
  13745. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13746. `org-agenda-archives-mode' is t."
  13747. (let ((files
  13748. (cond
  13749. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13750. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13751. ((listp org-agenda-files) org-agenda-files)
  13752. (t (error "Invalid value of `org-agenda-files'")))))
  13753. (setq files (apply 'append
  13754. (mapcar (lambda (f)
  13755. (if (file-directory-p f)
  13756. (directory-files
  13757. f t org-agenda-file-regexp)
  13758. (list (expand-file-name f org-directory))))
  13759. files)))
  13760. (when org-agenda-skip-unavailable-files
  13761. (setq files (delq nil
  13762. (mapcar (lambda (file)
  13763. (and (file-readable-p file) file))
  13764. files))))
  13765. (when (or (eq archives t)
  13766. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13767. (setq files (org-add-archive-files files)))
  13768. files))
  13769. (defun org-agenda-file-p (&optional file)
  13770. "Return non-nil, if FILE is an agenda file.
  13771. If FILE is omitted, use the file associated with the current
  13772. buffer."
  13773. (let ((fname (or file (buffer-file-name))))
  13774. (and fname
  13775. (member (file-truename fname)
  13776. (mapcar #'file-truename (org-agenda-files t))))))
  13777. (defun org-edit-agenda-file-list ()
  13778. "Edit the list of agenda files.
  13779. Depending on setup, this either uses customize to edit the variable
  13780. `org-agenda-files', or it visits the file that is holding the list. In the
  13781. latter case, the buffer is set up in a way that saving it automatically kills
  13782. the buffer and restores the previous window configuration."
  13783. (interactive)
  13784. (if (stringp org-agenda-files)
  13785. (let ((cw (current-window-configuration)))
  13786. (find-file org-agenda-files)
  13787. (setq-local org-window-configuration cw)
  13788. (add-hook 'after-save-hook
  13789. (lambda ()
  13790. (set-window-configuration
  13791. (prog1 org-window-configuration
  13792. (kill-buffer (current-buffer))))
  13793. (org-install-agenda-files-menu)
  13794. (message "New agenda file list installed"))
  13795. nil 'local)
  13796. (message "%s" (substitute-command-keys
  13797. "Edit list and finish with \\[save-buffer]")))
  13798. (customize-variable 'org-agenda-files)))
  13799. (defun org-store-new-agenda-file-list (list)
  13800. "Set new value for the agenda file list and save it correctly."
  13801. (if (stringp org-agenda-files)
  13802. (let ((fe (org-read-agenda-file-list t)) b u)
  13803. (while (setq b (find-buffer-visiting org-agenda-files))
  13804. (kill-buffer b))
  13805. (with-temp-file org-agenda-files
  13806. (insert
  13807. (mapconcat
  13808. (lambda (f) ;; Keep un-expanded entries.
  13809. (if (setq u (assoc f fe))
  13810. (cdr u)
  13811. f))
  13812. list "\n")
  13813. "\n")))
  13814. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13815. (org-insert-mode-line-in-empty-file nil))
  13816. (setq org-agenda-files list)
  13817. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13818. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13819. "Read the list of agenda files from a file.
  13820. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13821. filenames, used by `org-store-new-agenda-file-list' to write back
  13822. un-expanded file names."
  13823. (when (file-directory-p org-agenda-files)
  13824. (error "`org-agenda-files' cannot be a single directory"))
  13825. (when (stringp org-agenda-files)
  13826. (with-temp-buffer
  13827. (insert-file-contents org-agenda-files)
  13828. (mapcar
  13829. (lambda (f)
  13830. (let ((e (expand-file-name (substitute-in-file-name f)
  13831. org-directory)))
  13832. (if pair-with-expansion
  13833. (cons e f)
  13834. e)))
  13835. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13836. ;;;###autoload
  13837. (defun org-cycle-agenda-files ()
  13838. "Cycle through the files in `org-agenda-files'.
  13839. If the current buffer visits an agenda file, find the next one in the list.
  13840. If the current buffer does not, find the first agenda file."
  13841. (interactive)
  13842. (let* ((fs (or (org-agenda-files t)
  13843. (user-error "No agenda files")))
  13844. (files (copy-sequence fs))
  13845. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13846. file)
  13847. (when tcf
  13848. (while (and (setq file (pop files))
  13849. (not (equal (file-truename file) tcf)))))
  13850. (find-file (car (or files fs)))
  13851. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13852. (defun org-agenda-file-to-front (&optional to-end)
  13853. "Move/add the current file to the top of the agenda file list.
  13854. If the file is not present in the list, it is added to the front. If it is
  13855. present, it is moved there. With optional argument TO-END, add/move to the
  13856. end of the list."
  13857. (interactive "P")
  13858. (let ((org-agenda-skip-unavailable-files nil)
  13859. (file-alist (mapcar (lambda (x)
  13860. (cons (file-truename x) x))
  13861. (org-agenda-files t)))
  13862. (ctf (file-truename
  13863. (or buffer-file-name
  13864. (user-error "Please save the current buffer to a file"))))
  13865. x had)
  13866. (setq x (assoc ctf file-alist) had x)
  13867. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13868. (if to-end
  13869. (setq file-alist (append (delq x file-alist) (list x)))
  13870. (setq file-alist (cons x (delq x file-alist))))
  13871. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13872. (org-install-agenda-files-menu)
  13873. (message "File %s to %s of agenda file list"
  13874. (if had "moved" "added") (if to-end "end" "front"))))
  13875. (defun org-remove-file (&optional file)
  13876. "Remove current file from the list of files in variable `org-agenda-files'.
  13877. These are the files which are being checked for agenda entries.
  13878. Optional argument FILE means use this file instead of the current."
  13879. (interactive)
  13880. (let* ((org-agenda-skip-unavailable-files nil)
  13881. (file (or file buffer-file-name
  13882. (user-error "Current buffer does not visit a file")))
  13883. (true-file (file-truename file))
  13884. (afile (abbreviate-file-name file))
  13885. (files (delq nil (mapcar
  13886. (lambda (x)
  13887. (unless (equal true-file
  13888. (file-truename x))
  13889. x))
  13890. (org-agenda-files t)))))
  13891. (if (not (= (length files) (length (org-agenda-files t))))
  13892. (progn
  13893. (org-store-new-agenda-file-list files)
  13894. (org-install-agenda-files-menu)
  13895. (message "Removed from Org Agenda list: %s" afile))
  13896. (message "File was not in list: %s (not removed)" afile))))
  13897. (defun org-file-menu-entry (file)
  13898. (vector file (list 'find-file file) t))
  13899. (defun org-check-agenda-file (file)
  13900. "Make sure FILE exists. If not, ask user what to do."
  13901. (unless (file-exists-p file)
  13902. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13903. (abbreviate-file-name file))
  13904. (let ((r (downcase (read-char-exclusive))))
  13905. (cond
  13906. ((equal r ?r)
  13907. (org-remove-file file)
  13908. (throw 'nextfile t))
  13909. (t (user-error "Abort"))))))
  13910. (defun org-get-agenda-file-buffer (file)
  13911. "Get an agenda buffer visiting FILE.
  13912. If the buffer needs to be created, add it to the list of buffers
  13913. which might be released later."
  13914. (let ((buf (org-find-base-buffer-visiting file)))
  13915. (if buf
  13916. buf ; just return it
  13917. ;; Make a new buffer and remember it
  13918. (setq buf (find-file-noselect file))
  13919. (when buf (push buf org-agenda-new-buffers))
  13920. buf)))
  13921. (defun org-release-buffers (blist)
  13922. "Release all buffers in list, asking the user for confirmation when needed.
  13923. When a buffer is unmodified, it is just killed. When modified, it is saved
  13924. \(if the user agrees) and then killed."
  13925. (let (file)
  13926. (dolist (buf blist)
  13927. (setq file (buffer-file-name buf))
  13928. (when (and (buffer-modified-p buf)
  13929. file
  13930. (y-or-n-p (format "Save file %s? " file)))
  13931. (with-current-buffer buf (save-buffer)))
  13932. (kill-buffer buf))))
  13933. (defun org-agenda-prepare-buffers (files)
  13934. "Create buffers for all agenda files, protect archived trees and comments."
  13935. (interactive)
  13936. (let ((inhibit-read-only t)
  13937. (org-inhibit-startup org-agenda-inhibit-startup)
  13938. ;; Do not refresh list of agenda files in the menu when
  13939. ;; opening every new file.
  13940. (org-agenda-file-menu-enabled nil))
  13941. (setq org-tag-alist-for-agenda nil
  13942. org-tag-groups-alist-for-agenda nil)
  13943. (dolist (file files)
  13944. (catch 'nextfile
  13945. (with-current-buffer
  13946. (if (bufferp file)
  13947. file
  13948. (org-check-agenda-file file)
  13949. (org-get-agenda-file-buffer file))
  13950. (org-with-wide-buffer
  13951. (org-set-regexps-and-options 'tags-only)
  13952. (or (memq 'category org-agenda-ignore-properties)
  13953. (org-refresh-category-properties))
  13954. (or (memq 'stats org-agenda-ignore-properties)
  13955. (org-refresh-stats-properties))
  13956. (or (memq 'effort org-agenda-ignore-properties)
  13957. (unless org-element-use-cache
  13958. (org-refresh-effort-properties)))
  13959. (or (memq 'appt org-agenda-ignore-properties)
  13960. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13961. (dolist (el org-todo-keywords-1)
  13962. (unless (member el org-todo-keywords-for-agenda)
  13963. (push el org-todo-keywords-for-agenda)))
  13964. (dolist (el org-done-keywords)
  13965. (unless (member el org-done-keywords-for-agenda)
  13966. (push el org-done-keywords-for-agenda)))
  13967. (setq org-todo-keyword-alist-for-agenda
  13968. (org--tag-add-to-alist
  13969. org-todo-key-alist
  13970. org-todo-keyword-alist-for-agenda))
  13971. (setq org-tag-alist-for-agenda
  13972. (org--tag-add-to-alist
  13973. org-current-tag-alist
  13974. org-tag-alist-for-agenda))
  13975. ;; Merge current file's tag groups into global
  13976. ;; `org-tag-groups-alist-for-agenda'.
  13977. (when org-group-tags
  13978. (dolist (alist org-tag-groups-alist)
  13979. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13980. (if old
  13981. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13982. (push alist org-tag-groups-alist-for-agenda)))))))))
  13983. ;; Refresh the menu once after loading all the agenda buffers.
  13984. (when org-agenda-file-menu-enabled
  13985. (org-install-agenda-files-menu))))
  13986. ;;;; CDLaTeX minor mode
  13987. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13988. "Keymap for the minor `org-cdlatex-mode'.")
  13989. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13990. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13991. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13992. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13993. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13994. (defvar org-cdlatex-texmathp-advice-is-done nil
  13995. "Flag remembering if we have applied the advice to texmathp already.")
  13996. (define-minor-mode org-cdlatex-mode
  13997. "Toggle the minor `org-cdlatex-mode'.
  13998. This mode supports entering LaTeX environment and math in LaTeX fragments
  13999. in Org mode.
  14000. \\{org-cdlatex-mode-map}"
  14001. :lighter " OCDL"
  14002. (when org-cdlatex-mode
  14003. (require 'cdlatex)
  14004. (run-hooks 'cdlatex-mode-hook)
  14005. (cdlatex-compute-tables))
  14006. (unless org-cdlatex-texmathp-advice-is-done
  14007. (setq org-cdlatex-texmathp-advice-is-done t)
  14008. (advice-add 'texmathp :around #'org--math-always-on)))
  14009. (defun org--math-always-on (orig-fun &rest args)
  14010. "Always return t in Org buffers.
  14011. This is because we want to insert math symbols without dollars even outside
  14012. the LaTeX math segments. If Org mode thinks that point is actually inside
  14013. an embedded LaTeX fragment, let `texmathp' do its job.
  14014. `\\[org-cdlatex-mode-map]'"
  14015. (interactive)
  14016. (cond
  14017. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  14018. ((eq this-command 'cdlatex-math-symbol)
  14019. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  14020. t)
  14021. (t
  14022. (let ((p (org-inside-LaTeX-fragment-p)))
  14023. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  14024. (if (member (car p)
  14025. (plist-get org-format-latex-options :matchers))
  14026. (progn
  14027. (setq texmathp-why '("Org mode embedded math" . 0))
  14028. t)
  14029. (apply orig-fun args)))))))
  14030. (defun turn-on-org-cdlatex ()
  14031. "Unconditionally turn on `org-cdlatex-mode'."
  14032. (org-cdlatex-mode 1))
  14033. (defun org-try-cdlatex-tab ()
  14034. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14035. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14036. - inside a LaTeX fragment, or
  14037. - after the first word in a line, where an abbreviation expansion could
  14038. insert a LaTeX environment."
  14039. (when org-cdlatex-mode
  14040. (cond
  14041. ;; Before any word on the line: No expansion possible.
  14042. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14043. ;; Just after first word on the line: Expand it. Make sure it
  14044. ;; cannot happen on headlines, though.
  14045. ((save-excursion
  14046. (skip-chars-backward "a-zA-Z0-9*")
  14047. (skip-chars-backward " \t")
  14048. (and (bolp) (not (org-at-heading-p))))
  14049. (cdlatex-tab) t)
  14050. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14051. (defun org-cdlatex-underscore-caret (&optional _arg)
  14052. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14053. Revert to the normal definition outside of these fragments."
  14054. (interactive "P")
  14055. (if (org-inside-LaTeX-fragment-p)
  14056. (call-interactively 'cdlatex-sub-superscript)
  14057. (let (org-cdlatex-mode)
  14058. (call-interactively (key-binding (vector last-input-event))))))
  14059. (defun org-cdlatex-math-modify (&optional _arg)
  14060. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14061. Revert to the normal definition outside of these fragments."
  14062. (interactive "P")
  14063. (if (org-inside-LaTeX-fragment-p)
  14064. (call-interactively 'cdlatex-math-modify)
  14065. (let (org-cdlatex-mode)
  14066. (call-interactively (key-binding (vector last-input-event))))))
  14067. (defun org-cdlatex-environment-indent (&optional environment item)
  14068. "Execute `cdlatex-environment' and indent the inserted environment.
  14069. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14070. The inserted environment is indented to current indentation
  14071. unless point is at the beginning of the line, in which the
  14072. environment remains unintended."
  14073. (interactive)
  14074. ;; cdlatex-environment always return nil. Therefore, capture output
  14075. ;; first and determine if an environment was selected.
  14076. (let* ((beg (point-marker))
  14077. (end (copy-marker (point) t))
  14078. (inserted (progn
  14079. (ignore-errors (cdlatex-environment environment item))
  14080. (< beg end)))
  14081. ;; Figure out how many lines to move forward after the
  14082. ;; environment has been inserted.
  14083. (lines (when inserted
  14084. (save-excursion
  14085. (- (cl-loop while (< beg (point))
  14086. with x = 0
  14087. do (forward-line -1)
  14088. (cl-incf x)
  14089. finally return x)
  14090. (if (progn (goto-char beg)
  14091. (and (progn (skip-chars-forward " \t") (eolp))
  14092. (progn (skip-chars-backward " \t") (bolp))))
  14093. 1 0)))))
  14094. (env (org-trim (delete-and-extract-region beg end))))
  14095. (when inserted
  14096. ;; Get indentation of next line unless at column 0.
  14097. (let ((ind (if (bolp) 0
  14098. (save-excursion
  14099. (org-return t)
  14100. (prog1 (current-indentation)
  14101. (when (progn (skip-chars-forward " \t") (eolp))
  14102. (delete-region beg (point)))))))
  14103. (bol (progn (skip-chars-backward " \t") (bolp))))
  14104. ;; Insert a newline before environment unless at column zero
  14105. ;; to "escape" the current line. Insert a newline if
  14106. ;; something is one the same line as \end{ENVIRONMENT}.
  14107. (insert
  14108. (concat (unless bol "\n") env
  14109. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14110. (unless (zerop ind)
  14111. (save-excursion
  14112. (goto-char beg)
  14113. (while (< (point) end)
  14114. (unless (eolp) (indent-line-to ind))
  14115. (forward-line))))
  14116. (goto-char beg)
  14117. (forward-line lines)
  14118. (indent-line-to ind)))
  14119. (set-marker beg nil)
  14120. (set-marker end nil)))
  14121. ;;;; LaTeX fragments
  14122. (defun org-inside-LaTeX-fragment-p ()
  14123. "Test if point is inside a LaTeX fragment.
  14124. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14125. sequence appearing also before point.
  14126. Even though the matchers for math are configurable, this function assumes
  14127. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14128. delimiters are skipped when they have been removed by customization.
  14129. The return value is nil, or a cons cell with the delimiter and the
  14130. position of this delimiter.
  14131. This function does a reasonably good job, but can locally be fooled by
  14132. for example currency specifications. For example it will assume being in
  14133. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14134. fragments that are properly closed, but during editing, we have to live
  14135. with the uncertainty caused by missing closing delimiters. This function
  14136. looks only before point, not after."
  14137. (catch 'exit
  14138. (let ((pos (point))
  14139. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14140. (lim (progn
  14141. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14142. 'move)
  14143. (point)))
  14144. dd-on str (start 0) m re)
  14145. (goto-char pos)
  14146. (when dodollar
  14147. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14148. re (nth 1 (assoc "$" org-latex-regexps)))
  14149. (while (string-match re str start)
  14150. (cond
  14151. ((= (match-end 0) (length str))
  14152. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14153. ((= (match-end 0) (- (length str) 5))
  14154. (throw 'exit nil))
  14155. (t (setq start (match-end 0))))))
  14156. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14157. (goto-char pos)
  14158. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14159. (and (match-beginning 2) (throw 'exit nil))
  14160. ;; count $$
  14161. (while (re-search-backward "\\$\\$" lim t)
  14162. (setq dd-on (not dd-on)))
  14163. (goto-char pos)
  14164. (when dd-on (cons "$$" m))))))
  14165. (defun org-inside-latex-macro-p ()
  14166. "Is point inside a LaTeX macro or its arguments?"
  14167. (save-match-data
  14168. (org-in-regexp
  14169. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14170. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14171. "Build an overlay between BEG and END using IMAGE file.
  14172. Argument IMAGETYPE is the extension of the displayed image,
  14173. as a string. It defaults to \"png\"."
  14174. (let ((ov (make-overlay beg end))
  14175. (imagetype (or (intern imagetype) 'png)))
  14176. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14177. (overlay-put ov 'evaporate t)
  14178. (overlay-put ov
  14179. 'modification-hooks
  14180. (list (lambda (o _flag _beg _end &optional _l)
  14181. (delete-overlay o))))
  14182. (overlay-put ov
  14183. 'display
  14184. (list 'image :type imagetype :file image :ascent 'center))))
  14185. (defun org-clear-latex-preview (&optional beg end)
  14186. "Remove all overlays with LaTeX fragment images in current buffer.
  14187. When optional arguments BEG and END are non-nil, remove all
  14188. overlays between them instead. Return a non-nil value when some
  14189. overlays were removed, nil otherwise."
  14190. (let ((overlays
  14191. (cl-remove-if-not
  14192. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14193. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14194. (mapc #'delete-overlay overlays)
  14195. overlays))
  14196. (defun org--latex-preview-region (beg end)
  14197. "Preview LaTeX fragments between BEG and END.
  14198. BEG and END are buffer positions."
  14199. (let ((file (buffer-file-name (buffer-base-buffer))))
  14200. (save-excursion
  14201. (org-format-latex
  14202. (concat org-preview-latex-image-directory "org-ltximg")
  14203. beg end
  14204. ;; Emacs cannot overlay images from remote hosts. Create it in
  14205. ;; `temporary-file-directory' instead.
  14206. (if (or (not file) (file-remote-p file))
  14207. temporary-file-directory
  14208. default-directory)
  14209. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14210. (defun org-latex-preview (&optional arg)
  14211. "Toggle preview of the LaTeX fragment at point.
  14212. If the cursor is on a LaTeX fragment, create the image and
  14213. overlay it over the source code, if there is none. Remove it
  14214. otherwise. If there is no fragment at point, display images for
  14215. all fragments in the current section. With an active region,
  14216. display images for all fragments in the region.
  14217. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14218. for all fragments
  14219. in the current section.
  14220. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14221. argument ARG, display image for all
  14222. fragments in the buffer.
  14223. With a `\\[universal-argument] \\[universal-argument] \
  14224. \\[universal-argument]' prefix argument ARG, clear image for all
  14225. fragments in the buffer."
  14226. (interactive "P")
  14227. (cond
  14228. ((not (display-graphic-p)) nil)
  14229. ;; Clear whole buffer.
  14230. ((equal arg '(64))
  14231. (org-clear-latex-preview (point-min) (point-max))
  14232. (message "LaTeX previews removed from buffer"))
  14233. ;; Preview whole buffer.
  14234. ((equal arg '(16))
  14235. (message "Creating LaTeX previews in buffer...")
  14236. (org--latex-preview-region (point-min) (point-max))
  14237. (message "Creating LaTeX previews in buffer... done."))
  14238. ;; Clear current section.
  14239. ((equal arg '(4))
  14240. (org-clear-latex-preview
  14241. (if (use-region-p)
  14242. (region-beginning)
  14243. (if (org-before-first-heading-p) (point-min)
  14244. (save-excursion
  14245. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14246. (if (use-region-p)
  14247. (region-end)
  14248. (org-with-limited-levels (org-entry-end-position)))))
  14249. ((use-region-p)
  14250. (message "Creating LaTeX previews in region...")
  14251. (org--latex-preview-region (region-beginning) (region-end))
  14252. (message "Creating LaTeX previews in region... done."))
  14253. ;; Toggle preview on LaTeX code at point.
  14254. ((let ((datum (org-element-context)))
  14255. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14256. (let ((beg (org-element-property :begin datum))
  14257. (end (org-element-property :end datum)))
  14258. (if (org-clear-latex-preview beg end)
  14259. (message "LaTeX preview removed")
  14260. (message "Creating LaTeX preview...")
  14261. (org--latex-preview-region beg end)
  14262. (message "Creating LaTeX preview... done."))
  14263. t))))
  14264. ;; Preview current section.
  14265. (t
  14266. (let ((beg (if (org-before-first-heading-p) (point-min)
  14267. (save-excursion
  14268. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14269. (end (org-with-limited-levels (org-entry-end-position))))
  14270. (message "Creating LaTeX previews in section...")
  14271. (org--latex-preview-region beg end)
  14272. (message "Creating LaTeX previews in section... done.")))))
  14273. (defun org-format-latex
  14274. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14275. "Replace LaTeX fragments with links to an image.
  14276. The function takes care of creating the replacement image.
  14277. Only consider fragments between BEG and END when those are
  14278. provided.
  14279. When optional argument OVERLAYS is non-nil, display the image on
  14280. top of the fragment instead of replacing it.
  14281. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14282. Some of the options can be changed using the variable
  14283. `org-format-latex-options', which see."
  14284. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14285. (unless (eq processing-type 'verbatim)
  14286. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14287. (cnt 0)
  14288. checkdir-flag)
  14289. (goto-char (or beg (point-min)))
  14290. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14291. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14292. (overlay-recenter (or end (point-max))))
  14293. (while (re-search-forward math-regexp end t)
  14294. (unless (and overlays
  14295. (eq (get-char-property (point) 'org-overlay-type)
  14296. 'org-latex-overlay))
  14297. (let* ((context (org-element-context))
  14298. (type (org-element-type context)))
  14299. (when (memq type '(latex-environment latex-fragment))
  14300. (let ((block-type (eq type 'latex-environment))
  14301. (value (org-element-property :value context))
  14302. (beg (org-element-property :begin context))
  14303. (end (save-excursion
  14304. (goto-char (org-element-property :end context))
  14305. (skip-chars-backward " \r\t\n")
  14306. (point))))
  14307. (cond
  14308. ((eq processing-type 'mathjax)
  14309. ;; Prepare for MathJax processing.
  14310. (if (not (string-match "\\`\\$\\$?" value))
  14311. (goto-char end)
  14312. (delete-region beg end)
  14313. (if (string= (match-string 0 value) "$$")
  14314. (insert "\\[" (substring value 2 -2) "\\]")
  14315. (insert "\\(" (substring value 1 -1) "\\)"))))
  14316. ((eq processing-type 'html)
  14317. (goto-char beg)
  14318. (delete-region beg end)
  14319. (insert (org-format-latex-as-html value)))
  14320. ((assq processing-type org-preview-latex-process-alist)
  14321. ;; Process to an image.
  14322. (cl-incf cnt)
  14323. (goto-char beg)
  14324. (let* ((processing-info
  14325. (cdr (assq processing-type org-preview-latex-process-alist)))
  14326. (face (face-at-point))
  14327. ;; Get the colors from the face at point.
  14328. (fg
  14329. (let ((color (plist-get org-format-latex-options
  14330. :foreground)))
  14331. (if forbuffer
  14332. (cond
  14333. ((eq color 'auto)
  14334. (face-attribute face :foreground nil 'default))
  14335. ((eq color 'default)
  14336. (face-attribute 'default :foreground nil))
  14337. (t color))
  14338. color)))
  14339. (bg
  14340. (let ((color (plist-get org-format-latex-options
  14341. :background)))
  14342. (if forbuffer
  14343. (cond
  14344. ((eq color 'auto)
  14345. (face-attribute face :background nil 'default))
  14346. ((eq color 'default)
  14347. (face-attribute 'default :background nil))
  14348. (t color))
  14349. color)))
  14350. (hash (sha1 (prin1-to-string
  14351. (list org-format-latex-header
  14352. org-latex-default-packages-alist
  14353. org-latex-packages-alist
  14354. org-format-latex-options
  14355. forbuffer value fg bg))))
  14356. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14357. (absprefix (expand-file-name prefix dir))
  14358. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14359. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14360. (sep (and block-type "\n\n"))
  14361. (link (concat sep "[[file:" linkfile "]]" sep))
  14362. (options
  14363. (org-combine-plists
  14364. org-format-latex-options
  14365. `(:foreground ,fg :background ,bg))))
  14366. (when msg (message msg cnt))
  14367. (unless checkdir-flag ; Ensure the directory exists.
  14368. (setq checkdir-flag t)
  14369. (let ((todir (file-name-directory absprefix)))
  14370. (unless (file-directory-p todir)
  14371. (make-directory todir t))))
  14372. (unless (file-exists-p movefile)
  14373. (org-create-formula-image
  14374. value movefile options forbuffer processing-type))
  14375. (if overlays
  14376. (progn
  14377. (dolist (o (overlays-in beg end))
  14378. (when (eq (overlay-get o 'org-overlay-type)
  14379. 'org-latex-overlay)
  14380. (delete-overlay o)))
  14381. (org--make-preview-overlay beg end movefile imagetype)
  14382. (goto-char end))
  14383. (delete-region beg end)
  14384. (insert
  14385. (org-add-props link
  14386. (list 'org-latex-src
  14387. (replace-regexp-in-string "\"" "" value)
  14388. 'org-latex-src-embed-type
  14389. (if block-type 'paragraph 'character)))))))
  14390. ((eq processing-type 'mathml)
  14391. ;; Process to MathML.
  14392. (unless (org-format-latex-mathml-available-p)
  14393. (user-error "LaTeX to MathML converter not configured"))
  14394. (cl-incf cnt)
  14395. (when msg (message msg cnt))
  14396. (goto-char beg)
  14397. (delete-region beg end)
  14398. (insert (org-format-latex-as-mathml
  14399. value block-type prefix dir)))
  14400. (t
  14401. (error "Unknown conversion process %s for LaTeX fragments"
  14402. processing-type)))))))))))
  14403. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14404. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14405. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14406. successful, return the portion between \"<math...> </math>\"
  14407. elements otherwise return nil. When MATHML-FILE is specified,
  14408. write the results in to that file. When invoked as an
  14409. interactive command, prompt for LATEX-FRAG, with initial value
  14410. set to the current active region and echo the results for user
  14411. inspection."
  14412. (interactive (list (let ((frag (when (org-region-active-p)
  14413. (buffer-substring-no-properties
  14414. (region-beginning) (region-end)))))
  14415. (read-string "LaTeX Fragment: " frag nil frag))))
  14416. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14417. (let* ((tmp-in-file
  14418. (let ((file (file-relative-name
  14419. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14420. (write-region latex-frag nil file)
  14421. file))
  14422. (tmp-out-file (file-relative-name
  14423. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14424. (cmd (format-spec
  14425. org-latex-to-mathml-convert-command
  14426. `((?j . ,(and org-latex-to-mathml-jar-file
  14427. (shell-quote-argument
  14428. (expand-file-name
  14429. org-latex-to-mathml-jar-file))))
  14430. (?I . ,(shell-quote-argument tmp-in-file))
  14431. (?i . ,latex-frag)
  14432. (?o . ,(shell-quote-argument tmp-out-file)))))
  14433. mathml shell-command-output)
  14434. (when (called-interactively-p 'any)
  14435. (unless (org-format-latex-mathml-available-p)
  14436. (user-error "LaTeX to MathML converter not configured")))
  14437. (message "Running %s" cmd)
  14438. (setq shell-command-output (shell-command-to-string cmd))
  14439. (setq mathml
  14440. (when (file-readable-p tmp-out-file)
  14441. (with-current-buffer (find-file-noselect tmp-out-file t)
  14442. (goto-char (point-min))
  14443. (when (re-search-forward
  14444. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14445. (regexp-quote
  14446. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14447. nil t)
  14448. (prog1 (match-string 0) (kill-buffer))))))
  14449. (cond
  14450. (mathml
  14451. (setq mathml
  14452. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14453. (when mathml-file
  14454. (write-region mathml nil mathml-file))
  14455. (when (called-interactively-p 'any)
  14456. (message mathml)))
  14457. ((warn "LaTeX to MathML conversion failed")
  14458. (message shell-command-output)))
  14459. (delete-file tmp-in-file)
  14460. (when (file-exists-p tmp-out-file)
  14461. (delete-file tmp-out-file))
  14462. mathml))
  14463. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14464. prefix &optional dir)
  14465. "Use `org-create-math-formula' but check local cache first."
  14466. (let* ((absprefix (expand-file-name prefix dir))
  14467. (print-length nil) (print-level nil)
  14468. (formula-id (concat
  14469. "formula-"
  14470. (sha1
  14471. (prin1-to-string
  14472. (list latex-frag
  14473. org-latex-to-mathml-convert-command)))))
  14474. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14475. (formula-cache-dir (file-name-directory formula-cache)))
  14476. (unless (file-directory-p formula-cache-dir)
  14477. (make-directory formula-cache-dir t))
  14478. (unless (file-exists-p formula-cache)
  14479. (org-create-math-formula latex-frag formula-cache))
  14480. (if (file-exists-p formula-cache)
  14481. ;; Successful conversion. Return the link to MathML file.
  14482. (org-add-props
  14483. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14484. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14485. 'org-latex-src-embed-type (if latex-frag-type
  14486. 'paragraph 'character)))
  14487. ;; Failed conversion. Return the LaTeX fragment verbatim
  14488. latex-frag)))
  14489. (defun org-format-latex-as-html (latex-fragment)
  14490. "Convert LATEX-FRAGMENT to HTML.
  14491. This uses `org-latex-to-html-convert-command', which see."
  14492. (let ((cmd (format-spec org-latex-to-html-convert-command
  14493. `((?i . ,latex-fragment)))))
  14494. (message "Running %s" cmd)
  14495. (shell-command-to-string cmd)))
  14496. (defun org--get-display-dpi ()
  14497. "Get the DPI of the display.
  14498. The function assumes that the display has the same pixel width in
  14499. the horizontal and vertical directions."
  14500. (if (display-graphic-p)
  14501. (round (/ (display-pixel-height)
  14502. (/ (display-mm-height) 25.4)))
  14503. (error "Attempt to calculate the dpi of a non-graphic display")))
  14504. (defun org-create-formula-image
  14505. (string tofile options buffer &optional processing-type)
  14506. "Create an image from LaTeX source using external processes.
  14507. The LaTeX STRING is saved to a temporary LaTeX file, then
  14508. converted to an image file by process PROCESSING-TYPE defined in
  14509. `org-preview-latex-process-alist'. A nil value defaults to
  14510. `org-preview-latex-default-process'.
  14511. The generated image file is eventually moved to TOFILE.
  14512. The OPTIONS argument controls the size, foreground color and
  14513. background color of the generated image.
  14514. When BUFFER non-nil, this function is used for LaTeX previewing.
  14515. Otherwise, it is used to deal with LaTeX snippets showed in
  14516. a HTML file."
  14517. (let* ((processing-type (or processing-type
  14518. org-preview-latex-default-process))
  14519. (processing-info
  14520. (cdr (assq processing-type org-preview-latex-process-alist)))
  14521. (programs (plist-get processing-info :programs))
  14522. (error-message (or (plist-get processing-info :message) ""))
  14523. (image-input-type (plist-get processing-info :image-input-type))
  14524. (image-output-type (plist-get processing-info :image-output-type))
  14525. (post-clean (or (plist-get processing-info :post-clean)
  14526. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14527. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14528. (latex-header
  14529. (or (plist-get processing-info :latex-header)
  14530. (org-latex-make-preamble
  14531. (org-export-get-environment (org-export-get-backend 'latex))
  14532. org-format-latex-header
  14533. 'snippet)))
  14534. (latex-compiler (plist-get processing-info :latex-compiler))
  14535. (tmpdir temporary-file-directory)
  14536. (texfilebase (make-temp-name
  14537. (expand-file-name "orgtex" tmpdir)))
  14538. (texfile (concat texfilebase ".tex"))
  14539. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14540. '(1.0 . 1.0)))
  14541. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14542. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14543. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14544. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14545. "Black"))
  14546. (bg (or (plist-get options (if buffer :background :html-background))
  14547. "Transparent"))
  14548. (image-converter
  14549. (or (and (string= bg "Transparent")
  14550. (plist-get processing-info :transparent-image-converter))
  14551. (plist-get processing-info :image-converter)))
  14552. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14553. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14554. (dolist (program programs)
  14555. (org-check-external-command program error-message))
  14556. (if (eq fg 'default)
  14557. (setq fg (org-latex-color :foreground))
  14558. (setq fg (org-latex-color-format fg)))
  14559. (setq bg (cond
  14560. ((eq bg 'default) (org-latex-color :background))
  14561. ((string= bg "Transparent") nil)
  14562. (t (org-latex-color-format bg))))
  14563. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14564. (if (string-suffix-p string "\n")
  14565. (aset string (1- (length string)) ?%)
  14566. (setq string (concat string "%")))
  14567. (with-temp-file texfile
  14568. (insert latex-header)
  14569. (insert "\n\\begin{document}\n"
  14570. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14571. (if bg
  14572. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14573. "\n\\pagecolor{bg}%\n")
  14574. "")
  14575. "\n{\\color{fg}\n"
  14576. string
  14577. "\n}\n"
  14578. "\n\\end{document}\n"))
  14579. (let* ((err-msg (format "Please adjust `%s' part of \
  14580. `org-preview-latex-process-alist'."
  14581. processing-type))
  14582. (image-input-file
  14583. (org-compile-file
  14584. texfile latex-compiler image-input-type err-msg log-buf))
  14585. (image-output-file
  14586. (org-compile-file
  14587. image-input-file image-converter image-output-type err-msg log-buf
  14588. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14589. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14590. (copy-file image-output-file tofile 'replace)
  14591. (dolist (e post-clean)
  14592. (when (file-exists-p (concat texfilebase e))
  14593. (delete-file (concat texfilebase e))))
  14594. image-output-file)))
  14595. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14596. "Fill a LaTeX header template TPL.
  14597. In the template, the following place holders will be recognized:
  14598. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14599. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14600. [PACKAGES] \\usepackage statements for PKG
  14601. [NO-PACKAGES] do not include PKG
  14602. [EXTRA] the string EXTRA
  14603. [NO-EXTRA] do not include EXTRA
  14604. For backward compatibility, if both the positive and the negative place
  14605. holder is missing, the positive one (without the \"NO-\") will be
  14606. assumed to be present at the end of the template.
  14607. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14608. EXTRA is a string.
  14609. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14610. (let (rpl (end ""))
  14611. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14612. (setq rpl (if (or (match-end 1) (not def-pkg))
  14613. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14614. tpl (replace-match rpl t t tpl))
  14615. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14616. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14617. (setq rpl (if (or (match-end 1) (not pkg))
  14618. "" (org-latex-packages-to-string pkg snippets-p t))
  14619. tpl (replace-match rpl t t tpl))
  14620. (when pkg (setq end
  14621. (concat end "\n"
  14622. (org-latex-packages-to-string pkg snippets-p)))))
  14623. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14624. (setq rpl (if (or (match-end 1) (not extra))
  14625. "" (concat extra "\n"))
  14626. tpl (replace-match rpl t t tpl))
  14627. (when (and extra (string-match "\\S-" extra))
  14628. (setq end (concat end "\n" extra))))
  14629. (if (string-match "\\S-" end)
  14630. (concat tpl "\n" end)
  14631. tpl)))
  14632. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14633. "Turn an alist of packages into a string with the \\usepackage macros."
  14634. (setq pkg (mapconcat (lambda(p)
  14635. (cond
  14636. ((stringp p) p)
  14637. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14638. (format "%% Package %s omitted" (cadr p)))
  14639. ((equal "" (car p))
  14640. (format "\\usepackage{%s}" (cadr p)))
  14641. (t
  14642. (format "\\usepackage[%s]{%s}"
  14643. (car p) (cadr p)))))
  14644. pkg
  14645. "\n"))
  14646. (if newline (concat pkg "\n") pkg))
  14647. (defun org-dvipng-color (attr)
  14648. "Return a RGB color specification for dvipng."
  14649. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14650. (defun org-dvipng-color-format (color-name)
  14651. "Convert COLOR-NAME to a RGB color value for dvipng."
  14652. (apply #'format "rgb %s %s %s"
  14653. (mapcar 'org-normalize-color
  14654. (color-values color-name))))
  14655. (defun org-latex-color (attr)
  14656. "Return a RGB color for the LaTeX color package."
  14657. (org-latex-color-format (face-attribute 'default attr nil)))
  14658. (defun org-latex-color-format (color-name)
  14659. "Convert COLOR-NAME to a RGB color value."
  14660. (apply #'format "%s,%s,%s"
  14661. (mapcar 'org-normalize-color
  14662. (color-values color-name))))
  14663. (defun org-normalize-color (value)
  14664. "Return string to be used as color value for an RGB component."
  14665. (format "%g" (/ value 65535.0)))
  14666. ;; Image display
  14667. (defvar-local org-inline-image-overlays nil)
  14668. (defun org-toggle-inline-images (&optional include-linked)
  14669. "Toggle the display of inline images.
  14670. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14671. (interactive "P")
  14672. (if org-inline-image-overlays
  14673. (progn
  14674. (org-remove-inline-images)
  14675. (when (called-interactively-p 'interactive)
  14676. (message "Inline image display turned off")))
  14677. (org-display-inline-images include-linked)
  14678. (when (called-interactively-p 'interactive)
  14679. (message (if org-inline-image-overlays
  14680. (format "%d images displayed inline"
  14681. (length org-inline-image-overlays))
  14682. "No images to display inline")))))
  14683. (defun org-redisplay-inline-images ()
  14684. "Assure display of inline images and refresh them."
  14685. (interactive)
  14686. (org-toggle-inline-images)
  14687. (unless org-inline-image-overlays
  14688. (org-toggle-inline-images)))
  14689. ;; For without-x builds.
  14690. (declare-function image-flush "image" (spec &optional frame))
  14691. (defcustom org-display-remote-inline-images 'skip
  14692. "How to display remote inline images.
  14693. Possible values of this option are:
  14694. skip Don't display remote images.
  14695. download Always download and display remote images.
  14696. cache Display remote images, and open them in separate buffers
  14697. for caching. Silently update the image buffer when a file
  14698. change is detected."
  14699. :group 'org-appearance
  14700. :package-version '(Org . "9.4")
  14701. :type '(choice
  14702. (const :tag "Ignore remote images" skip)
  14703. (const :tag "Always display remote images" download)
  14704. (const :tag "Display and silently update remote images" cache))
  14705. :safe #'symbolp)
  14706. (defun org--create-inline-image (file width)
  14707. "Create image located at FILE, or return nil.
  14708. WIDTH is the width of the image. The image may not be created
  14709. according to the value of `org-display-remote-inline-images'."
  14710. (let* ((remote? (file-remote-p file))
  14711. (file-or-data
  14712. (pcase org-display-remote-inline-images
  14713. ((guard (not remote?)) file)
  14714. (`download (with-temp-buffer
  14715. (set-buffer-multibyte nil)
  14716. (insert-file-contents-literally file)
  14717. (buffer-string)))
  14718. (`cache (let ((revert-without-query '(".")))
  14719. (with-current-buffer (find-file-noselect file)
  14720. (buffer-string))))
  14721. (`skip nil)
  14722. (other
  14723. (message "Invalid value of `org-display-remote-inline-images': %S"
  14724. other)
  14725. nil))))
  14726. (when file-or-data
  14727. (create-image file-or-data
  14728. (and (image-type-available-p 'imagemagick)
  14729. width
  14730. 'imagemagick)
  14731. remote?
  14732. :width width :scale 1))))
  14733. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14734. "Display inline images.
  14735. An inline image is a link which follows either of these
  14736. conventions:
  14737. 1. Its path is a file with an extension matching return value
  14738. from `image-file-name-regexp' and it has no contents.
  14739. 2. Its description consists in a single link of the previous
  14740. type. In this case, that link must be a well-formed plain
  14741. or angle link, i.e., it must have an explicit \"file\" type.
  14742. Equip each image with the key-map `image-map'.
  14743. When optional argument INCLUDE-LINKED is non-nil, also links with
  14744. a text description part will be inlined. This can be nice for
  14745. a quick look at those images, but it does not reflect what
  14746. exported files will look like.
  14747. When optional argument REFRESH is non-nil, refresh existing
  14748. images between BEG and END. This will create new image displays
  14749. only if necessary.
  14750. BEG and END define the considered part. They default to the
  14751. buffer boundaries with possible narrowing."
  14752. (interactive "P")
  14753. (when (display-graphic-p)
  14754. (unless refresh
  14755. (org-remove-inline-images)
  14756. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14757. (let ((end (or end (point-max))))
  14758. (org-with-point-at (or beg (point-min))
  14759. (let* ((case-fold-search t)
  14760. (file-extension-re (image-file-name-regexp))
  14761. (link-abbrevs (mapcar #'car
  14762. (append org-link-abbrev-alist-local
  14763. org-link-abbrev-alist)))
  14764. ;; Check absolute, relative file names and explicit
  14765. ;; "file:" links. Also check link abbreviations since
  14766. ;; some might expand to "file" links.
  14767. (file-types-re
  14768. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14769. (if (not link-abbrevs) ""
  14770. (concat "\\|" (regexp-opt link-abbrevs))))))
  14771. (while (re-search-forward file-types-re end t)
  14772. (let* ((link (org-element-lineage
  14773. (save-match-data (org-element-context))
  14774. '(link) t))
  14775. (linktype (org-element-property :type link))
  14776. (inner-start (match-beginning 1))
  14777. (path
  14778. (cond
  14779. ;; No link at point; no inline image.
  14780. ((not link) nil)
  14781. ;; File link without a description. Also handle
  14782. ;; INCLUDE-LINKED here since it should have
  14783. ;; precedence over the next case. I.e., if link
  14784. ;; contains filenames in both the path and the
  14785. ;; description, prioritize the path only when
  14786. ;; INCLUDE-LINKED is non-nil.
  14787. ((or (not (org-element-property :contents-begin link))
  14788. include-linked)
  14789. (and (or (equal "file" linktype)
  14790. (equal "attachment" linktype))
  14791. (org-element-property :path link)))
  14792. ;; Link with a description. Check if description
  14793. ;; is a filename. Even if Org doesn't have syntax
  14794. ;; for those -- clickable image -- constructs, fake
  14795. ;; them, as in `org-export-insert-image-links'.
  14796. ((not inner-start) nil)
  14797. (t
  14798. (org-with-point-at inner-start
  14799. (and (looking-at
  14800. (if (char-equal ?< (char-after inner-start))
  14801. org-link-angle-re
  14802. org-link-plain-re))
  14803. ;; File name must fill the whole
  14804. ;; description.
  14805. (= (org-element-property :contents-end link)
  14806. (match-end 0))
  14807. (match-string 2)))))))
  14808. (when (and path (string-match-p file-extension-re path))
  14809. (let ((file (if (equal "attachment" linktype)
  14810. (progn
  14811. (require 'org-attach)
  14812. (ignore-errors (org-attach-expand path)))
  14813. (expand-file-name path))))
  14814. (when (and file (file-exists-p file))
  14815. (let ((width (org-display-inline-image--width link))
  14816. (old (get-char-property-and-overlay
  14817. (org-element-property :begin link)
  14818. 'org-image-overlay)))
  14819. (if (and (car-safe old) refresh)
  14820. (image-flush (overlay-get (cdr old) 'display))
  14821. (let ((image (org--create-inline-image file width)))
  14822. (when image
  14823. (let ((ov (make-overlay
  14824. (org-element-property :begin link)
  14825. (progn
  14826. (goto-char
  14827. (org-element-property :end link))
  14828. (skip-chars-backward " \t")
  14829. (point)))))
  14830. (overlay-put ov 'display image)
  14831. (overlay-put ov 'face 'default)
  14832. (overlay-put ov 'org-image-overlay t)
  14833. (overlay-put
  14834. ov 'modification-hooks
  14835. (list 'org-display-inline-remove-overlay))
  14836. (when (boundp 'image-map)
  14837. (overlay-put ov 'keymap image-map))
  14838. (push ov org-inline-image-overlays))))))))))))))))
  14839. (defvar visual-fill-column-width) ; Silence compiler warning
  14840. (defun org-display-inline-image--width (link)
  14841. "Determine the display width of the image LINK, in pixels.
  14842. - When `org-image-actual-width' is t, the image's pixel width is used.
  14843. - When `org-image-actual-width' is a number, that value will is used.
  14844. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14845. set (if it exists) is used to set the image width. A width of X% is
  14846. divided by 100.
  14847. If no :width attribute is given and `org-image-actual-width' is a list with
  14848. a number as the car, then that number is used as the default value.
  14849. If the value is a float between 0 and 2, it interpreted as that proportion
  14850. of the text width in the buffer."
  14851. ;; Apply `org-image-actual-width' specifications.
  14852. ;; Support subtree-level property "ORG-IMAGE-ACTUAL-WIDTH" specified
  14853. ;; width.
  14854. (let ((org-image-actual-width (org-property-or-variable-value 'org-image-actual-width)))
  14855. (cond
  14856. ((eq org-image-actual-width t) nil)
  14857. ((listp org-image-actual-width)
  14858. (let* ((case-fold-search t)
  14859. (par (org-element-lineage link '(paragraph)))
  14860. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14861. (par-end (org-element-property :post-affiliated par))
  14862. ;; Try to find an attribute providing a :width.
  14863. (attr-width
  14864. (when (and par (org-with-point-at
  14865. (org-element-property :begin par)
  14866. (re-search-forward attr-re par-end t)))
  14867. (match-string 1)))
  14868. (width
  14869. (cond
  14870. ;; Treat :width t as if `org-image-actual-width' were t.
  14871. ((string= attr-width "t") nil)
  14872. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14873. ((or (null attr-width)
  14874. (string-match-p "\\`[^0-9]" attr-width))
  14875. (car org-image-actual-width))
  14876. ;; Convert numeric widths to numbers, converting percentages.
  14877. ((string-match-p "\\`[0-9.]+%" attr-width)
  14878. (/ (string-to-number attr-width) 100.0))
  14879. (t (string-to-number attr-width)))))
  14880. (if (and (floatp width) (<= 0.0 width 2.0))
  14881. ;; A float in [0,2] should be interpereted as this portion of
  14882. ;; the text width in the window. This works well with cases like
  14883. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14884. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14885. ;; bound as cases such as 1.2\linewidth are feasible.
  14886. (round (* width
  14887. (window-pixel-width)
  14888. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14889. (or visual-fill-column-width auto-fill-function))
  14890. (when auto-fill-function fill-column)
  14891. (- (window-text-width) (line-number-display-width)))
  14892. (float (window-total-width)))))
  14893. width)))
  14894. ((numberp org-image-actual-width)
  14895. org-image-actual-width)
  14896. (t nil))))
  14897. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14898. "Remove inline-display overlay if a corresponding region is modified."
  14899. (let ((inhibit-modification-hooks t))
  14900. (when (and ov after)
  14901. (delete ov org-inline-image-overlays)
  14902. (delete-overlay ov))))
  14903. (defun org-remove-inline-images ()
  14904. "Remove inline display of images."
  14905. (interactive)
  14906. (mapc #'delete-overlay org-inline-image-overlays)
  14907. (setq org-inline-image-overlays nil))
  14908. (defvar org-self-insert-command-undo-counter 0)
  14909. (defvar org-speed-command nil)
  14910. (defun org-fix-tags-on-the-fly ()
  14911. "Align tags in headline at point.
  14912. Unlike `org-align-tags', this function does nothing if point is
  14913. either not currently on a tagged headline or on a tag."
  14914. (when (and (org-match-line org-tag-line-re)
  14915. (< (point) (match-beginning 1)))
  14916. (org-align-tags)))
  14917. (defun org-self-insert-command (N)
  14918. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14919. If the cursor is in a table looking at whitespace, the whitespace is
  14920. overwritten, and the table is not marked as requiring realignment."
  14921. (interactive "p")
  14922. (org-fold-check-before-invisible-edit 'insert)
  14923. (cond
  14924. ((and org-use-speed-commands
  14925. (let ((kv (this-command-keys-vector)))
  14926. (setq org-speed-command
  14927. (run-hook-with-args-until-success
  14928. 'org-speed-command-hook
  14929. (make-string 1 (aref kv (1- (length kv))))))))
  14930. (cond
  14931. ((commandp org-speed-command)
  14932. (setq this-command org-speed-command)
  14933. (call-interactively org-speed-command))
  14934. ((functionp org-speed-command)
  14935. (funcall org-speed-command))
  14936. ((consp org-speed-command)
  14937. (eval org-speed-command t))
  14938. (t (let (org-use-speed-commands)
  14939. (call-interactively 'org-self-insert-command)))))
  14940. ((and
  14941. (= N 1)
  14942. (not (org-region-active-p))
  14943. (org-at-table-p)
  14944. (progn
  14945. ;; Check if we blank the field, and if that triggers align.
  14946. (and (featurep 'org-table)
  14947. org-table-auto-blank-field
  14948. (memq last-command
  14949. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14950. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14951. ;; Got extra space, this field does not determine
  14952. ;; column width.
  14953. (let (org-table-may-need-update) (org-table-blank-field))
  14954. ;; No extra space, this field may determine column
  14955. ;; width.
  14956. (org-table-blank-field)))
  14957. t)
  14958. (looking-at "[^|\n]* |"))
  14959. ;; There is room for insertion without re-aligning the table.
  14960. (self-insert-command N)
  14961. (org-table-with-shrunk-field
  14962. (save-excursion
  14963. (skip-chars-forward "^|")
  14964. ;; Do not delete last space, which is
  14965. ;; `org-table-separator-space', but the regular space before
  14966. ;; it.
  14967. (delete-region (- (point) 2) (1- (point))))))
  14968. (t
  14969. (setq org-table-may-need-update t)
  14970. (self-insert-command N)
  14971. (org-fix-tags-on-the-fly)
  14972. (when org-self-insert-cluster-for-undo
  14973. (if (not (eq last-command 'org-self-insert-command))
  14974. (setq org-self-insert-command-undo-counter 1)
  14975. (if (>= org-self-insert-command-undo-counter 20)
  14976. (setq org-self-insert-command-undo-counter 1)
  14977. (and (> org-self-insert-command-undo-counter 0)
  14978. buffer-undo-list (listp buffer-undo-list)
  14979. (not (cadr buffer-undo-list)) ; remove nil entry
  14980. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14981. (setq org-self-insert-command-undo-counter
  14982. (1+ org-self-insert-command-undo-counter))))))))
  14983. (defun org-delete-backward-char (N)
  14984. "Like `delete-backward-char', insert whitespace at field end in tables.
  14985. When deleting backwards, in tables this function will insert whitespace in
  14986. front of the next \"|\" separator, to keep the table aligned. The table will
  14987. still be marked for re-alignment if the field did fill the entire column,
  14988. because, in this case the deletion might narrow the column."
  14989. (interactive "p")
  14990. (save-match-data
  14991. (org-fold-check-before-invisible-edit 'delete-backward)
  14992. (if (and (= N 1)
  14993. (not overwrite-mode)
  14994. (not (org-region-active-p))
  14995. (not (eq (char-before) ?|))
  14996. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14997. (looking-at-p ".*?|")
  14998. (org-at-table-p))
  14999. (progn (forward-char -1) (org-delete-char 1))
  15000. (backward-delete-char N)
  15001. (org-fix-tags-on-the-fly))))
  15002. (defun org-delete-char (N)
  15003. "Like `delete-char', but insert whitespace at field end in tables.
  15004. When deleting characters, in tables this function will insert whitespace in
  15005. front of the next \"|\" separator, to keep the table aligned. The table will
  15006. still be marked for re-alignment if the field did fill the entire column,
  15007. because, in this case the deletion might narrow the column."
  15008. (interactive "p")
  15009. (save-match-data
  15010. (org-fold-check-before-invisible-edit 'delete)
  15011. (cond
  15012. ((or (/= N 1)
  15013. (eq (char-after) ?|)
  15014. (save-excursion (skip-chars-backward " \t") (bolp))
  15015. (not (org-at-table-p)))
  15016. (delete-char N)
  15017. (org-fix-tags-on-the-fly))
  15018. ((looking-at ".\\(.*?\\)|")
  15019. (let* ((update? org-table-may-need-update)
  15020. (noalign (looking-at-p ".*? |")))
  15021. (delete-char 1)
  15022. (org-table-with-shrunk-field
  15023. (save-excursion
  15024. ;; Last space is `org-table-separator-space', so insert
  15025. ;; a regular one before it instead.
  15026. (goto-char (- (match-end 0) 2))
  15027. (insert " ")))
  15028. ;; If there were two spaces at the end, this field does not
  15029. ;; determine the width of the column.
  15030. (when noalign (setq org-table-may-need-update update?))))
  15031. (t
  15032. (delete-char N)))))
  15033. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15034. (put 'org-self-insert-command 'delete-selection
  15035. (lambda ()
  15036. (not (run-hook-with-args-until-success
  15037. 'self-insert-uses-region-functions))))
  15038. (put 'orgtbl-self-insert-command 'delete-selection
  15039. (lambda ()
  15040. (not (run-hook-with-args-until-success
  15041. 'self-insert-uses-region-functions))))
  15042. (put 'org-delete-char 'delete-selection 'supersede)
  15043. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15044. (put 'org-yank 'delete-selection 'yank)
  15045. (put 'org-return 'delete-selection t)
  15046. ;; Make `flyspell-mode' delay after some commands
  15047. (put 'org-self-insert-command 'flyspell-delayed t)
  15048. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15049. (put 'org-delete-char 'flyspell-delayed t)
  15050. (put 'org-delete-backward-char 'flyspell-delayed t)
  15051. ;; Make pabbrev-mode expand after Org mode commands
  15052. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15053. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15054. (defun org-transpose-words ()
  15055. "Transpose words for Org.
  15056. This uses the `org-mode-transpose-word-syntax-table' syntax
  15057. table, which interprets characters in `org-emphasis-alist' as
  15058. word constituents."
  15059. (interactive)
  15060. (with-syntax-table org-mode-transpose-word-syntax-table
  15061. (call-interactively 'transpose-words)))
  15062. (defvar org-ctrl-c-ctrl-c-hook nil
  15063. "Hook for functions attaching themselves to `C-c C-c'.
  15064. This can be used to add additional functionality to the `C-c C-c'
  15065. key which executes context-dependent commands. This hook is run
  15066. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15067. run after the last test.
  15068. Each function will be called with no arguments. The function
  15069. must check if the context is appropriate for it to act. If yes,
  15070. it should do its thing and then return a non-nil value. If the
  15071. context is wrong, just do nothing and return nil.")
  15072. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15073. "Hook for functions attaching themselves to `C-c C-c'.
  15074. This can be used to add additional functionality to the `C-c C-c'
  15075. key which executes context-dependent commands. This hook is run
  15076. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15077. before the first test.
  15078. Each function will be called with no arguments. The function
  15079. must check if the context is appropriate for it to act. If yes,
  15080. it should do its thing and then return a non-nil value. If the
  15081. context is wrong, just do nothing and return nil.")
  15082. (defvar org-tab-after-check-for-table-hook nil
  15083. "Hook for functions to attach themselves to TAB.
  15084. See `org-ctrl-c-ctrl-c-hook' for more information.
  15085. This hook runs after it has been established that the cursor is not in a
  15086. table, but before checking if the cursor is in a headline or if global cycling
  15087. should be done.
  15088. If any function in this hook returns t, not other actions like visibility
  15089. cycling will be done.")
  15090. (defvar org-tab-after-check-for-cycling-hook nil
  15091. "Hook for functions to attach themselves to TAB.
  15092. See `org-ctrl-c-ctrl-c-hook' for more information.
  15093. This hook runs after it has been established that not table field motion and
  15094. not visibility should be done because of current context. This is probably
  15095. the place where a package like yasnippets can hook in.")
  15096. (defvar org-tab-before-tab-emulation-hook nil
  15097. "Hook for functions to attach themselves to TAB.
  15098. See `org-ctrl-c-ctrl-c-hook' for more information.
  15099. This hook runs after every other options for TAB have been exhausted, but
  15100. before indentation and \t insertion takes place.")
  15101. (defvar org-metaleft-hook nil
  15102. "Hook for functions attaching themselves to `M-left'.
  15103. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15104. (defvar org-metaright-hook nil
  15105. "Hook for functions attaching themselves to `M-right'.
  15106. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15107. (defvar org-metaup-hook nil
  15108. "Hook for functions attaching themselves to `M-up'.
  15109. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15110. (defvar org-metadown-hook nil
  15111. "Hook for functions attaching themselves to `M-down'.
  15112. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15113. (defvar org-shiftmetaleft-hook nil
  15114. "Hook for functions attaching themselves to `M-S-left'.
  15115. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15116. (defvar org-shiftmetaright-hook nil
  15117. "Hook for functions attaching themselves to `M-S-right'.
  15118. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15119. (defvar org-shiftmetaup-hook nil
  15120. "Hook for functions attaching themselves to `M-S-up'.
  15121. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15122. (defvar org-shiftmetadown-hook nil
  15123. "Hook for functions attaching themselves to `M-S-down'.
  15124. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15125. (defvar org-metareturn-hook nil
  15126. "Hook for functions attaching themselves to `M-RET'.
  15127. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15128. (defvar org-shiftup-hook nil
  15129. "Hook for functions attaching themselves to `S-up'.
  15130. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15131. (defvar org-shiftup-final-hook nil
  15132. "Hook for functions attaching themselves to `S-up'.
  15133. This one runs after all other options except shift-select have been excluded.
  15134. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15135. (defvar org-shiftdown-hook nil
  15136. "Hook for functions attaching themselves to `S-down'.
  15137. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15138. (defvar org-shiftdown-final-hook nil
  15139. "Hook for functions attaching themselves to `S-down'.
  15140. This one runs after all other options except shift-select have been excluded.
  15141. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15142. (defvar org-shiftleft-hook nil
  15143. "Hook for functions attaching themselves to `S-left'.
  15144. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15145. (defvar org-shiftleft-final-hook nil
  15146. "Hook for functions attaching themselves to `S-left'.
  15147. This one runs after all other options except shift-select have been excluded.
  15148. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15149. (defvar org-shiftright-hook nil
  15150. "Hook for functions attaching themselves to `S-right'.
  15151. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15152. (defvar org-shiftright-final-hook nil
  15153. "Hook for functions attaching themselves to `S-right'.
  15154. This one runs after all other options except shift-select have been excluded.
  15155. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15156. (defun org-modifier-cursor-error ()
  15157. "Throw an error, a modified cursor command was applied in wrong context."
  15158. (user-error "This command is active in special context like tables, headlines or items"))
  15159. (defun org-shiftselect-error ()
  15160. "Throw an error because Shift-Cursor command was applied in wrong context."
  15161. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15162. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15163. (user-error "This command works only in special context like headlines or timestamps")))
  15164. (defun org-call-for-shift-select (cmd)
  15165. (let ((this-command-keys-shift-translated t))
  15166. (call-interactively cmd)))
  15167. (defun org-shifttab (&optional arg)
  15168. "Global visibility cycling or move to previous table field.
  15169. Call `org-table-previous-field' within a table.
  15170. When ARG is nil, cycle globally through visibility states.
  15171. When ARG is a numeric prefix, show contents of this level."
  15172. (interactive "P")
  15173. (cond
  15174. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15175. ((integerp arg)
  15176. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15177. (message "Content view to level: %d" arg)
  15178. (org-cycle-content (prefix-numeric-value arg2))
  15179. (org-cycle-show-empty-lines t)
  15180. (setq org-cycle-global-status 'overview)
  15181. (run-hook-with-args 'org-cycle-hook 'overview)))
  15182. (t (call-interactively 'org-cycle-global))))
  15183. (defun org-shiftmetaleft ()
  15184. "Promote subtree or delete table column.
  15185. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15186. `org-table-delete-column', depending on context. See the
  15187. individual commands for more information."
  15188. (interactive)
  15189. (cond
  15190. ((and (eq system-type 'darwin)
  15191. (or (eq org-support-shift-select 'always)
  15192. (and org-support-shift-select (org-region-active-p))))
  15193. (org-call-for-shift-select 'backward-char))
  15194. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15195. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15196. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15197. ((if (not (org-region-active-p)) (org-at-item-p)
  15198. (save-excursion (goto-char (region-beginning))
  15199. (org-at-item-p)))
  15200. (call-interactively 'org-outdent-item-tree))
  15201. (t (org-modifier-cursor-error))))
  15202. (defun org-shiftmetaright ()
  15203. "Demote subtree or insert table column.
  15204. Calls `org-demote-subtree', `org-indent-item-tree', or
  15205. `org-table-insert-column', depending on context. See the
  15206. individual commands for more information."
  15207. (interactive)
  15208. (cond
  15209. ((and (eq system-type 'darwin)
  15210. (or (eq org-support-shift-select 'always)
  15211. (and org-support-shift-select (org-region-active-p))))
  15212. (org-call-for-shift-select 'forward-char))
  15213. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15214. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15215. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15216. ((if (not (org-region-active-p)) (org-at-item-p)
  15217. (save-excursion (goto-char (region-beginning))
  15218. (org-at-item-p)))
  15219. (call-interactively 'org-indent-item-tree))
  15220. (t (org-modifier-cursor-error))))
  15221. (defun org-shiftmetaup (&optional _arg)
  15222. "Drag the line at point up.
  15223. In a table, kill the current row.
  15224. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15225. but also adjust the previous clocked item in the clock history.
  15226. Everywhere else, drag the line at point up."
  15227. (interactive "P")
  15228. (cond
  15229. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15230. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15231. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15232. (call-interactively 'org-timestamp-up)))
  15233. (t (call-interactively 'org-drag-line-backward))))
  15234. (defun org-shiftmetadown (&optional _arg)
  15235. "Drag the line at point down.
  15236. In a table, insert an empty row at the current line.
  15237. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15238. but also adjust the previous clocked item in the clock history.
  15239. Everywhere else, drag the line at point down."
  15240. (interactive "P")
  15241. (cond
  15242. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15243. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15244. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15245. (call-interactively 'org-timestamp-down)))
  15246. (t (call-interactively 'org-drag-line-forward))))
  15247. (defsubst org-hidden-tree-error ()
  15248. (user-error
  15249. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15250. (defun org-metaleft (&optional _arg)
  15251. "Promote heading, list item at point or move table column left.
  15252. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15253. depending on context. With no specific context, calls the Emacs
  15254. default `backward-word'. See the individual commands for more
  15255. information.
  15256. This function runs the hook `org-metaleft-hook' as a first step,
  15257. and returns at first non-nil value."
  15258. (interactive "P")
  15259. (cond
  15260. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15261. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15262. ((org-with-limited-levels
  15263. (or (org-at-heading-p)
  15264. (and (org-region-active-p)
  15265. (save-excursion
  15266. (goto-char (region-beginning))
  15267. (org-at-heading-p)))))
  15268. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15269. (call-interactively 'org-do-promote))
  15270. ;; At an inline task.
  15271. ((org-at-heading-p)
  15272. (call-interactively 'org-inlinetask-promote))
  15273. ((or (org-at-item-p)
  15274. (and (org-region-active-p)
  15275. (save-excursion
  15276. (goto-char (region-beginning))
  15277. (org-at-item-p))))
  15278. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15279. (call-interactively 'org-outdent-item))
  15280. (t (call-interactively 'backward-word))))
  15281. (defun org-metaright (&optional _arg)
  15282. "Demote heading, list item at point or move table column right.
  15283. In front of a drawer or a block keyword, indent it correctly.
  15284. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15285. `org-indent-drawer' or `org-indent-block' depending on context.
  15286. With no specific context, calls the Emacs default `forward-word'.
  15287. See the individual commands for more information.
  15288. This function runs the hook `org-metaright-hook' as a first step,
  15289. and returns at first non-nil value."
  15290. (interactive "P")
  15291. (cond
  15292. ((run-hook-with-args-until-success 'org-metaright-hook))
  15293. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15294. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15295. ((org-at-block-p) (call-interactively 'org-indent-block))
  15296. ((org-with-limited-levels
  15297. (or (org-at-heading-p)
  15298. (and (org-region-active-p)
  15299. (save-excursion
  15300. (goto-char (region-beginning))
  15301. (org-at-heading-p)))))
  15302. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15303. (call-interactively 'org-do-demote))
  15304. ;; At an inline task.
  15305. ((org-at-heading-p)
  15306. (call-interactively 'org-inlinetask-demote))
  15307. ((or (org-at-item-p)
  15308. (and (org-region-active-p)
  15309. (save-excursion
  15310. (goto-char (region-beginning))
  15311. (org-at-item-p))))
  15312. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15313. (call-interactively 'org-indent-item))
  15314. (t (call-interactively 'forward-word))))
  15315. (defun org-check-for-hidden (what)
  15316. "Check if there are hidden headlines/items in the current visual line.
  15317. WHAT can be either `headlines' or `items'. If the current line is
  15318. an outline or item heading and it has a folded subtree below it,
  15319. this function returns t, nil otherwise."
  15320. (let ((re (cond
  15321. ((eq what 'headlines) org-outline-regexp-bol)
  15322. ((eq what 'items) (org-item-beginning-re))
  15323. (t (error "This should not happen"))))
  15324. beg end)
  15325. (save-excursion
  15326. (catch 'exit
  15327. (unless (org-region-active-p)
  15328. (setq beg (line-beginning-position))
  15329. (beginning-of-line 2)
  15330. (while (and (not (eobp)) ;; this is like `next-line'
  15331. (org-invisible-p (1- (point))))
  15332. (beginning-of-line 2))
  15333. (setq end (point))
  15334. (goto-char beg)
  15335. (goto-char (line-end-position))
  15336. (setq end (max end (point)))
  15337. (while (re-search-forward re end t)
  15338. (when (org-invisible-p (match-beginning 0))
  15339. (throw 'exit t))))
  15340. nil))))
  15341. (defun org-metaup (&optional _arg)
  15342. "Move subtree up or move table row up.
  15343. Calls `org-move-subtree-up' or `org-table-move-row' or
  15344. `org-move-item-up', depending on context. See the individual commands
  15345. for more information."
  15346. (interactive "P")
  15347. (cond
  15348. ((run-hook-with-args-until-success 'org-metaup-hook))
  15349. ((org-region-active-p)
  15350. (let* ((a (save-excursion
  15351. (goto-char (region-beginning))
  15352. (line-beginning-position)))
  15353. (b (save-excursion
  15354. (goto-char (region-end))
  15355. (if (bolp) (1- (point)) (line-end-position))))
  15356. (c (save-excursion
  15357. (goto-char a)
  15358. (move-beginning-of-line 0)
  15359. (point)))
  15360. (d (save-excursion
  15361. (goto-char a)
  15362. (move-end-of-line 0)
  15363. (point))))
  15364. (transpose-regions a b c d)
  15365. (goto-char c)))
  15366. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15367. ((and (featurep 'org-inlinetask)
  15368. (org-inlinetask-in-task-p))
  15369. (org-drag-element-backward))
  15370. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15371. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15372. (t (org-drag-element-backward))))
  15373. (defun org-metadown (&optional _arg)
  15374. "Move subtree down or move table row down.
  15375. Calls `org-move-subtree-down' or `org-table-move-row' or
  15376. `org-move-item-down', depending on context. See the individual
  15377. commands for more information."
  15378. (interactive "P")
  15379. (cond
  15380. ((run-hook-with-args-until-success 'org-metadown-hook))
  15381. ((org-region-active-p)
  15382. (let* ((a (save-excursion
  15383. (goto-char (region-beginning))
  15384. (line-beginning-position)))
  15385. (b (save-excursion
  15386. (goto-char (region-end))
  15387. (if (bolp) (1- (point)) (line-end-position))))
  15388. (c (save-excursion
  15389. (goto-char b)
  15390. (move-beginning-of-line (if (bolp) 1 2))
  15391. (point)))
  15392. (d (save-excursion
  15393. (goto-char b)
  15394. (move-end-of-line (if (bolp) 1 2))
  15395. (point))))
  15396. (transpose-regions a b c d)
  15397. (goto-char d)))
  15398. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15399. ((and (featurep 'org-inlinetask)
  15400. (org-inlinetask-in-task-p))
  15401. (org-drag-element-forward))
  15402. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15403. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15404. (t (org-drag-element-forward))))
  15405. (defun org-shiftup (&optional arg)
  15406. "Act on current element according to context.
  15407. Call `org-timestamp-up' or `org-priority-up', or
  15408. `org-previous-item', or `org-table-move-cell-up'. See the
  15409. individual commands for more information."
  15410. (interactive "P")
  15411. (cond
  15412. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15413. ((and org-support-shift-select (org-region-active-p))
  15414. (org-call-for-shift-select 'previous-line))
  15415. ((org-at-timestamp-p 'lax)
  15416. (call-interactively (if org-edit-timestamp-down-means-later
  15417. 'org-timestamp-down 'org-timestamp-up)))
  15418. ((and (not (eq org-support-shift-select 'always))
  15419. org-priority-enable-commands
  15420. (org-at-heading-p))
  15421. (call-interactively 'org-priority-up))
  15422. ((and (not org-support-shift-select) (org-at-item-p))
  15423. (call-interactively 'org-previous-item))
  15424. ((org-clocktable-try-shift 'up arg))
  15425. ((and (not (eq org-support-shift-select 'always))
  15426. (org-at-table-p))
  15427. (org-table-move-cell-up))
  15428. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15429. (org-support-shift-select
  15430. (org-call-for-shift-select 'previous-line))
  15431. (t (org-shiftselect-error))))
  15432. (defun org-shiftdown (&optional arg)
  15433. "Act on current element according to context.
  15434. Call `org-timestamp-down' or `org-priority-down', or
  15435. `org-next-item', or `org-table-move-cell-down'. See the
  15436. individual commands for more information."
  15437. (interactive "P")
  15438. (cond
  15439. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15440. ((and org-support-shift-select (org-region-active-p))
  15441. (org-call-for-shift-select 'next-line))
  15442. ((org-at-timestamp-p 'lax)
  15443. (call-interactively (if org-edit-timestamp-down-means-later
  15444. 'org-timestamp-up 'org-timestamp-down)))
  15445. ((and (not (eq org-support-shift-select 'always))
  15446. org-priority-enable-commands
  15447. (org-at-heading-p))
  15448. (call-interactively 'org-priority-down))
  15449. ((and (not org-support-shift-select) (org-at-item-p))
  15450. (call-interactively 'org-next-item))
  15451. ((org-clocktable-try-shift 'down arg))
  15452. ((and (not (eq org-support-shift-select 'always))
  15453. (org-at-table-p))
  15454. (org-table-move-cell-down))
  15455. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15456. (org-support-shift-select
  15457. (org-call-for-shift-select 'next-line))
  15458. (t (org-shiftselect-error))))
  15459. (defun org-shiftright (&optional arg)
  15460. "Act on the current element according to context.
  15461. This does one of the following:
  15462. - switch a timestamp at point one day into the future
  15463. - on a headline, switch to the next TODO keyword
  15464. - on an item, switch entire list to the next bullet type
  15465. - on a property line, switch to the next allowed value
  15466. - on a clocktable definition line, move time block into the future
  15467. - in a table, move a single cell right"
  15468. (interactive "P")
  15469. (cond
  15470. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15471. ((and org-support-shift-select (org-region-active-p))
  15472. (org-call-for-shift-select 'forward-char))
  15473. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15474. ((and (not (eq org-support-shift-select 'always))
  15475. (org-at-heading-p))
  15476. (let ((org-inhibit-logging
  15477. (not org-treat-S-cursor-todo-selection-as-state-change))
  15478. (org-inhibit-blocking
  15479. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15480. (org-call-with-arg 'org-todo 'right)))
  15481. ((or (and org-support-shift-select
  15482. (not (eq org-support-shift-select 'always))
  15483. (org-at-item-bullet-p))
  15484. (and (not org-support-shift-select) (org-at-item-p)))
  15485. (org-call-with-arg 'org-cycle-list-bullet nil))
  15486. ((and (not (eq org-support-shift-select 'always))
  15487. (org-at-property-p))
  15488. (call-interactively 'org-property-next-allowed-value))
  15489. ((org-clocktable-try-shift 'right arg))
  15490. ((and (not (eq org-support-shift-select 'always))
  15491. (org-at-table-p))
  15492. (org-table-move-cell-right))
  15493. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15494. (org-support-shift-select
  15495. (org-call-for-shift-select 'forward-char))
  15496. (t (org-shiftselect-error))))
  15497. (defun org-shiftleft (&optional arg)
  15498. "Act on current element according to context.
  15499. This does one of the following:
  15500. - switch a timestamp at point one day into the past
  15501. - on a headline, switch to the previous TODO keyword.
  15502. - on an item, switch entire list to the previous bullet type
  15503. - on a property line, switch to the previous allowed value
  15504. - on a clocktable definition line, move time block into the past
  15505. - in a table, move a single cell left"
  15506. (interactive "P")
  15507. (cond
  15508. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15509. ((and org-support-shift-select (org-region-active-p))
  15510. (org-call-for-shift-select 'backward-char))
  15511. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15512. ((and (not (eq org-support-shift-select 'always))
  15513. (org-at-heading-p))
  15514. (let ((org-inhibit-logging
  15515. (not org-treat-S-cursor-todo-selection-as-state-change))
  15516. (org-inhibit-blocking
  15517. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15518. (org-call-with-arg 'org-todo 'left)))
  15519. ((or (and org-support-shift-select
  15520. (not (eq org-support-shift-select 'always))
  15521. (org-at-item-bullet-p))
  15522. (and (not org-support-shift-select) (org-at-item-p)))
  15523. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15524. ((and (not (eq org-support-shift-select 'always))
  15525. (org-at-property-p))
  15526. (call-interactively 'org-property-previous-allowed-value))
  15527. ((org-clocktable-try-shift 'left arg))
  15528. ((and (not (eq org-support-shift-select 'always))
  15529. (org-at-table-p))
  15530. (org-table-move-cell-left))
  15531. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15532. (org-support-shift-select
  15533. (org-call-for-shift-select 'backward-char))
  15534. (t (org-shiftselect-error))))
  15535. (defun org-shiftcontrolright ()
  15536. "Switch to next TODO set."
  15537. (interactive)
  15538. (cond
  15539. ((and org-support-shift-select (org-region-active-p))
  15540. (org-call-for-shift-select 'forward-word))
  15541. ((and (not (eq org-support-shift-select 'always))
  15542. (org-at-heading-p))
  15543. (org-call-with-arg 'org-todo 'nextset))
  15544. (org-support-shift-select
  15545. (org-call-for-shift-select 'forward-word))
  15546. (t (org-shiftselect-error))))
  15547. (defun org-shiftcontrolleft ()
  15548. "Switch to previous TODO set."
  15549. (interactive)
  15550. (cond
  15551. ((and org-support-shift-select (org-region-active-p))
  15552. (org-call-for-shift-select 'backward-word))
  15553. ((and (not (eq org-support-shift-select 'always))
  15554. (org-at-heading-p))
  15555. (org-call-with-arg 'org-todo 'previousset))
  15556. (org-support-shift-select
  15557. (org-call-for-shift-select 'backward-word))
  15558. (t (org-shiftselect-error))))
  15559. (defun org-shiftcontrolup (&optional n)
  15560. "Change timestamps synchronously up in CLOCK log lines.
  15561. Optional argument N tells to change by that many units."
  15562. (interactive "P")
  15563. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15564. (let (org-support-shift-select)
  15565. (org-clock-timestamps-up n))
  15566. (user-error "Not at a clock log")))
  15567. (defun org-shiftcontroldown (&optional n)
  15568. "Change timestamps synchronously down in CLOCK log lines.
  15569. Optional argument N tells to change by that many units."
  15570. (interactive "P")
  15571. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15572. (let (org-support-shift-select)
  15573. (org-clock-timestamps-down n))
  15574. (user-error "Not at a clock log")))
  15575. (defun org-increase-number-at-point (&optional inc)
  15576. "Increment the number at point.
  15577. With an optional prefix numeric argument INC, increment using
  15578. this numeric value."
  15579. (interactive "p")
  15580. (if (not (number-at-point))
  15581. (user-error "Not on a number")
  15582. (unless inc (setq inc 1))
  15583. (let ((pos (point))
  15584. (beg (skip-chars-backward "-+^/*0-9eE."))
  15585. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15586. (setq nap (buffer-substring-no-properties
  15587. (+ pos beg) (+ pos beg end)))
  15588. (delete-region (+ pos beg) (+ pos beg end))
  15589. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15590. (when (org-at-table-p)
  15591. (org-table-align)
  15592. (org-table-end-of-field 1))))
  15593. (defun org-decrease-number-at-point (&optional inc)
  15594. "Decrement the number at point.
  15595. With an optional prefix numeric argument INC, decrement using
  15596. this numeric value."
  15597. (interactive "p")
  15598. (org-increase-number-at-point (- (or inc 1))))
  15599. (defun org-ctrl-c-ret ()
  15600. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15601. (interactive)
  15602. (cond
  15603. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15604. (t (call-interactively 'org-insert-heading))))
  15605. (defun org-copy-visible (beg end)
  15606. "Copy the visible parts of the region."
  15607. (interactive "r")
  15608. (let ((result ""))
  15609. (while (/= beg end)
  15610. (if (eq org-fold-core-style 'text-properties)
  15611. (progn
  15612. (while (org-invisible-p beg)
  15613. (setq beg (org-fold-next-visibility-change beg end)))
  15614. (let ((next (org-fold-next-visibility-change beg end)))
  15615. (setq result (concat result (buffer-substring beg next)))
  15616. (setq beg next)))
  15617. (when (invisible-p beg)
  15618. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15619. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15620. (setq result (concat result (buffer-substring beg next)))
  15621. (setq beg next))))
  15622. ;; Prevent Emacs from adding full selected text to `kill-ring'
  15623. ;; when `select-enable-primary' is non-nil. This special value of
  15624. ;; `deactivate-mark' only works since Emacs 29.
  15625. (setq deactivate-mark 'dont-save)
  15626. (kill-new result)
  15627. (message "Visible strings have been copied to the kill ring.")))
  15628. (defun org-copy-special ()
  15629. "Copy region in table or copy current subtree.
  15630. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15631. context. See the individual commands for more information."
  15632. (interactive)
  15633. (call-interactively
  15634. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15635. (defun org-cut-special ()
  15636. "Cut region in table or cut current subtree.
  15637. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15638. context. See the individual commands for more information."
  15639. (interactive)
  15640. (call-interactively
  15641. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15642. (defun org-paste-special (arg)
  15643. "Paste rectangular region into table, or past subtree relative to level.
  15644. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15645. See the individual commands for more information."
  15646. (interactive "P")
  15647. (if (org-at-table-p)
  15648. (org-table-paste-rectangle)
  15649. (org-paste-subtree arg)))
  15650. (defun org-edit-special (&optional arg)
  15651. "Call a special editor for the element at point.
  15652. When at a table, call the formula editor with `org-table-edit-formulas'.
  15653. When in a source code block, call `org-edit-src-code'.
  15654. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15655. When in an export block, call `org-edit-export-block'.
  15656. When in a comment block, call `org-edit-comment-block'.
  15657. When in a LaTeX environment, call `org-edit-latex-environment'.
  15658. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15659. When at a footnote reference, call `org-edit-footnote-reference'.
  15660. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15661. When at an active timestamp, call `org-time-stamp'.
  15662. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15663. On a link, call `ffap' to visit the link at point.
  15664. Otherwise, return a user error."
  15665. (interactive "P")
  15666. (let ((element (org-element-at-point)))
  15667. (barf-if-buffer-read-only)
  15668. (pcase (org-element-type element)
  15669. (`src-block
  15670. (if (not arg) (org-edit-src-code)
  15671. (let* ((info (org-babel-get-src-block-info))
  15672. (lang (nth 0 info))
  15673. (params (nth 2 info))
  15674. (session (cdr (assq :session params))))
  15675. (if (not session) (org-edit-src-code)
  15676. ;; At a source block with a session and function called
  15677. ;; with an ARG: switch to the buffer related to the
  15678. ;; inferior process.
  15679. (switch-to-buffer
  15680. (funcall (intern (concat "org-babel-prep-session:" lang))
  15681. session params))))))
  15682. (`keyword
  15683. (unless (member (org-element-property :key element)
  15684. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15685. (user-error "No special environment to edit here"))
  15686. (let ((value (org-element-property :value element)))
  15687. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15688. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15689. (or (match-string 1 value)
  15690. (match-string 0 value)))))
  15691. (when (org-url-p file)
  15692. (user-error "Files located with a URL cannot be edited"))
  15693. (org-link-open-from-string
  15694. (format "[[%s]]" (expand-file-name file))))))
  15695. (`table
  15696. (if (eq (org-element-property :type element) 'table.el)
  15697. (org-edit-table.el)
  15698. (call-interactively 'org-table-edit-formulas)))
  15699. ;; Only Org tables contain `table-row' type elements.
  15700. (`table-row (call-interactively 'org-table-edit-formulas))
  15701. (`example-block (org-edit-src-code))
  15702. (`export-block (org-edit-export-block))
  15703. (`comment-block (org-edit-comment-block))
  15704. (`fixed-width (org-edit-fixed-width-region))
  15705. (`latex-environment (org-edit-latex-environment))
  15706. (`planning
  15707. (let ((proplist (cadr element)))
  15708. (mapc #'call-interactively
  15709. (remq nil
  15710. (list
  15711. (when (plist-get proplist :deadline) #'org-deadline)
  15712. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15713. (_
  15714. ;; No notable element at point. Though, we may be at a link or
  15715. ;; a footnote reference, which are objects. Thus, scan deeper.
  15716. (let ((context (org-element-context element)))
  15717. (pcase (org-element-type context)
  15718. (`footnote-reference (org-edit-footnote-reference))
  15719. (`inline-src-block (org-edit-inline-src-code))
  15720. (`latex-fragment (org-edit-latex-fragment))
  15721. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15722. (call-interactively #'org-time-stamp-inactive)
  15723. (call-interactively #'org-time-stamp)))
  15724. (`link (call-interactively #'ffap))
  15725. (_ (user-error "No special environment to edit here"))))))))
  15726. (defun org-ctrl-c-ctrl-c (&optional arg)
  15727. "Set tags in headline, or update according to changed information at point.
  15728. This command does many different things, depending on context:
  15729. - If column view is active, in agenda or org buffers, quit it.
  15730. - If there are highlights, remove them.
  15731. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15732. this is what we do.
  15733. - If the cursor is on a statistics cookie, update it.
  15734. - If the cursor is in a headline, in an agenda or an org buffer,
  15735. prompt for tags and insert them into the current line, aligned
  15736. to `org-tags-column'. When called with prefix arg, realign all
  15737. tags in the current buffer.
  15738. - If the cursor is in one of the special #+KEYWORD lines, this
  15739. triggers scanning the buffer for these lines and updating the
  15740. information.
  15741. - If the cursor is inside a table, realign the table. This command
  15742. works even if the automatic table editor has been turned off.
  15743. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15744. the entire table.
  15745. - If the cursor is at a footnote reference or definition, jump to
  15746. the corresponding definition or references, respectively.
  15747. - If the cursor is a the beginning of a dynamic block, update it.
  15748. - If the current buffer is a capture buffer, close note and file it.
  15749. - If the cursor is on a <<<target>>>, update radio targets and
  15750. corresponding links in this buffer.
  15751. - If the cursor is on a numbered item in a plain list, renumber the
  15752. ordered list.
  15753. - If the cursor is on a checkbox, toggle it.
  15754. - If the cursor is on a code block, evaluate it. The variable
  15755. `org-confirm-babel-evaluate' can be used to control prompting
  15756. before code block evaluation, by default every code block
  15757. evaluation requires confirmation. Code block evaluation can be
  15758. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15759. (interactive "P")
  15760. (cond
  15761. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15762. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15763. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15764. (org-remove-occur-highlights)
  15765. (message "Temporary highlights/overlays removed from current buffer"))
  15766. ((and (local-variable-p 'org-finish-function)
  15767. (fboundp org-finish-function))
  15768. (funcall org-finish-function))
  15769. ((org-babel-hash-at-point))
  15770. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15771. (t
  15772. (let* ((context
  15773. (org-element-lineage
  15774. (org-element-context)
  15775. ;; Limit to supported contexts.
  15776. '(babel-call clock dynamic-block footnote-definition
  15777. footnote-reference inline-babel-call inline-src-block
  15778. inlinetask item keyword node-property paragraph
  15779. plain-list planning property-drawer radio-target
  15780. src-block statistics-cookie table table-cell table-row
  15781. timestamp)
  15782. t))
  15783. (radio-list-p (org-at-radio-list-p))
  15784. (type (org-element-type context)))
  15785. ;; For convenience: at the first line of a paragraph on the same
  15786. ;; line as an item, apply function on that item instead.
  15787. (when (eq type 'paragraph)
  15788. (let ((parent (org-element-property :parent context)))
  15789. (when (and (eq (org-element-type parent) 'item)
  15790. (= (line-beginning-position)
  15791. (org-element-property :begin parent)))
  15792. (setq context parent)
  15793. (setq type 'item))))
  15794. ;; Act according to type of element or object at point.
  15795. ;;
  15796. ;; Do nothing on a blank line, except if it is contained in
  15797. ;; a source block. Hence, we first check if point is in such
  15798. ;; a block and then if it is at a blank line.
  15799. (pcase type
  15800. ((or `inline-src-block `src-block)
  15801. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15802. (org-babel-eval-wipe-error-buffer)
  15803. (org-babel-execute-src-block
  15804. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15805. ((guard (org-match-line "[ \t]*$"))
  15806. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15807. (user-error
  15808. (substitute-command-keys
  15809. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15810. ((or `babel-call `inline-babel-call)
  15811. (let ((info (org-babel-lob-get-info context)))
  15812. (when info (org-babel-execute-src-block nil info nil type))))
  15813. (`clock (org-clock-update-time-maybe))
  15814. (`dynamic-block
  15815. (save-excursion
  15816. (goto-char (org-element-property :post-affiliated context))
  15817. (org-update-dblock)))
  15818. (`footnote-definition
  15819. (goto-char (org-element-property :post-affiliated context))
  15820. (call-interactively 'org-footnote-action))
  15821. (`footnote-reference (call-interactively #'org-footnote-action))
  15822. ((or `headline `inlinetask)
  15823. (save-excursion (goto-char (org-element-property :begin context))
  15824. (call-interactively #'org-set-tags-command)))
  15825. (`item
  15826. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15827. ;; unconditionally, whereas `C-u' will toggle its presence.
  15828. ;; Without a universal argument, if the item has a checkbox,
  15829. ;; toggle it. Otherwise repair the list.
  15830. (if (or radio-list-p
  15831. (and (boundp org-list-checkbox-radio-mode)
  15832. org-list-checkbox-radio-mode))
  15833. (org-toggle-radio-button arg)
  15834. (let* ((box (org-element-property :checkbox context))
  15835. (struct (org-element-property :structure context))
  15836. (old-struct (copy-tree struct))
  15837. (parents (org-list-parents-alist struct))
  15838. (prevs (org-list-prevs-alist struct))
  15839. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15840. (org-list-set-checkbox
  15841. (org-element-property :begin context) struct
  15842. (cond ((equal arg '(16)) "[-]")
  15843. ((and (not box) (equal arg '(4))) "[ ]")
  15844. ((or (not box) (equal arg '(4))) nil)
  15845. ((eq box 'on) "[ ]")
  15846. (t "[X]")))
  15847. ;; Mimic `org-list-write-struct' but with grabbing a return
  15848. ;; value from `org-list-struct-fix-box'.
  15849. (org-list-struct-fix-ind struct parents 2)
  15850. (org-list-struct-fix-item-end struct)
  15851. (org-list-struct-fix-bul struct prevs)
  15852. (org-list-struct-fix-ind struct parents)
  15853. (let ((block-item
  15854. (org-list-struct-fix-box struct parents prevs orderedp)))
  15855. (if (and box (equal struct old-struct))
  15856. (if (equal arg '(16))
  15857. (message "Checkboxes already reset")
  15858. (user-error "Cannot toggle this checkbox: %s"
  15859. (if (eq box 'on)
  15860. "all subitems checked"
  15861. "unchecked subitems")))
  15862. (org-list-struct-apply-struct struct old-struct)
  15863. (org-update-checkbox-count-maybe))
  15864. (when block-item
  15865. (message "Checkboxes were removed due to empty box at line %d"
  15866. (org-current-line block-item)))))))
  15867. (`plain-list
  15868. ;; At a plain list, with a double C-u argument, set
  15869. ;; checkboxes of each item to "[-]", whereas a single one
  15870. ;; will toggle their presence according to the state of the
  15871. ;; first item in the list. Without an argument, repair the
  15872. ;; list.
  15873. (if (or radio-list-p
  15874. (and (boundp org-list-checkbox-radio-mode)
  15875. org-list-checkbox-radio-mode))
  15876. (org-toggle-radio-button arg)
  15877. (let* ((begin (org-element-property :contents-begin context))
  15878. (struct (org-element-property :structure context))
  15879. (old-struct (copy-tree struct))
  15880. (first-box (save-excursion
  15881. (goto-char begin)
  15882. (looking-at org-list-full-item-re)
  15883. (match-string-no-properties 3)))
  15884. (new-box (cond ((equal arg '(16)) "[-]")
  15885. ((equal arg '(4)) (unless first-box "[ ]"))
  15886. ((equal first-box "[X]") "[ ]")
  15887. (t "[X]"))))
  15888. (cond
  15889. (arg
  15890. (dolist (pos
  15891. (org-list-get-all-items
  15892. begin struct (org-list-prevs-alist struct)))
  15893. (org-list-set-checkbox pos struct new-box)))
  15894. ((and first-box (eq (point) begin))
  15895. ;; For convenience, when point is at bol on the first
  15896. ;; item of the list and no argument is provided, simply
  15897. ;; toggle checkbox of that item, if any.
  15898. (org-list-set-checkbox begin struct new-box)))
  15899. (when (equal
  15900. (org-list-write-struct
  15901. struct (org-list-parents-alist struct) old-struct)
  15902. old-struct)
  15903. (message "Cannot update this checkbox"))
  15904. (org-update-checkbox-count-maybe))))
  15905. (`keyword
  15906. (let ((org-inhibit-startup-visibility-stuff t)
  15907. (org-startup-align-all-tables nil))
  15908. (when (boundp 'org-table-coordinate-overlays)
  15909. (mapc #'delete-overlay org-table-coordinate-overlays)
  15910. (setq org-table-coordinate-overlays nil))
  15911. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15912. (message "Local setup has been refreshed"))
  15913. ((or `property-drawer `node-property)
  15914. (call-interactively #'org-property-action))
  15915. (`radio-target
  15916. (call-interactively #'org-update-radio-target-regexp))
  15917. (`statistics-cookie
  15918. (call-interactively #'org-update-statistics-cookies))
  15919. ((or `table `table-cell `table-row)
  15920. ;; At a table, generate a plot if on the #+plot line,
  15921. ;; recalculate every field and align it otherwise. Also
  15922. ;; send the table if necessary.
  15923. (cond
  15924. ((and (org-match-line "[ \t]*#\\+plot:")
  15925. (< (point) (org-element-property :post-affiliated context)))
  15926. (org-plot/gnuplot))
  15927. ;; If the table has a `table.el' type, just give up.
  15928. ((eq (org-element-property :type context) 'table.el)
  15929. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15930. Use `\\[org-edit-special]' to edit table.el tables")))
  15931. ;; At a table row or cell, maybe recalculate line but always
  15932. ;; align table.
  15933. ((or (eq type 'table)
  15934. ;; Check if point is at a TBLFM line.
  15935. (and (eq type 'table-row)
  15936. (= (point) (org-element-property :end context))))
  15937. (save-excursion
  15938. (if (org-at-TBLFM-p)
  15939. (progn (require 'org-table)
  15940. (org-table-calc-current-TBLFM))
  15941. (goto-char (org-element-property :contents-begin context))
  15942. (org-call-with-arg 'org-table-recalculate (or arg t))
  15943. (orgtbl-send-table 'maybe))))
  15944. (t
  15945. (org-table-maybe-eval-formula)
  15946. (cond (arg (call-interactively #'org-table-recalculate))
  15947. ((org-table-maybe-recalculate-line))
  15948. (t (org-table-align))))))
  15949. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15950. (org-timestamp-change 0 'day))
  15951. ((and `nil (guard (org-at-heading-p)))
  15952. ;; When point is on an unsupported object type, we can miss
  15953. ;; the fact that it also is at a heading. Handle it here.
  15954. (call-interactively #'org-set-tags-command))
  15955. ((guard
  15956. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15957. (_
  15958. (user-error
  15959. (substitute-command-keys
  15960. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15961. (defun org-mode-restart ()
  15962. "Restart `org-mode'."
  15963. (interactive)
  15964. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15965. (funcall major-mode)
  15966. (hack-local-variables)
  15967. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15968. (org-indent-mode -1))
  15969. (org-reset-file-cache))
  15970. (message "%s restarted" major-mode))
  15971. (defun org-kill-note-or-show-branches ()
  15972. "Abort storing current note, or show just branches."
  15973. (interactive)
  15974. (cond (org-finish-function
  15975. (let ((org-note-abort t)) (funcall org-finish-function)))
  15976. ((org-before-first-heading-p)
  15977. (org-fold-show-branches-buffer)
  15978. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15979. (t
  15980. (let ((beg (progn (org-back-to-heading) (point)))
  15981. (end (save-excursion (org-end-of-subtree t t) (point))))
  15982. (org-fold-hide-subtree)
  15983. (org-fold-show-branches)
  15984. (org-fold-hide-archived-subtrees beg end)))))
  15985. (defun org-delete-indentation (&optional arg)
  15986. "Join current line to previous and fix whitespace at join.
  15987. If previous line is a headline add to headline title. Otherwise
  15988. the function calls `delete-indentation'.
  15989. I.e. with a non-nil optional argument, join the line with the
  15990. following one. If there is a region then join the lines in that
  15991. region."
  15992. (interactive "*P")
  15993. (if (save-excursion
  15994. (beginning-of-line (if arg 1 0))
  15995. (let ((case-fold-search nil))
  15996. (looking-at org-complex-heading-regexp)))
  15997. ;; At headline.
  15998. (let ((tags-column (when (match-beginning 5)
  15999. (save-excursion (goto-char (match-beginning 5))
  16000. (current-column))))
  16001. (string (concat " " (progn (when arg (forward-line 1))
  16002. (org-trim (delete-and-extract-region
  16003. (line-beginning-position)
  16004. (line-end-position)))))))
  16005. (unless (bobp) (delete-region (point) (1- (point))))
  16006. (goto-char (or (match-end 4)
  16007. (match-beginning 5)
  16008. (match-end 0)))
  16009. (skip-chars-backward " \t")
  16010. (save-excursion (insert string))
  16011. ;; Adjust alignment of tags.
  16012. (cond
  16013. ((not tags-column)) ;no tags
  16014. (org-auto-align-tags (org-align-tags))
  16015. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16016. (let ((current-prefix-arg arg))
  16017. (call-interactively #'delete-indentation))))
  16018. (defun org-open-line (n)
  16019. "Insert a new row in tables, call `open-line' elsewhere.
  16020. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16021. As a special case, when a document starts with a table, allow to
  16022. call `open-line' on the very first character."
  16023. (interactive "*p")
  16024. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16025. (org-table-insert-row)
  16026. (open-line n)))
  16027. (defun org--newline (indent arg interactive)
  16028. "Call `newline-and-indent' or just `newline'.
  16029. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16030. indent unconditionally; otherwise, call `newline' with ARG and
  16031. INTERACTIVE, which can trigger indentation if
  16032. `electric-indent-mode' is enabled."
  16033. (if indent
  16034. (org-newline-and-indent arg)
  16035. (newline arg interactive)))
  16036. (defun org-return (&optional indent arg interactive)
  16037. "Goto next table row or insert a newline.
  16038. Calls `org-table-next-row' or `newline', depending on context.
  16039. When optional INDENT argument is non-nil, call
  16040. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16041. and INTERACTIVE.
  16042. When `org-return-follows-link' is non-nil and point is on
  16043. a timestamp or a link, call `org-open-at-point'. However, it
  16044. will not happen if point is in a table or on a \"dead\"
  16045. object (e.g., within a comment). In these case, you need to use
  16046. `org-open-at-point' directly."
  16047. (interactive "i\nP\np")
  16048. (let* ((context (if org-return-follows-link (org-element-context)
  16049. (org-element-at-point)))
  16050. (element-type (org-element-type context)))
  16051. (cond
  16052. ;; In a table, call `org-table-next-row'. However, before first
  16053. ;; column or after last one, split the table.
  16054. ((or (and (eq 'table element-type)
  16055. (not (eq 'table.el (org-element-property :type context)))
  16056. (>= (point) (org-element-property :contents-begin context))
  16057. (< (point) (org-element-property :contents-end context)))
  16058. (org-element-lineage context '(table-row table-cell) t))
  16059. (if (or (looking-at-p "[ \t]*$")
  16060. (save-excursion (skip-chars-backward " \t") (bolp)))
  16061. (insert "\n")
  16062. (org-table-justify-field-maybe)
  16063. (call-interactively #'org-table-next-row)))
  16064. ;; On a link or a timestamp, call `org-open-at-point' if
  16065. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16066. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16067. ((and org-return-follows-link
  16068. (or (and (eq 'link element-type)
  16069. ;; Ensure point is not on the white spaces after
  16070. ;; the link.
  16071. (let ((origin (point)))
  16072. (org-with-point-at (org-element-property :end context)
  16073. (skip-chars-backward " \t")
  16074. (> (point) origin))))
  16075. (org-in-regexp org-ts-regexp-both nil t)
  16076. (org-in-regexp org-tsr-regexp-both nil t)
  16077. (org-in-regexp org-link-any-re nil t)))
  16078. (call-interactively #'org-open-at-point))
  16079. ;; Insert newline in heading, but preserve tags.
  16080. ((and (not (bolp))
  16081. (let ((case-fold-search nil))
  16082. (org-match-line org-complex-heading-regexp)))
  16083. ;; At headline. Split line. However, if point is on keyword,
  16084. ;; priority cookie or tags, do not break any of them: add
  16085. ;; a newline after the headline instead.
  16086. (let ((tags-column (and (match-beginning 5)
  16087. (save-excursion (goto-char (match-beginning 5))
  16088. (current-column))))
  16089. (string
  16090. (when (and (match-end 4) (org-point-in-group (point) 4))
  16091. (delete-and-extract-region (point) (match-end 4)))))
  16092. ;; Adjust tag alignment.
  16093. (cond
  16094. ((not (and tags-column string)))
  16095. (org-auto-align-tags (org-align-tags))
  16096. (t (org--align-tags-here tags-column))) ;preserve tags column
  16097. (end-of-line)
  16098. (org-fold-show-entry 'hide-drawers)
  16099. (org--newline indent arg interactive)
  16100. (when string (save-excursion (insert (org-trim string))))))
  16101. ;; In a list, make sure indenting keeps trailing text within.
  16102. ((and (not (eolp))
  16103. (org-element-lineage context '(item)))
  16104. (let ((trailing-data
  16105. (delete-and-extract-region (point) (line-end-position))))
  16106. (org--newline indent arg interactive)
  16107. (save-excursion (insert trailing-data))))
  16108. (t
  16109. ;; Do not auto-fill when point is in an Org property drawer.
  16110. (let ((auto-fill-function (and (not (org-at-property-p))
  16111. auto-fill-function)))
  16112. (org--newline indent arg interactive))))))
  16113. (defun org-return-and-maybe-indent ()
  16114. "Goto next table row, or insert a newline, maybe indented.
  16115. Call `org-table-next-row' or `org-return', depending on context.
  16116. See the individual commands for more information.
  16117. When inserting a newline, if `org-adapt-indentation' is t:
  16118. indent the line if `electric-indent-mode' is disabled, don't
  16119. indent it if it is enabled."
  16120. (interactive)
  16121. (org-return (not electric-indent-mode)))
  16122. (defun org-ctrl-c-tab (&optional arg)
  16123. "Toggle columns width in a table, or show children.
  16124. Call `org-table-toggle-column-width' if point is in a table.
  16125. Otherwise provide a compact view of the children. ARG is the
  16126. level to hide."
  16127. (interactive "p")
  16128. (cond
  16129. ((org-at-table-p)
  16130. (call-interactively #'org-table-toggle-column-width))
  16131. ((org-before-first-heading-p)
  16132. (save-excursion
  16133. (org-fold-flag-above-first-heading)
  16134. (org-fold-hide-sublevels (or arg 1))))
  16135. (t
  16136. (org-fold-hide-subtree)
  16137. (org-fold-show-children arg))))
  16138. (defun org-ctrl-c-star ()
  16139. "Compute table, or change heading status of lines.
  16140. Calls `org-table-recalculate' or `org-toggle-heading',
  16141. depending on context."
  16142. (interactive)
  16143. (cond
  16144. ((org-at-table-p)
  16145. (call-interactively 'org-table-recalculate))
  16146. (t
  16147. ;; Convert all lines in region to list items
  16148. (call-interactively 'org-toggle-heading))))
  16149. (defun org-ctrl-c-minus ()
  16150. "Insert separator line in table or modify bullet status of line.
  16151. Also turns a plain line or a region of lines into list items.
  16152. Calls `org-table-insert-hline', `org-toggle-item', or
  16153. `org-cycle-list-bullet', depending on context."
  16154. (interactive)
  16155. (cond
  16156. ((org-at-table-p)
  16157. (call-interactively 'org-table-insert-hline))
  16158. ((org-region-active-p)
  16159. (call-interactively 'org-toggle-item))
  16160. ((org-in-item-p)
  16161. (call-interactively 'org-cycle-list-bullet))
  16162. (t
  16163. (call-interactively 'org-toggle-item))))
  16164. (defun org-toggle-heading (&optional nstars)
  16165. "Convert headings to normal text, or items or text to headings.
  16166. If there is no active region, only convert the current line.
  16167. With a `\\[universal-argument]' prefix, convert the whole list at
  16168. point into heading.
  16169. In a region:
  16170. - If the first non blank line is a headline, remove the stars
  16171. from all headlines in the region.
  16172. - If it is a normal line, turn each and every normal line (i.e.,
  16173. not an heading or an item) in the region into headings. If you
  16174. want to convert only the first line of this region, use one
  16175. universal prefix argument.
  16176. - If it is a plain list item, turn all plain list items into headings.
  16177. When converting a line into a heading, the number of stars is chosen
  16178. such that the lines become children of the current entry. However,
  16179. when a numeric prefix argument is given, its value determines the
  16180. number of stars to add."
  16181. (interactive "P")
  16182. (let ((skip-blanks
  16183. ;; Return beginning of first non-blank line, starting from
  16184. ;; line at POS.
  16185. (lambda (pos)
  16186. (save-excursion
  16187. (goto-char pos)
  16188. (while (org-at-comment-p) (forward-line))
  16189. (skip-chars-forward " \r\t\n")
  16190. (line-beginning-position))))
  16191. beg end toggled)
  16192. ;; Determine boundaries of changes. If a universal prefix has
  16193. ;; been given, put the list in a region. If region ends at a bol,
  16194. ;; do not consider the last line to be in the region.
  16195. (when (and current-prefix-arg (org-at-item-p))
  16196. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16197. (org-mark-element))
  16198. (if (org-region-active-p)
  16199. (setq beg (funcall skip-blanks (region-beginning))
  16200. end (copy-marker (save-excursion
  16201. (goto-char (region-end))
  16202. (if (bolp) (point) (line-end-position)))))
  16203. (setq beg (funcall skip-blanks (line-beginning-position))
  16204. end (copy-marker (line-end-position))))
  16205. ;; Ensure inline tasks don't count as headings.
  16206. (org-with-limited-levels
  16207. (save-excursion
  16208. (goto-char beg)
  16209. (cond
  16210. ;; Case 1. Started at an heading: de-star headings.
  16211. ((org-at-heading-p)
  16212. (while (< (point) end)
  16213. (when (org-at-heading-p)
  16214. (looking-at org-outline-regexp) (replace-match "")
  16215. (setq toggled t))
  16216. (forward-line)))
  16217. ;; Case 2. Started at an item: change items into headlines.
  16218. ;; One star will be added by `org-list-to-subtree'.
  16219. ((org-at-item-p)
  16220. (while (< (point) end)
  16221. (when (org-at-item-p)
  16222. ;; Pay attention to cases when region ends before list.
  16223. (let* ((struct (org-list-struct))
  16224. (list-end
  16225. (min (org-list-get-bottom-point struct) (1+ end))))
  16226. (save-restriction
  16227. (narrow-to-region (point) list-end)
  16228. (insert (org-list-to-subtree
  16229. (org-list-to-lisp t)
  16230. (pcase (org-current-level)
  16231. (`nil 1)
  16232. (l (1+ (org-reduced-level l)))))
  16233. "\n")))
  16234. (setq toggled t))
  16235. (forward-line)))
  16236. ;; Case 3. Started at normal text: make every line an heading,
  16237. ;; skipping headlines and items.
  16238. (t (let* ((stars
  16239. (make-string
  16240. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16241. (add-stars
  16242. (cond (nstars "") ; stars from prefix only
  16243. ((equal stars "") "*") ; before first heading
  16244. (org-odd-levels-only "**") ; inside heading, odd
  16245. (t "*"))) ; inside heading, oddeven
  16246. (rpl (concat stars add-stars " "))
  16247. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16248. (while (< (point) (if (equal nstars '(4)) lend end))
  16249. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16250. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16251. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16252. (forward-line)))))))
  16253. (unless toggled (message "Cannot toggle heading from here"))))
  16254. (defun org-meta-return (&optional arg)
  16255. "Insert a new heading or wrap a region in a table.
  16256. Calls `org-insert-heading', `org-insert-item' or
  16257. `org-table-wrap-region', depending on context. When called with
  16258. an argument, unconditionally call `org-insert-heading'."
  16259. (interactive "P")
  16260. (org-fold-check-before-invisible-edit 'insert)
  16261. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16262. (call-interactively (cond (arg #'org-insert-heading)
  16263. ((org-at-table-p) #'org-table-wrap-region)
  16264. ((org-in-item-p) #'org-insert-item)
  16265. (t #'org-insert-heading)))))
  16266. ;;; Menu entries
  16267. (defsubst org-in-subtree-not-table-p ()
  16268. "Are we in a subtree and not in a table?"
  16269. (and (not (org-before-first-heading-p))
  16270. (not (org-at-table-p))))
  16271. ;; Define the Org mode menus
  16272. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16273. `("Org"
  16274. ("Show/Hide"
  16275. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16276. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16277. ["Sparse Tree..." org-sparse-tree t]
  16278. ["Reveal Context" org-fold-reveal t]
  16279. ["Show All" org-fold-show-all t]
  16280. "--"
  16281. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16282. "--"
  16283. ["New Heading" org-insert-heading t]
  16284. ("Navigate Headings"
  16285. ["Up" outline-up-heading t]
  16286. ["Next" outline-next-visible-heading t]
  16287. ["Previous" outline-previous-visible-heading t]
  16288. ["Next Same Level" outline-forward-same-level t]
  16289. ["Previous Same Level" outline-backward-same-level t]
  16290. "--"
  16291. ["Jump" org-goto t])
  16292. ("Edit Structure"
  16293. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16294. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16295. "--"
  16296. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16297. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16298. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16299. "--"
  16300. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16301. "--"
  16302. ["Copy visible text" org-copy-visible t]
  16303. "--"
  16304. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16305. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16306. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16307. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16308. "--"
  16309. ["Sort Region/Children" org-sort t]
  16310. "--"
  16311. ["Convert to odd levels" org-convert-to-odd-levels t]
  16312. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16313. ("Editing"
  16314. ["Emphasis..." org-emphasize t]
  16315. ["Add block structure" org-insert-structure-template t]
  16316. ["Edit Source Example" org-edit-special t]
  16317. "--"
  16318. ["Footnote new/jump" org-footnote-action t]
  16319. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16320. ("Archive"
  16321. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16322. "--"
  16323. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16324. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16325. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16326. "--"
  16327. ("Hyperlinks"
  16328. ["Store Link (Global)" org-store-link t]
  16329. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16330. ["Insert Link" org-insert-link t]
  16331. ["Follow Link" org-open-at-point t]
  16332. "--"
  16333. ["Next link" org-next-link t]
  16334. ["Previous link" org-previous-link t]
  16335. "--"
  16336. ["Descriptive Links"
  16337. org-toggle-link-display
  16338. :style radio
  16339. :selected org-descriptive-links
  16340. ]
  16341. ["Literal Links"
  16342. org-toggle-link-display
  16343. :style radio
  16344. :selected (not org-descriptive-links)])
  16345. "--"
  16346. ("TODO Lists"
  16347. ["TODO/DONE/-" org-todo t]
  16348. ("Select keyword"
  16349. ["Next keyword" org-shiftright (org-at-heading-p)]
  16350. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16351. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16352. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16353. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16354. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16355. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16356. "--"
  16357. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16358. :selected org-enforce-todo-dependencies :style toggle :active t]
  16359. "Settings for tree at point"
  16360. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16361. :selected (org-entry-get nil "ORDERED")
  16362. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16363. ["Do Children parallel" org-toggle-ordered-property :style radio
  16364. :selected (not (org-entry-get nil "ORDERED"))
  16365. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16366. "--"
  16367. ["Set Priority" org-priority t]
  16368. ["Priority Up" org-shiftup t]
  16369. ["Priority Down" org-shiftdown t]
  16370. "--"
  16371. ["Get news from all feeds" org-feed-update-all t]
  16372. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16373. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16374. ("TAGS and Properties"
  16375. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16376. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16377. "--"
  16378. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16379. ["Column view of properties" org-columns t]
  16380. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16381. ("Dates and Scheduling"
  16382. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16383. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16384. ("Change Date"
  16385. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16386. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16387. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16388. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16389. ["Compute Time Range" org-evaluate-time-range t]
  16390. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16391. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16392. "--"
  16393. ["Custom time format" org-toggle-time-stamp-overlays
  16394. :style radio :selected org-display-custom-times]
  16395. "--"
  16396. ["Goto Calendar" org-goto-calendar t]
  16397. ["Date from Calendar" org-date-from-calendar t]
  16398. "--"
  16399. ["Start/Restart Timer" org-timer-start t]
  16400. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16401. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16402. ["Insert Timer String" org-timer t]
  16403. ["Insert Timer Item" org-timer-item t])
  16404. ("Logging work"
  16405. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16406. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16407. ["Clock out" org-clock-out t]
  16408. ["Clock cancel" org-clock-cancel t]
  16409. "--"
  16410. ["Mark as default task" org-clock-mark-default-task t]
  16411. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16412. ["Goto running clock" org-clock-goto t]
  16413. "--"
  16414. ["Display times" org-clock-display t]
  16415. ["Create clock table" org-clock-report t]
  16416. "--"
  16417. ["Record DONE time"
  16418. (progn (setq org-log-done (not org-log-done))
  16419. (message "Switching to %s will %s record a timestamp"
  16420. (car org-done-keywords)
  16421. (if org-log-done "automatically" "not")))
  16422. :style toggle :selected org-log-done])
  16423. "--"
  16424. ["Agenda Command..." org-agenda t]
  16425. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16426. ("File List for Agenda")
  16427. ("Special views current file"
  16428. ["TODO Tree" org-show-todo-tree t]
  16429. ["Check Deadlines" org-check-deadlines t]
  16430. ["Tags/Property tree" org-match-sparse-tree t])
  16431. "--"
  16432. ["Export/Publish..." org-export-dispatch t]
  16433. ("LaTeX"
  16434. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16435. :style toggle :selected org-cdlatex-mode]
  16436. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16437. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16438. ["Modify math symbol" org-cdlatex-math-modify
  16439. (org-inside-LaTeX-fragment-p)]
  16440. ["Insert citation" org-reftex-citation t])
  16441. "--"
  16442. ("Documentation"
  16443. ["Show Version" org-version t]
  16444. ["Info Documentation" org-info t]
  16445. ["Browse Org News" org-browse-news t])
  16446. ("Customize"
  16447. ["Browse Org Group" org-customize t]
  16448. "--"
  16449. ["Expand This Menu" org-create-customize-menu t])
  16450. ["Send bug report" org-submit-bug-report t]
  16451. "--"
  16452. ("Refresh/Reload"
  16453. ["Refresh setup current buffer" org-mode-restart t]
  16454. ["Reload Org (after update)" org-reload t]
  16455. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16456. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16457. '("Table"
  16458. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16459. ["Next Field" org-cycle (org-at-table-p)]
  16460. ["Previous Field" org-shifttab (org-at-table-p)]
  16461. ["Next Row" org-return (org-at-table-p)]
  16462. "--"
  16463. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16464. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16465. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16466. "--"
  16467. ("Column"
  16468. ["Move Column Left" org-metaleft (org-at-table-p)]
  16469. ["Move Column Right" org-metaright (org-at-table-p)]
  16470. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16471. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16472. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16473. ("Row"
  16474. ["Move Row Up" org-metaup (org-at-table-p)]
  16475. ["Move Row Down" org-metadown (org-at-table-p)]
  16476. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16477. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16478. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16479. "--"
  16480. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16481. ("Rectangle"
  16482. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16483. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16484. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16485. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16486. "--"
  16487. ("Calculate"
  16488. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16489. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16490. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16491. "--"
  16492. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16493. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16494. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16495. "--"
  16496. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16497. "--"
  16498. ["Sum Column/Rectangle" org-table-sum
  16499. (or (org-at-table-p) (org-region-active-p))]
  16500. ["Which Column?" org-table-current-column (org-at-table-p)])
  16501. ["Debug Formulas"
  16502. org-table-toggle-formula-debugger
  16503. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16504. ["Show Col/Row Numbers"
  16505. org-table-toggle-coordinate-overlays
  16506. :style toggle
  16507. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16508. "--"
  16509. ["Create" org-table-create (not (org-at-table-p))]
  16510. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16511. ["Import from File" org-table-import (not (org-at-table-p))]
  16512. ["Export to File" org-table-export (org-at-table-p)]
  16513. "--"
  16514. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16515. "--"
  16516. ("Plot"
  16517. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16518. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16519. (defun org-info (&optional node)
  16520. "Read documentation for Org in the info system.
  16521. With optional NODE, go directly to that node."
  16522. (interactive)
  16523. (info (format "(org)%s" (or node ""))))
  16524. (defun org-browse-news ()
  16525. "Browse the news for the latest major release."
  16526. (interactive)
  16527. (browse-url "https://orgmode.org/Changes.html"))
  16528. ;;;###autoload
  16529. (defun org-submit-bug-report ()
  16530. "Submit a bug report on Org via mail.
  16531. Don't hesitate to report any problems or inaccurate documentation.
  16532. If you don't have setup sending mail from (X)Emacs, please copy the
  16533. output buffer into your mail program, as it gives us important
  16534. information about your Org version and configuration."
  16535. (interactive)
  16536. (require 'reporter)
  16537. (defvar reporter-prompt-for-summary-p)
  16538. (org-load-modules-maybe)
  16539. (org-require-autoloaded-modules)
  16540. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16541. (reporter-submit-bug-report
  16542. "emacs-orgmode@gnu.org"
  16543. (org-version nil 'full)
  16544. (let (list)
  16545. (save-window-excursion
  16546. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16547. (delete-other-windows)
  16548. (erase-buffer)
  16549. (insert "You are about to submit a bug report to the Org mailing list.
  16550. If your report is about Org installation, please read this section:
  16551. https://orgmode.org/org.html#Installation
  16552. Please read https://orgmode.org/org.html#Feedback on how to make
  16553. a good report, it will help Org contributors fixing your problem.
  16554. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16555. if the issue you are about to raise has already been dealt with.
  16556. We also would like to add your full Org and Outline configuration
  16557. to the bug report. It will help us debugging the issue.
  16558. *HOWEVER*, some variables you have customized may contain private
  16559. information. The names of customers, colleagues, or friends, might
  16560. appear in the form of file names, tags, todo states or search strings.
  16561. If you answer \"yes\" to the prompt, you might want to check and remove
  16562. such private information before sending the email.")
  16563. (add-text-properties (point-min) (point-max) '(face org-warning))
  16564. (when (yes-or-no-p "Include your Org configuration ")
  16565. (mapatoms
  16566. (lambda (v)
  16567. (and (boundp v)
  16568. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16569. (or (and (symbol-value v)
  16570. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16571. (and
  16572. (get v 'custom-type) (get v 'standard-value)
  16573. (not (equal (symbol-value v)
  16574. (eval (car (get v 'standard-value)) t)))))
  16575. (push v list)))))
  16576. (kill-buffer (get-buffer "*Warn about privacy*"))
  16577. list))
  16578. nil nil
  16579. "Remember to cover the basics, that is, what you expected to happen and
  16580. what in fact did happen. You don't know how to make a good report? See
  16581. https://orgmode.org/manual/Feedback.html#Feedback
  16582. Your bug report will be posted to the Org mailing list.
  16583. ------------------------------------------------------------------------")
  16584. (save-excursion
  16585. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16586. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16587. (defvar org-agenda-file-menu-enabled t
  16588. "When non-nil, refresh Agenda files in Org menu when loading Org.")
  16589. (defun org-install-agenda-files-menu ()
  16590. "Install agenda file menu."
  16591. (let ((bl (buffer-list)))
  16592. (save-excursion
  16593. (while bl
  16594. (set-buffer (pop bl))
  16595. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16596. (when (derived-mode-p 'org-mode)
  16597. (easy-menu-change
  16598. '("Org") "File List for Agenda"
  16599. (append
  16600. (list
  16601. ["Edit File List" (org-edit-agenda-file-list) t]
  16602. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16603. ["Remove Current File from List" org-remove-file t]
  16604. ["Cycle through agenda files" org-cycle-agenda-files t]
  16605. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16606. "--")
  16607. (mapcar 'org-file-menu-entry
  16608. ;; Prevent initialization from failing.
  16609. (ignore-errors (org-agenda-files t)))))))))
  16610. ;;;; Documentation
  16611. (defun org-require-autoloaded-modules ()
  16612. (interactive)
  16613. (mapc #'require
  16614. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16615. org-table org-timer)))
  16616. ;;;###autoload
  16617. (defun org-reload (&optional uncompiled)
  16618. "Reload all Org Lisp files.
  16619. With prefix arg UNCOMPILED, load the uncompiled versions."
  16620. (interactive "P")
  16621. (require 'loadhist)
  16622. (let* ((org-dir (org-find-library-dir "org"))
  16623. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16624. (feature-re "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?")
  16625. (remove-re (format "\\`%s\\'"
  16626. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16627. (feats (delete-dups
  16628. (mapcar 'file-name-sans-extension
  16629. (mapcar 'file-name-nondirectory
  16630. (delq nil
  16631. (mapcar 'feature-file
  16632. features))))))
  16633. (lfeat (append
  16634. (sort
  16635. (setq feats
  16636. (delq nil (mapcar
  16637. (lambda (f)
  16638. (if (and (string-match feature-re f)
  16639. (not (string-match remove-re f)))
  16640. f nil))
  16641. feats)))
  16642. 'string-lessp)
  16643. (list "org-version" "org")))
  16644. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16645. load-uncore load-misses)
  16646. (setq load-misses
  16647. (delq t
  16648. (mapcar (lambda (f)
  16649. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16650. (and (string= org-dir contrib-dir)
  16651. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16652. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16653. (push f load-uncore)
  16654. t)
  16655. f))
  16656. lfeat)))
  16657. (when load-uncore
  16658. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16659. (if (> (length load-uncore) 1) "s were" " was")
  16660. (reverse load-uncore)))
  16661. (if load-misses
  16662. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16663. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16664. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16665. ;;;###autoload
  16666. (defun org-customize ()
  16667. "Call the customize function with org as argument."
  16668. (interactive)
  16669. (org-load-modules-maybe)
  16670. (org-require-autoloaded-modules)
  16671. (customize-browse 'org))
  16672. (defun org-create-customize-menu ()
  16673. "Create a full customization menu for Org mode, insert it into the menu."
  16674. (interactive)
  16675. (org-load-modules-maybe)
  16676. (org-require-autoloaded-modules)
  16677. (easy-menu-change
  16678. '("Org") "Customize"
  16679. `(["Browse Org group" org-customize t]
  16680. "--"
  16681. ,(customize-menu-create 'org)
  16682. ["Set" Custom-set t]
  16683. ["Save" Custom-save t]
  16684. ["Reset to Current" Custom-reset-current t]
  16685. ["Reset to Saved" Custom-reset-saved t]
  16686. ["Reset to Standard Settings" Custom-reset-standard t]))
  16687. (message "\"Org\"-menu now contains full customization menu"))
  16688. ;;;; Miscellaneous stuff
  16689. ;;; Generally useful functions
  16690. (defun org-in-clocktable-p ()
  16691. "Check if the cursor is in a clocktable."
  16692. (let ((pos (point)) start)
  16693. (save-excursion
  16694. (end-of-line 1)
  16695. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16696. (setq start (match-beginning 0))
  16697. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16698. (>= (match-end 0) pos)
  16699. start))))
  16700. (defun org-in-verbatim-emphasis ()
  16701. (save-match-data
  16702. (and (org-in-regexp org-verbatim-re 2)
  16703. (>= (point) (match-beginning 3))
  16704. (<= (point) (match-end 4)))))
  16705. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16706. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16707. (if (and marker (marker-buffer marker)
  16708. (buffer-live-p (marker-buffer marker)))
  16709. (progn
  16710. (pop-to-buffer-same-window (marker-buffer marker))
  16711. (when (or (> marker (point-max)) (< marker (point-min)))
  16712. (widen))
  16713. (goto-char marker)
  16714. (org-fold-show-context 'org-goto))
  16715. (if bookmark
  16716. (bookmark-jump bookmark)
  16717. (error "Cannot find location"))))
  16718. (defun org-quote-csv-field (s)
  16719. "Quote field for inclusion in CSV material."
  16720. (if (string-match "[\",]" s)
  16721. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16722. s))
  16723. (defun org-force-self-insert (N)
  16724. "Needed to enforce self-insert under remapping."
  16725. (interactive "p")
  16726. (self-insert-command N))
  16727. (defun org-quote-vert (s)
  16728. "Replace \"|\" with \"\\vert\"."
  16729. (while (string-match "|" s)
  16730. (setq s (replace-match "\\vert" t t s)))
  16731. s)
  16732. (defun org-uuidgen-p (s)
  16733. "Is S an ID created by UUIDGEN?"
  16734. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16735. (defun org-in-src-block-p (&optional inside element)
  16736. "Whether point is in a code source block.
  16737. When INSIDE is non-nil, don't consider we are within a source
  16738. block when point is at #+BEGIN_SRC or #+END_SRC.
  16739. When ELEMENT is provided, it is considered to be element at point."
  16740. (save-match-data (setq element (or element (org-element-at-point))))
  16741. (when (eq 'src-block (org-element-type element))
  16742. (or (not inside)
  16743. (not (or (= (line-beginning-position)
  16744. (org-element-property :post-affiliated element))
  16745. (= (1+ (line-end-position))
  16746. (- (org-element-property :end element)
  16747. (org-element-property :post-blank element))))))))
  16748. (defun org-context ()
  16749. "Return a list of contexts of the current cursor position.
  16750. If several contexts apply, all are returned.
  16751. Each context entry is a list with a symbol naming the context, and
  16752. two positions indicating start and end of the context. Possible
  16753. contexts are:
  16754. :headline anywhere in a headline
  16755. :headline-stars on the leading stars in a headline
  16756. :todo-keyword on a TODO keyword (including DONE) in a headline
  16757. :tags on the TAGS in a headline
  16758. :priority on the priority cookie in a headline
  16759. :item on the first line of a plain list item
  16760. :item-bullet on the bullet/number of a plain list item
  16761. :checkbox on the checkbox in a plain list item
  16762. :table in an Org table
  16763. :table-special on a special filed in a table
  16764. :table-table in a table.el table
  16765. :clocktable in a clocktable
  16766. :src-block in a source block
  16767. :link on a hyperlink
  16768. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16769. :latex-fragment on a LaTeX fragment
  16770. :latex-preview on a LaTeX fragment with overlaid preview image
  16771. This function expects the position to be visible because it uses font-lock
  16772. faces as a help to recognize the following contexts: :table-special, :link,
  16773. and :keyword."
  16774. (let* ((f (get-text-property (point) 'face))
  16775. (faces (if (listp f) f (list f)))
  16776. (case-fold-search t)
  16777. (p (point)) clist o)
  16778. ;; First the large context
  16779. (cond
  16780. ((org-at-heading-p)
  16781. (push (list :headline (line-beginning-position) (line-end-position)) clist)
  16782. (when (progn
  16783. (beginning-of-line 1)
  16784. (looking-at org-todo-line-tags-regexp))
  16785. (push (org-point-in-group p 1 :headline-stars) clist)
  16786. (push (org-point-in-group p 2 :todo-keyword) clist)
  16787. (push (org-point-in-group p 4 :tags) clist))
  16788. (goto-char p)
  16789. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16790. (when (looking-at "\\[#[A-Z0-9]\\]")
  16791. (push (org-point-in-group p 0 :priority) clist)))
  16792. ((org-at-item-p)
  16793. (push (org-point-in-group p 2 :item-bullet) clist)
  16794. (push (list :item (line-beginning-position)
  16795. (save-excursion (org-end-of-item) (point)))
  16796. clist)
  16797. (and (org-at-item-checkbox-p)
  16798. (push (org-point-in-group p 0 :checkbox) clist)))
  16799. ((org-at-table-p)
  16800. (push (list :table (org-table-begin) (org-table-end)) clist)
  16801. (when (memq 'org-formula faces)
  16802. (push (list :table-special
  16803. (previous-single-property-change p 'face)
  16804. (next-single-property-change p 'face))
  16805. clist)))
  16806. ((org-at-table-p 'any)
  16807. (push (list :table-table) clist)))
  16808. (goto-char p)
  16809. (let ((case-fold-search t))
  16810. ;; New the "medium" contexts: clocktables, source blocks
  16811. (cond ((org-in-clocktable-p)
  16812. (push (list :clocktable
  16813. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16814. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16815. (match-beginning 1))
  16816. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16817. (match-end 0)))
  16818. clist))
  16819. ((org-in-src-block-p)
  16820. (push (list :src-block
  16821. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16822. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16823. (match-beginning 1))
  16824. (and (search-forward "#+END_SRC" nil t)
  16825. (match-beginning 0)))
  16826. clist))))
  16827. (goto-char p)
  16828. ;; Now the small context
  16829. (cond
  16830. ((org-at-timestamp-p)
  16831. (push (org-point-in-group p 0 :timestamp) clist))
  16832. ((memq 'org-link faces)
  16833. (push (list :link
  16834. (previous-single-property-change p 'face)
  16835. (next-single-property-change p 'face))
  16836. clist))
  16837. ((memq 'org-special-keyword faces)
  16838. (push (list :keyword
  16839. (previous-single-property-change p 'face)
  16840. (next-single-property-change p 'face))
  16841. clist))
  16842. ((setq o (cl-some
  16843. (lambda (o)
  16844. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16845. o))
  16846. (overlays-at (point))))
  16847. (push (list :latex-fragment
  16848. (overlay-start o) (overlay-end o))
  16849. clist)
  16850. (push (list :latex-preview
  16851. (overlay-start o) (overlay-end o))
  16852. clist))
  16853. ((org-inside-LaTeX-fragment-p)
  16854. ;; FIXME: positions wrong.
  16855. (push (list :latex-fragment (point) (point)) clist)))
  16856. (setq clist (nreverse (delq nil clist)))
  16857. clist))
  16858. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16859. "Non-nil when point is between matches of START-RE and END-RE.
  16860. Also return a non-nil value when point is on one of the matches.
  16861. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16862. buffer positions. Default values are the positions of headlines
  16863. surrounding the point.
  16864. The functions returns a cons cell whose car (resp. cdr) is the
  16865. position before START-RE (resp. after END-RE)."
  16866. (save-match-data
  16867. (let ((pos (point))
  16868. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16869. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16870. beg end)
  16871. (save-excursion
  16872. ;; Point is on a block when on START-RE or if START-RE can be
  16873. ;; found before it...
  16874. (and (or (org-in-regexp start-re)
  16875. (re-search-backward start-re limit-up t))
  16876. (setq beg (match-beginning 0))
  16877. ;; ... and END-RE after it...
  16878. (goto-char (match-end 0))
  16879. (re-search-forward end-re limit-down t)
  16880. (> (setq end (match-end 0)) pos)
  16881. ;; ... without another START-RE in-between.
  16882. (goto-char (match-beginning 0))
  16883. (not (re-search-backward start-re (1+ beg) t))
  16884. ;; Return value.
  16885. (cons beg end))))))
  16886. (defun org-in-block-p (names)
  16887. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16888. NAMES is a list of strings containing names of blocks.
  16889. Return first block name matched, or nil. Beware that in case of
  16890. nested blocks, the returned name may not belong to the closest
  16891. block from point."
  16892. (save-match-data
  16893. (catch 'exit
  16894. (let ((case-fold-search t)
  16895. (lim-up (save-excursion (outline-previous-heading)))
  16896. (lim-down (save-excursion (outline-next-heading))))
  16897. (dolist (name names)
  16898. (let ((n (regexp-quote name)))
  16899. (when (org-between-regexps-p
  16900. (concat "^[ \t]*#\\+begin_" n)
  16901. (concat "^[ \t]*#\\+end_" n)
  16902. lim-up lim-down)
  16903. (throw 'exit n)))))
  16904. nil)))
  16905. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16906. "Call `multi-occur' with buffers for all agenda files."
  16907. (interactive "sOrg-files matching: ")
  16908. (let* ((files (org-agenda-files))
  16909. (tnames (mapcar #'file-truename files))
  16910. (extra org-agenda-text-search-extra-files))
  16911. (when (eq (car extra) 'agenda-archives)
  16912. (setq extra (cdr extra))
  16913. (setq files (org-add-archive-files files)))
  16914. (dolist (f extra)
  16915. (unless (member (file-truename f) tnames)
  16916. (unless (member f files) (setq files (append files (list f))))
  16917. (setq tnames (append tnames (list (file-truename f))))))
  16918. (multi-occur
  16919. (mapcar (lambda (x)
  16920. (with-current-buffer
  16921. ;; FIXME: Why not just (find-file-noselect x)?
  16922. ;; Is it to avoid the "revert buffer" prompt?
  16923. (or (get-file-buffer x) (find-file-noselect x))
  16924. (widen)
  16925. (current-buffer)))
  16926. files)
  16927. regexp)))
  16928. (add-hook 'occur-mode-find-occurrence-hook
  16929. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16930. (defun org-occur-link-in-agenda-files ()
  16931. "Create a link and search for it in the agendas.
  16932. The link is not stored in `org-stored-links', it is just created
  16933. for the search purpose."
  16934. (interactive)
  16935. (let ((link (condition-case nil
  16936. (org-store-link nil)
  16937. (error "Unable to create a link to here"))))
  16938. (org-occur-in-agenda-files (regexp-quote link))))
  16939. (defun org-back-over-empty-lines ()
  16940. "Move backwards over whitespace, to the beginning of the first empty line.
  16941. Returns the number of empty lines passed."
  16942. (let ((pos (point)))
  16943. (if (cdr (assq 'heading org-blank-before-new-entry))
  16944. (skip-chars-backward " \t\n\r")
  16945. (unless (eobp)
  16946. (forward-line -1)))
  16947. (beginning-of-line 2)
  16948. (goto-char (min (point) pos))
  16949. (count-lines (point) pos)))
  16950. ;;; TODO: Only called once, from ox-odt which should probably use
  16951. ;;; org-export-inline-image-p or something.
  16952. (defun org-file-image-p (file)
  16953. "Return non-nil if FILE is an image."
  16954. (save-match-data
  16955. (string-match (image-file-name-regexp) file)))
  16956. (defun org-get-cursor-date (&optional with-time)
  16957. "Return the date at cursor in as a time.
  16958. This works in the calendar and in the agenda, anywhere else it just
  16959. returns the current time.
  16960. If WITH-TIME is non-nil, returns the time of the event at point (in
  16961. the agenda) or the current time of the day; otherwise returns the
  16962. earliest time on the cursor date that Org treats as that date
  16963. (bearing in mind `org-extend-today-until')."
  16964. (let (date day defd tp hod mod)
  16965. (when with-time
  16966. (setq tp (get-text-property (point) 'time))
  16967. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16968. (setq hod (string-to-number (match-string 1 tp))
  16969. mod (string-to-number (match-string 2 tp))))
  16970. (or tp (let ((now (decode-time)))
  16971. (setq hod (nth 2 now)
  16972. mod (nth 1 now)))))
  16973. (cond
  16974. ((eq major-mode 'calendar-mode)
  16975. (setq date (calendar-cursor-to-date)
  16976. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16977. (nth 1 date) (nth 0 date) (nth 2 date))))
  16978. ((eq major-mode 'org-agenda-mode)
  16979. (setq day (get-text-property (point) 'day))
  16980. (when day
  16981. (setq date (calendar-gregorian-from-absolute day)
  16982. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16983. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16984. (or defd (current-time))))
  16985. (defun org-mark-subtree (&optional up)
  16986. "Mark the current subtree.
  16987. This puts point at the start of the current subtree, and mark at
  16988. the end. If a numeric prefix UP is given, move up into the
  16989. hierarchy of headlines by UP levels before marking the subtree."
  16990. (interactive "P")
  16991. (org-with-limited-levels
  16992. (cond ((org-at-heading-p) (beginning-of-line))
  16993. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16994. (t (outline-previous-visible-heading 1))))
  16995. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16996. (if (called-interactively-p 'any)
  16997. (call-interactively 'org-mark-element)
  16998. (org-mark-element)))
  16999. ;;; Indentation
  17000. (defun org--at-headline-data-p (&optional beg element)
  17001. "Return non-nil when `point' or BEG is inside headline metadata.
  17002. Metadata is planning line, properties drawer, logbook drawer right
  17003. after property drawer, or clock log line immediately following
  17004. properties drawer/planning line/ heading.
  17005. Optional argument ELEMENT contains element at BEG."
  17006. (org-with-wide-buffer
  17007. (when beg (goto-char beg))
  17008. (setq element (or element (org-element-at-point)))
  17009. (if (not (org-element-lineage element '(headline inlinetask)))
  17010. nil ; Not inside heading.
  17011. ;; Skip to top-level parent in section.
  17012. (while (not (eq 'section (org-element-type (org-element-property :parent element))))
  17013. (setq element (org-element-property :parent element)))
  17014. (pcase (org-element-type element)
  17015. ((or `planning `property-drawer)
  17016. t)
  17017. (`drawer
  17018. ;; LOGBOOK drawer with appropriate name.
  17019. (equal
  17020. (org-log-into-drawer)
  17021. (org-element-property :drawer-name element)))
  17022. (`clock
  17023. ;; Previous element must be headline metadata or headline.
  17024. (goto-char (1- (org-element-property :begin element)))
  17025. (or (org-at-heading-p)
  17026. (org--at-headline-data-p)))))))
  17027. (defvar org-element-greater-elements)
  17028. (defun org--get-expected-indentation (element contentsp)
  17029. "Expected indentation column for current line, according to ELEMENT.
  17030. ELEMENT is an element containing point. CONTENTSP is non-nil
  17031. when indentation is to be computed according to contents of
  17032. ELEMENT."
  17033. (let ((type (org-element-type element))
  17034. (start (org-element-property :begin element))
  17035. (post-affiliated (org-element-property :post-affiliated element)))
  17036. (org-with-wide-buffer
  17037. (cond
  17038. (contentsp
  17039. (cl-case type
  17040. ((diary-sexp footnote-definition) 0)
  17041. (section
  17042. (org--get-expected-indentation
  17043. (org-element-property :parent element)
  17044. t))
  17045. ((headline inlinetask nil)
  17046. (if (not org-adapt-indentation) 0
  17047. (let ((level (org-current-level)))
  17048. (if level (1+ level) 0))))
  17049. ((item plain-list) (org-list-item-body-column post-affiliated))
  17050. (t
  17051. (goto-char start)
  17052. (current-indentation))))
  17053. ((memq type '(headline inlinetask nil))
  17054. (if (org-match-line "[ \t]*$")
  17055. (org--get-expected-indentation element t)
  17056. 0))
  17057. ((memq type '(diary-sexp footnote-definition)) 0)
  17058. ;; First paragraph of a footnote definition or an item.
  17059. ;; Indent like parent.
  17060. ((< (line-beginning-position) start)
  17061. (org--get-expected-indentation
  17062. (org-element-property :parent element) t))
  17063. ;; At first line: indent according to previous sibling, if any,
  17064. ;; ignoring footnote definitions and inline tasks, or parent's
  17065. ;; contents. If `org-adapt-indentation' is `headline-data', ignore
  17066. ;; previous headline data siblings.
  17067. ((= (line-beginning-position) start)
  17068. (catch 'exit
  17069. (while t
  17070. (if (= (point-min) start) (throw 'exit 0)
  17071. (goto-char (1- start))
  17072. (let* ((previous (org-element-at-point))
  17073. (parent previous))
  17074. (while (and parent (<= (org-element-property :end parent) start))
  17075. (setq previous parent
  17076. parent (org-element-property :parent parent)))
  17077. (cond
  17078. ((not previous) (throw 'exit 0))
  17079. ((> (org-element-property :end previous) start)
  17080. (throw 'exit (org--get-expected-indentation previous t)))
  17081. ((memq (org-element-type previous)
  17082. '(footnote-definition inlinetask))
  17083. (setq start (org-element-property :begin previous)))
  17084. ;; Do not indent like previous when the previous
  17085. ;; element is headline data and `org-adapt-indentation'
  17086. ;; is set to `headline-data'.
  17087. ((and (eq 'headline-data org-adapt-indentation)
  17088. (not (org--at-headline-data-p start element))
  17089. (or (org-at-heading-p)
  17090. (org--at-headline-data-p (1- start) previous)))
  17091. (throw 'exit 0))
  17092. (t (goto-char (org-element-property :begin previous))
  17093. (throw 'exit
  17094. (if (bolp) (current-indentation)
  17095. ;; At first paragraph in an item or
  17096. ;; a footnote definition.
  17097. (org--get-expected-indentation
  17098. (org-element-property :parent previous) t))))))))))
  17099. ;; Otherwise, move to the first non-blank line above.
  17100. (t
  17101. (beginning-of-line)
  17102. (let ((pos (point)))
  17103. (skip-chars-backward " \r\t\n")
  17104. (cond
  17105. ;; Two blank lines end a footnote definition or a plain
  17106. ;; list. When we indent an empty line after them, the
  17107. ;; containing list or footnote definition is over, so it
  17108. ;; qualifies as a previous sibling. Therefore, we indent
  17109. ;; like its first line.
  17110. ((and (memq type '(footnote-definition plain-list))
  17111. (> (count-lines (point) pos) 2))
  17112. (goto-char start)
  17113. (current-indentation))
  17114. ;; Line above is the first one of a paragraph at the
  17115. ;; beginning of an item or a footnote definition. Indent
  17116. ;; like parent.
  17117. ((< (line-beginning-position) start)
  17118. (org--get-expected-indentation
  17119. (org-element-property :parent element) t))
  17120. ;; Line above is the beginning of an element, i.e., point
  17121. ;; was originally on the blank lines between element's start
  17122. ;; and contents.
  17123. ((= (line-beginning-position) post-affiliated)
  17124. (org--get-expected-indentation element t))
  17125. ;; POS is after contents in a greater element. Indent like
  17126. ;; the beginning of the element.
  17127. ((and (memq type org-element-greater-elements)
  17128. (let ((cend (org-element-property :contents-end element)))
  17129. (and cend (<= cend pos))))
  17130. ;; As a special case, if point is at the end of a footnote
  17131. ;; definition or an item, indent like the very last element
  17132. ;; within. If that last element is an item, indent like
  17133. ;; its contents.
  17134. (if (memq type '(footnote-definition item plain-list))
  17135. (let ((last (org-element-at-point)))
  17136. (goto-char pos)
  17137. (org--get-expected-indentation
  17138. last (eq (org-element-type last) 'item)))
  17139. (goto-char start)
  17140. (current-indentation)))
  17141. ;; In any other case, indent like the current line.
  17142. (t (current-indentation)))))
  17143. ;; Finally, no indentation is needed, fall back to 0.
  17144. (t (current-indentation))))))
  17145. (defun org--align-node-property ()
  17146. "Align node property at point.
  17147. Alignment is done according to `org-property-format', which see."
  17148. (when (save-excursion
  17149. (beginning-of-line)
  17150. (looking-at org-property-re))
  17151. (combine-change-calls (match-beginning 0) (match-end 0)
  17152. (let ((newtext (concat (match-string 4)
  17153. (org-trim
  17154. (format org-property-format (match-string 1) (match-string 3))))))
  17155. ;; Do not use `replace-match' here as we want to inherit folding
  17156. ;; properties if inside fold.
  17157. (delete-region (match-beginning 0) (match-end 0))
  17158. (insert-and-inherit newtext)))))
  17159. (defun org-indent-line ()
  17160. "Indent line depending on context.
  17161. Indentation is done according to the following rules:
  17162. - Footnote definitions, diary sexps, headlines and inline tasks
  17163. have to start at column 0.
  17164. - On the very first line of an element, consider, in order, the
  17165. next rules until one matches:
  17166. 1. If there's a sibling element before, ignoring footnote
  17167. definitions and inline tasks, indent like its first line.
  17168. 2. If element has a parent, indent like its contents. More
  17169. precisely, if parent is an item, indent after the bullet.
  17170. Else, indent like parent's first line.
  17171. 3. Otherwise, indent relatively to current level, if
  17172. `org-adapt-indentation' is t, or to left margin.
  17173. - On a blank line at the end of an element, indent according to
  17174. the type of the element. More precisely
  17175. 1. If element is a plain list, an item, or a footnote
  17176. definition, indent like the very last element within.
  17177. 2. If element is a paragraph, indent like its last non blank
  17178. line.
  17179. 3. Otherwise, indent like its very first line.
  17180. - In the code part of a source block, use language major mode
  17181. to indent current line if `org-src-tab-acts-natively' is
  17182. non-nil. If it is nil, do nothing.
  17183. - Otherwise, indent like the first non-blank line above.
  17184. The function doesn't indent an item as it could break the whole
  17185. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17186. `\\[org-shiftmetaright]'.
  17187. Also align node properties according to `org-property-format'."
  17188. (interactive)
  17189. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  17190. (type (org-element-type element)))
  17191. (unless (or (org-at-heading-p)
  17192. (and (eq org-adapt-indentation 'headline-data)
  17193. (not (org--at-headline-data-p nil element))
  17194. (save-excursion
  17195. (goto-char (1- (org-element-property :begin element)))
  17196. (or (org-at-heading-p)
  17197. (org--at-headline-data-p)))))
  17198. (cond ((and (memq type '(plain-list item))
  17199. (= (line-beginning-position)
  17200. (org-element-property :post-affiliated element)))
  17201. nil)
  17202. ((and (eq type 'latex-environment)
  17203. (>= (point) (org-element-property :post-affiliated element))
  17204. (< (point)
  17205. (org-with-point-at (org-element-property :end element)
  17206. (skip-chars-backward " \t\n")
  17207. (line-beginning-position 2))))
  17208. nil)
  17209. ((and (eq type 'src-block)
  17210. org-src-tab-acts-natively
  17211. (> (line-beginning-position)
  17212. (org-element-property :post-affiliated element))
  17213. (< (line-beginning-position)
  17214. (org-with-point-at (org-element-property :end element)
  17215. (skip-chars-backward " \t\n")
  17216. (line-beginning-position))))
  17217. ;; At the beginning of a blank line, do some preindentation. This
  17218. ;; signals org-src--edit-element to preserve the indentation on exit
  17219. (when (and (looking-at-p "^[[:space:]]*$")
  17220. (not org-src-preserve-indentation))
  17221. (let ((element (org-element-at-point))
  17222. block-content-ind some-ind)
  17223. (org-with-point-at (org-element-property :begin element)
  17224. (setq block-content-ind (+ (current-indentation)
  17225. org-edit-src-content-indentation))
  17226. (forward-line)
  17227. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17228. (backward-char)
  17229. (setq some-ind (if (looking-at-p "#\\+end_src")
  17230. block-content-ind (current-indentation))))
  17231. (indent-line-to (min block-content-ind some-ind))))
  17232. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17233. (t
  17234. (let ((column (org--get-expected-indentation element nil)))
  17235. ;; Preserve current column.
  17236. (if (<= (current-column) (current-indentation))
  17237. (indent-line-to column)
  17238. (save-excursion (indent-line-to column))))
  17239. ;; Align node property. Also preserve current column.
  17240. (when (eq type 'node-property)
  17241. (let ((column (current-column)))
  17242. (org--align-node-property)
  17243. (org-move-to-column column))))))))
  17244. (defun org-indent-region (start end)
  17245. "Indent each non-blank line in the region.
  17246. Called from a program, START and END specify the region to
  17247. indent. The function will not indent contents of example blocks,
  17248. verse blocks and export blocks as leading white spaces are
  17249. assumed to be significant there."
  17250. (interactive "r")
  17251. (save-excursion
  17252. (goto-char start)
  17253. (skip-chars-forward " \r\t\n")
  17254. (unless (eobp) (beginning-of-line))
  17255. (let ((indent-to
  17256. (lambda (ind pos)
  17257. ;; Set IND as indentation for all lines between point and
  17258. ;; POS. Blank lines are ignored. Leave point after POS
  17259. ;; once done.
  17260. (let ((limit (copy-marker pos)))
  17261. (while (< (point) limit)
  17262. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17263. (forward-line))
  17264. (set-marker limit nil))))
  17265. (end (copy-marker end)))
  17266. (while (< (point) end)
  17267. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17268. (let* ((element (org-element-at-point))
  17269. (type (org-element-type element))
  17270. (element-end (copy-marker (org-element-property :end element)))
  17271. (ind (org--get-expected-indentation element nil)))
  17272. (cond
  17273. ;; Element indented as a single block. Example blocks
  17274. ;; preserving indentation are a special case since the
  17275. ;; "contents" must not be indented whereas the block
  17276. ;; boundaries can.
  17277. ((or (memq type '(export-block latex-environment))
  17278. (and (eq type 'example-block)
  17279. (not
  17280. (or org-src-preserve-indentation
  17281. (org-element-property :preserve-indent element)))))
  17282. (let ((offset (- ind (current-indentation))))
  17283. (unless (zerop offset)
  17284. (indent-rigidly (org-element-property :begin element)
  17285. (org-element-property :end element)
  17286. offset)))
  17287. (goto-char element-end))
  17288. ;; Elements indented line wise. Be sure to exclude
  17289. ;; example blocks (preserving indentation) and source
  17290. ;; blocks from this category as they are treated
  17291. ;; specially later.
  17292. ((or (memq type '(paragraph table table-row))
  17293. (not (or (org-element-property :contents-begin element)
  17294. (memq type '(example-block src-block)))))
  17295. (when (eq type 'node-property)
  17296. (org--align-node-property)
  17297. (beginning-of-line))
  17298. (funcall indent-to ind (min element-end end)))
  17299. ;; Elements consisting of three parts: before the
  17300. ;; contents, the contents, and after the contents. The
  17301. ;; contents are treated specially, according to the
  17302. ;; element type, or not indented at all. Other parts are
  17303. ;; indented as a single block.
  17304. (t
  17305. (let* ((post (copy-marker
  17306. (org-element-property :post-affiliated element)))
  17307. (cbeg
  17308. (copy-marker
  17309. (cond
  17310. ((not (org-element-property :contents-begin element))
  17311. ;; Fake contents for source blocks.
  17312. (org-with-wide-buffer
  17313. (goto-char post)
  17314. (line-beginning-position 2)))
  17315. ((memq type '(footnote-definition item plain-list))
  17316. ;; Contents in these elements could start on
  17317. ;; the same line as the beginning of the
  17318. ;; element. Make sure we start indenting
  17319. ;; from the second line.
  17320. (org-with-wide-buffer
  17321. (goto-char post)
  17322. (end-of-line)
  17323. (skip-chars-forward " \r\t\n")
  17324. (if (eobp) (point) (line-beginning-position))))
  17325. (t (org-element-property :contents-begin element)))))
  17326. (cend (copy-marker
  17327. (or (org-element-property :contents-end element)
  17328. ;; Fake contents for source blocks.
  17329. (org-with-wide-buffer
  17330. (goto-char element-end)
  17331. (skip-chars-backward " \r\t\n")
  17332. (line-beginning-position)))
  17333. t)))
  17334. ;; Do not change items indentation individually as it
  17335. ;; might break the list as a whole. On the other
  17336. ;; hand, when at a plain list, indent it as a whole.
  17337. (cond ((eq type 'plain-list)
  17338. (let ((offset (- ind (current-indentation))))
  17339. (unless (zerop offset)
  17340. (indent-rigidly (org-element-property :begin element)
  17341. (org-element-property :end element)
  17342. offset))
  17343. (goto-char cbeg)))
  17344. ((eq type 'item) (goto-char cbeg))
  17345. (t (funcall indent-to ind (min cbeg end))))
  17346. (when (< (point) end)
  17347. (cl-case type
  17348. ((example-block verse-block))
  17349. (src-block
  17350. ;; In a source block, indent source code
  17351. ;; according to language major mode, but only if
  17352. ;; `org-src-tab-acts-natively' is non-nil.
  17353. (when (and (< (point) end) org-src-tab-acts-natively)
  17354. (ignore-errors
  17355. (org-babel-do-in-edit-buffer
  17356. (indent-region (point-min) (point-max))))))
  17357. (t (org-indent-region (point) (min cend end))))
  17358. (goto-char (min cend end))
  17359. (when (< (point) end)
  17360. (funcall indent-to ind (min element-end end))))
  17361. (set-marker post nil)
  17362. (set-marker cbeg nil)
  17363. (set-marker cend nil))))
  17364. (set-marker element-end nil))))
  17365. (set-marker end nil))))
  17366. (defun org-indent-drawer ()
  17367. "Indent the drawer at point."
  17368. (interactive)
  17369. (unless (save-excursion
  17370. (beginning-of-line)
  17371. (looking-at-p org-drawer-regexp))
  17372. (user-error "Not at a drawer"))
  17373. (let ((element (org-element-at-point-no-context)))
  17374. (unless (memq (org-element-type element) '(drawer property-drawer))
  17375. (user-error "Not at a drawer"))
  17376. (org-with-wide-buffer
  17377. (org-indent-region (org-element-property :begin element)
  17378. (org-element-property :end element))))
  17379. (message "Drawer at point indented"))
  17380. (defun org-indent-block ()
  17381. "Indent the block at point."
  17382. (interactive)
  17383. (unless (save-excursion
  17384. (beginning-of-line)
  17385. (let ((case-fold-search t))
  17386. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17387. (user-error "Not at a block"))
  17388. (let ((element (org-element-at-point-no-context)))
  17389. (unless (memq (org-element-type element)
  17390. '(comment-block center-block dynamic-block example-block
  17391. export-block quote-block special-block
  17392. src-block verse-block))
  17393. (user-error "Not at a block"))
  17394. (org-with-wide-buffer
  17395. (org-indent-region (org-element-property :begin element)
  17396. (org-element-property :end element))))
  17397. (message "Block at point indented"))
  17398. ;;; Filling
  17399. ;; We use our own fill-paragraph and auto-fill functions.
  17400. ;; `org-fill-paragraph' relies on adaptive filling and context
  17401. ;; checking. Appropriate `fill-prefix' is computed with
  17402. ;; `org-adaptive-fill-function'.
  17403. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17404. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17405. ;; `org-adaptive-fill-function' value. Internally,
  17406. ;; `org-comment-line-break-function' breaks the line.
  17407. ;; `org-setup-filling' installs filling and auto-filling related
  17408. ;; variables during `org-mode' initialization.
  17409. (defvar org--single-lines-list-is-paragraph) ; defined later
  17410. (defun org-setup-filling ()
  17411. (require 'org-element)
  17412. ;; Prevent auto-fill from inserting unwanted new items.
  17413. (setq-local fill-nobreak-predicate
  17414. (org-uniquify
  17415. (append fill-nobreak-predicate
  17416. '(org-fill-line-break-nobreak-p
  17417. org-fill-n-macro-as-item-nobreak-p
  17418. org-fill-paragraph-with-timestamp-nobreak-p))))
  17419. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17420. (setq-local paragraph-start paragraph-ending)
  17421. (setq-local paragraph-separate paragraph-ending))
  17422. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17423. (setq-local fill-forward-paragraph-function
  17424. (lambda (&optional arg)
  17425. (let ((org--single-lines-list-is-paragraph nil))
  17426. (org-forward-paragraph arg))))
  17427. (setq-local auto-fill-inhibit-regexp nil)
  17428. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17429. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17430. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17431. (defun org-fill-line-break-nobreak-p ()
  17432. "Non-nil when a new line at point would create an Org line break."
  17433. (save-excursion
  17434. (skip-chars-backward " \t")
  17435. (skip-chars-backward "\\\\")
  17436. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17437. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17438. "Non-nil when a new line at point would split a timestamp."
  17439. (and (org-at-timestamp-p 'lax)
  17440. (not (looking-at org-ts-regexp-both))))
  17441. (defun org-fill-n-macro-as-item-nobreak-p ()
  17442. "Non-nil when a new line at point would create a new list."
  17443. ;; During export, a "n" macro followed by a dot or a closing
  17444. ;; parenthesis can end up being parsed as a new list item.
  17445. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17446. (defun org-adaptive-fill-function ()
  17447. "Compute a fill prefix for the current line.
  17448. Return fill prefix, as a string, or nil if current line isn't
  17449. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17450. matches in paragraphs or comments, use it."
  17451. (org-with-wide-buffer
  17452. (unless (org-at-heading-p)
  17453. (let* ((p (line-beginning-position))
  17454. (element (save-excursion
  17455. (beginning-of-line)
  17456. (org-element-at-point)))
  17457. (type (org-element-type element))
  17458. (post-affiliated (org-element-property :post-affiliated element)))
  17459. (unless (< p post-affiliated)
  17460. (cl-case type
  17461. (comment
  17462. (save-excursion
  17463. (beginning-of-line)
  17464. (looking-at "[ \t]*")
  17465. (concat (match-string 0) "# ")))
  17466. (footnote-definition "")
  17467. ((item plain-list)
  17468. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17469. (paragraph
  17470. ;; Fill prefix is usually the same as the current line,
  17471. ;; unless the paragraph is at the beginning of an item.
  17472. (let ((parent (org-element-property :parent element)))
  17473. (save-excursion
  17474. (beginning-of-line)
  17475. (cond ((eq (org-element-type parent) 'item)
  17476. (make-string (org-list-item-body-column
  17477. (org-element-property :begin parent))
  17478. ?\s))
  17479. ((and adaptive-fill-regexp
  17480. ;; Locally disable
  17481. ;; `adaptive-fill-function' to let
  17482. ;; `fill-context-prefix' handle
  17483. ;; `adaptive-fill-regexp' variable.
  17484. (let (adaptive-fill-function)
  17485. (fill-context-prefix
  17486. post-affiliated
  17487. (org-element-property :end element)))))
  17488. ((looking-at "[ \t]+") (match-string 0))
  17489. (t "")))))
  17490. (comment-block
  17491. ;; Only fill contents if P is within block boundaries.
  17492. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17493. (forward-line)
  17494. (point)))
  17495. (cend (save-excursion
  17496. (goto-char (org-element-property :end element))
  17497. (skip-chars-backward " \r\t\n")
  17498. (line-beginning-position))))
  17499. (when (and (>= p cbeg) (< p cend))
  17500. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17501. (match-string 0)
  17502. ""))))))))))
  17503. (defun org-fill-element (&optional justify)
  17504. "Fill element at point, when applicable.
  17505. This function only applies to comment blocks, comments, example
  17506. blocks and paragraphs. Also, as a special case, re-align table
  17507. when point is at one.
  17508. If JUSTIFY is non-nil (interactively, with prefix argument),
  17509. justify as well. If `sentence-end-double-space' is non-nil, then
  17510. period followed by one space does not end a sentence, so don't
  17511. break a line there. The variable `fill-column' controls the
  17512. width for filling.
  17513. For convenience, when point is at a plain list, an item or
  17514. a footnote definition, try to fill the first paragraph within."
  17515. (with-syntax-table org-mode-transpose-word-syntax-table
  17516. ;; Move to end of line in order to get the first paragraph within
  17517. ;; a plain list or a footnote definition.
  17518. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17519. ;; First check if point is in a blank line at the beginning of
  17520. ;; the buffer. In that case, ignore filling.
  17521. (cl-case (org-element-type element)
  17522. ;; Use major mode filling function is source blocks.
  17523. (src-block (org-babel-do-in-edit-buffer
  17524. (push-mark (point-min))
  17525. (goto-char (point-max))
  17526. (setq mark-active t)
  17527. (funcall-interactively #'fill-paragraph justify 'region)))
  17528. ;; Align Org tables, leave table.el tables as-is.
  17529. (table-row (org-table-align) t)
  17530. (table
  17531. (when (eq (org-element-property :type element) 'org)
  17532. (save-excursion
  17533. (goto-char (org-element-property :post-affiliated element))
  17534. (org-table-align)))
  17535. t)
  17536. (paragraph
  17537. ;; Paragraphs may contain `line-break' type objects.
  17538. (let ((beg (max (point-min)
  17539. (org-element-property :contents-begin element)))
  17540. (end (min (point-max)
  17541. (org-element-property :contents-end element))))
  17542. ;; Do nothing if point is at an affiliated keyword.
  17543. (if (< (line-end-position) beg) t
  17544. ;; Fill paragraph, taking line breaks into account.
  17545. (save-excursion
  17546. (goto-char beg)
  17547. (let ((cuts (list beg)))
  17548. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17549. (when (eq 'line-break
  17550. (org-element-type
  17551. (save-excursion (backward-char)
  17552. (org-element-context))))
  17553. (push (point) cuts)))
  17554. (dolist (c (delq end cuts))
  17555. (fill-region-as-paragraph c end justify)
  17556. (setq end c))))
  17557. t)))
  17558. ;; Contents of `comment-block' type elements should be
  17559. ;; filled as plain text, but only if point is within block
  17560. ;; markers.
  17561. (comment-block
  17562. (let* ((case-fold-search t)
  17563. (beg (save-excursion
  17564. (goto-char (org-element-property :begin element))
  17565. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17566. (forward-line)
  17567. (point)))
  17568. (end (save-excursion
  17569. (goto-char (org-element-property :end element))
  17570. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17571. (line-beginning-position))))
  17572. (if (or (< (point) beg) (> (point) end)) t
  17573. (fill-region-as-paragraph
  17574. (save-excursion (end-of-line)
  17575. (re-search-backward "^[ \t]*$" beg 'move)
  17576. (line-beginning-position))
  17577. (save-excursion (beginning-of-line)
  17578. (re-search-forward "^[ \t]*$" end 'move)
  17579. (line-beginning-position))
  17580. justify))))
  17581. ;; Fill comments.
  17582. (comment
  17583. (let ((begin (org-element-property :post-affiliated element))
  17584. (end (org-element-property :end element)))
  17585. (when (and (>= (point) begin) (<= (point) end))
  17586. (let ((begin (save-excursion
  17587. (end-of-line)
  17588. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17589. (progn (forward-line) (point))
  17590. begin)))
  17591. (end (save-excursion
  17592. (end-of-line)
  17593. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17594. (1- (line-beginning-position))
  17595. (skip-chars-backward " \r\t\n")
  17596. (line-end-position)))))
  17597. ;; Do not fill comments when at a blank line.
  17598. (when (> end begin)
  17599. (let ((fill-prefix
  17600. (save-excursion
  17601. (beginning-of-line)
  17602. (looking-at "[ \t]*#")
  17603. (let ((comment-prefix (match-string 0)))
  17604. (goto-char (match-end 0))
  17605. (if (looking-at adaptive-fill-regexp)
  17606. (concat comment-prefix (match-string 0))
  17607. (concat comment-prefix " "))))))
  17608. (save-excursion
  17609. (fill-region-as-paragraph begin end justify))))))
  17610. t))
  17611. ;; Ignore every other element.
  17612. (otherwise t)))))
  17613. (defun org-fill-paragraph (&optional justify region)
  17614. "Fill element at point, when applicable.
  17615. This function only applies to comment blocks, comments, example
  17616. blocks and paragraphs. Also, as a special case, re-align table
  17617. when point is at one.
  17618. For convenience, when point is at a plain list, an item or
  17619. a footnote definition, try to fill the first paragraph within.
  17620. If JUSTIFY is non-nil (interactively, with prefix argument),
  17621. justify as well. If `sentence-end-double-space' is non-nil, then
  17622. period followed by one space does not end a sentence, so don't
  17623. break a line there. The variable `fill-column' controls the
  17624. width for filling.
  17625. The REGION argument is non-nil if called interactively; in that
  17626. case, if Transient Mark mode is enabled and the mark is active,
  17627. fill each of the elements in the active region, instead of just
  17628. filling the current element."
  17629. (interactive (progn
  17630. (barf-if-buffer-read-only)
  17631. (list (when current-prefix-arg 'full) t)))
  17632. (let ((hash (and (not (buffer-modified-p))
  17633. (org-buffer-hash))))
  17634. (cond
  17635. ((and region transient-mark-mode mark-active
  17636. (not (eq (region-beginning) (region-end))))
  17637. (let ((origin (point-marker))
  17638. (start (region-beginning)))
  17639. (unwind-protect
  17640. (progn
  17641. (goto-char (region-end))
  17642. (skip-chars-backward " \t\n")
  17643. (let ((org--single-lines-list-is-paragraph nil))
  17644. (while (> (point) start)
  17645. (org-fill-element justify)
  17646. (org-backward-paragraph)
  17647. (skip-chars-backward " \t\n"))))
  17648. (goto-char origin)
  17649. (set-marker origin nil))))
  17650. (t
  17651. (save-excursion
  17652. (when (org-match-line "[ \t]*$")
  17653. (skip-chars-forward " \t\n"))
  17654. (org-fill-element justify))))
  17655. ;; If we didn't change anything in the buffer (and the buffer was
  17656. ;; previously unmodified), then flip the modification status back
  17657. ;; to "unchanged".
  17658. (when (and hash (equal hash (org-buffer-hash)))
  17659. (set-buffer-modified-p nil))
  17660. ;; Return non-nil.
  17661. t))
  17662. (defun org-auto-fill-function ()
  17663. "Auto-fill function."
  17664. ;; Check if auto-filling is meaningful.
  17665. (let ((fc (current-fill-column)))
  17666. (when (and fc (> (current-column) fc))
  17667. (let* ((fill-prefix (org-adaptive-fill-function))
  17668. ;; Enforce empty fill prefix, if required. Otherwise, it
  17669. ;; will be computed again.
  17670. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17671. (when fill-prefix (do-auto-fill))))))
  17672. (defun org-comment-line-break-function (&optional soft)
  17673. "Break line at point and indent, continuing comment if within one.
  17674. The inserted newline is marked hard if variable
  17675. `use-hard-newlines' is true, unless optional argument SOFT is
  17676. non-nil."
  17677. (if soft (insert-and-inherit ?\n) (newline 1))
  17678. (save-excursion (forward-char -1) (delete-horizontal-space))
  17679. (delete-horizontal-space)
  17680. (indent-to-left-margin)
  17681. (insert-before-markers-and-inherit fill-prefix))
  17682. ;;; Fixed Width Areas
  17683. (defun org-toggle-fixed-width ()
  17684. "Toggle fixed-width markup.
  17685. Add or remove fixed-width markup on current line, whenever it
  17686. makes sense. Return an error otherwise.
  17687. If a region is active and if it contains only fixed-width areas
  17688. or blank lines, remove all fixed-width markup in it. If the
  17689. region contains anything else, convert all non-fixed-width lines
  17690. to fixed-width ones.
  17691. Blank lines at the end of the region are ignored unless the
  17692. region only contains such lines."
  17693. (interactive)
  17694. (if (not (org-region-active-p))
  17695. ;; No region:
  17696. ;;
  17697. ;; Remove fixed width marker only in a fixed-with element.
  17698. ;;
  17699. ;; Add fixed width maker in paragraphs, in blank lines after
  17700. ;; elements or at the beginning of a headline or an inlinetask,
  17701. ;; and before any one-line elements (e.g., a clock).
  17702. (progn
  17703. (beginning-of-line)
  17704. (let* ((element (org-element-at-point))
  17705. (type (org-element-type element)))
  17706. (cond
  17707. ((and (eq type 'fixed-width)
  17708. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17709. (replace-match
  17710. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17711. ((and (memq type '(babel-call clock comment diary-sexp headline
  17712. horizontal-rule keyword paragraph
  17713. planning))
  17714. (<= (org-element-property :post-affiliated element) (point)))
  17715. (skip-chars-forward " \t")
  17716. (insert ": "))
  17717. ((and (looking-at-p "[ \t]*$")
  17718. (or (eq type 'inlinetask)
  17719. (save-excursion
  17720. (skip-chars-forward " \r\t\n")
  17721. (<= (org-element-property :end element) (point)))))
  17722. (delete-region (point) (line-end-position))
  17723. (org-indent-line)
  17724. (insert ": "))
  17725. (t (user-error "Cannot insert a fixed-width line here")))))
  17726. ;; Region active.
  17727. (let* ((begin (save-excursion
  17728. (goto-char (region-beginning))
  17729. (line-beginning-position)))
  17730. (end (copy-marker
  17731. (save-excursion
  17732. (goto-char (region-end))
  17733. (unless (eolp) (beginning-of-line))
  17734. (if (save-excursion (re-search-backward "\\S-" begin t))
  17735. (progn (skip-chars-backward " \r\t\n") (point))
  17736. (point)))))
  17737. (all-fixed-width-p
  17738. (catch 'not-all-p
  17739. (save-excursion
  17740. (goto-char begin)
  17741. (skip-chars-forward " \r\t\n")
  17742. (when (eobp) (throw 'not-all-p nil))
  17743. (while (< (point) end)
  17744. (let ((element (org-element-at-point)))
  17745. (if (eq (org-element-type element) 'fixed-width)
  17746. (goto-char (org-element-property :end element))
  17747. (throw 'not-all-p nil))))
  17748. t))))
  17749. (if all-fixed-width-p
  17750. (save-excursion
  17751. (goto-char begin)
  17752. (while (< (point) end)
  17753. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17754. (replace-match
  17755. "" nil nil nil
  17756. (if (= (line-end-position) (match-end 0)) 0 1)))
  17757. (forward-line)))
  17758. (let ((min-ind (point-max)))
  17759. ;; Find minimum indentation across all lines.
  17760. (save-excursion
  17761. (goto-char begin)
  17762. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17763. (setq min-ind 0)
  17764. (catch 'zerop
  17765. (while (< (point) end)
  17766. (unless (looking-at-p "[ \t]*$")
  17767. (let ((ind (current-indentation)))
  17768. (setq min-ind (min min-ind ind))
  17769. (when (zerop ind) (throw 'zerop t))))
  17770. (forward-line)))))
  17771. ;; Loop over all lines and add fixed-width markup everywhere
  17772. ;; but in fixed-width lines.
  17773. (save-excursion
  17774. (goto-char begin)
  17775. (while (< (point) end)
  17776. (cond
  17777. ((org-at-heading-p)
  17778. (insert ": ")
  17779. (forward-line)
  17780. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17781. (insert ":")
  17782. (forward-line)))
  17783. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17784. (let* ((element (org-element-at-point))
  17785. (element-end (org-element-property :end element)))
  17786. (if (eq (org-element-type element) 'fixed-width)
  17787. (progn (goto-char element-end)
  17788. (skip-chars-backward " \r\t\n")
  17789. (forward-line))
  17790. (let ((limit (min end element-end)))
  17791. (while (< (point) limit)
  17792. (org-move-to-column min-ind t)
  17793. (insert ": ")
  17794. (forward-line))))))
  17795. (t
  17796. (org-move-to-column min-ind t)
  17797. (insert ": ")
  17798. (forward-line)))))))
  17799. (set-marker end nil))))
  17800. ;;; Blocks
  17801. (defun org-block-map (function &optional start end)
  17802. "Call FUNCTION at the head of all source blocks in the current buffer.
  17803. Optional arguments START and END can be used to limit the range."
  17804. (let ((start (or start (point-min)))
  17805. (end (or end (point-max))))
  17806. (save-excursion
  17807. (goto-char start)
  17808. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17809. (save-excursion
  17810. (save-match-data
  17811. (goto-char (match-beginning 0))
  17812. (funcall function)))))))
  17813. (defun org-next-block (arg &optional backward block-regexp)
  17814. "Jump to the next block.
  17815. With a prefix argument ARG, jump forward ARG many blocks.
  17816. When BACKWARD is non-nil, jump to the previous block.
  17817. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17818. Match data is set according to this regexp when the function
  17819. returns.
  17820. Return point at beginning of the opening line of found block.
  17821. Throw an error if no block is found."
  17822. (interactive "p")
  17823. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17824. (case-fold-search t)
  17825. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17826. (count (or arg 1))
  17827. (origin (point))
  17828. last-element)
  17829. (if backward (beginning-of-line) (end-of-line))
  17830. (while (and (> count 0) (funcall search-fn re nil t))
  17831. (let ((element (save-excursion
  17832. (goto-char (match-beginning 0))
  17833. (save-match-data (org-element-at-point)))))
  17834. (when (and (memq (org-element-type element)
  17835. '(center-block comment-block dynamic-block
  17836. example-block export-block quote-block
  17837. special-block src-block verse-block))
  17838. (<= (match-beginning 0)
  17839. (org-element-property :post-affiliated element)))
  17840. (setq last-element element)
  17841. (cl-decf count))))
  17842. (if (= count 0)
  17843. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17844. (save-match-data (org-fold-show-context)))
  17845. (goto-char origin)
  17846. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17847. (defun org-previous-block (arg &optional block-regexp)
  17848. "Jump to the previous block.
  17849. With a prefix argument ARG, jump backward ARG many source blocks.
  17850. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17851. (interactive "p")
  17852. (org-next-block arg t block-regexp))
  17853. ;;; Comments
  17854. ;; Org comments syntax is quite complex. It requires the entire line
  17855. ;; to be just a comment. Also, even with the right syntax at the
  17856. ;; beginning of line, some elements (e.g., verse-block or
  17857. ;; example-block) don't accept comments. Usual Emacs comment commands
  17858. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17859. ;; Org still relies on 'comment-dwim', but cannot trust
  17860. ;; 'comment-only-p'. So, 'comment-region-function' and
  17861. ;; 'uncomment-region-function' both point
  17862. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17863. ;; 'org-insert-comment' takes care of insertion of comments at the
  17864. ;; beginning of line.
  17865. ;; 'org-setup-comments-handling' install comments related variables
  17866. ;; during 'org-mode' initialization.
  17867. (defun org-setup-comments-handling ()
  17868. (interactive)
  17869. (setq-local comment-use-syntax nil)
  17870. (setq-local comment-start "# ")
  17871. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17872. (setq-local comment-insert-comment-function 'org-insert-comment)
  17873. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17874. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17875. (defun org-insert-comment ()
  17876. "Insert an empty comment above current line.
  17877. If the line is empty, insert comment at its beginning. When
  17878. point is within a source block, comment according to the related
  17879. major mode."
  17880. (if (let ((element (org-element-at-point)))
  17881. (and (eq (org-element-type element) 'src-block)
  17882. (< (save-excursion
  17883. (goto-char (org-element-property :post-affiliated element))
  17884. (line-end-position))
  17885. (point))
  17886. (> (save-excursion
  17887. (goto-char (org-element-property :end element))
  17888. (skip-chars-backward " \r\t\n")
  17889. (line-beginning-position))
  17890. (point))))
  17891. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17892. (beginning-of-line)
  17893. (if (looking-at "\\s-*$") (delete-region (point) (line-end-position))
  17894. (open-line 1))
  17895. (org-indent-line)
  17896. (insert "# ")))
  17897. (defvar comment-empty-lines) ; From newcomment.el.
  17898. (defun org-comment-or-uncomment-region (beg end &rest _)
  17899. "Comment or uncomment each non-blank line in the region.
  17900. Uncomment each non-blank line between BEG and END if it only
  17901. contains commented lines. Otherwise, comment them. If region is
  17902. strictly within a source block, use appropriate comment syntax."
  17903. (if (let ((element (org-element-at-point)))
  17904. (and (eq (org-element-type element) 'src-block)
  17905. (< (save-excursion
  17906. (goto-char (org-element-property :post-affiliated element))
  17907. (line-end-position))
  17908. beg)
  17909. (>= (save-excursion
  17910. (goto-char (org-element-property :end element))
  17911. (skip-chars-backward " \r\t\n")
  17912. (line-beginning-position))
  17913. end)))
  17914. ;; Translate region boundaries for the Org buffer to the source
  17915. ;; buffer.
  17916. (let ((offset (- end beg)))
  17917. (save-excursion
  17918. (goto-char beg)
  17919. (org-babel-do-in-edit-buffer
  17920. (comment-or-uncomment-region (point) (+ offset (point))))))
  17921. (save-restriction
  17922. ;; Restrict region
  17923. (narrow-to-region (save-excursion (goto-char beg)
  17924. (skip-chars-forward " \r\t\n" end)
  17925. (line-beginning-position))
  17926. (save-excursion (goto-char end)
  17927. (skip-chars-backward " \r\t\n" beg)
  17928. (line-end-position)))
  17929. (let ((uncommentp
  17930. ;; UNCOMMENTP is non-nil when every non blank line between
  17931. ;; BEG and END is a comment.
  17932. (save-excursion
  17933. (goto-char (point-min))
  17934. (while (and (not (eobp))
  17935. (let ((element (org-element-at-point)))
  17936. (and (eq (org-element-type element) 'comment)
  17937. (goto-char (min (point-max)
  17938. (org-element-property
  17939. :end element)))))))
  17940. (eobp))))
  17941. (if uncommentp
  17942. ;; Only blank lines and comments in region: uncomment it.
  17943. (save-excursion
  17944. (goto-char (point-min))
  17945. (while (not (eobp))
  17946. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17947. (replace-match "" nil nil nil 1))
  17948. (forward-line)))
  17949. ;; Comment each line in region.
  17950. (let ((min-indent (point-max)))
  17951. ;; First find the minimum indentation across all lines.
  17952. (save-excursion
  17953. (goto-char (point-min))
  17954. (while (and (not (eobp)) (not (zerop min-indent)))
  17955. (unless (looking-at "[ \t]*$")
  17956. (setq min-indent (min min-indent (current-indentation))))
  17957. (forward-line)))
  17958. ;; Then loop over all lines.
  17959. (save-excursion
  17960. (goto-char (point-min))
  17961. (while (not (eobp))
  17962. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17963. ;; Don't get fooled by invisible text (e.g. link path)
  17964. ;; when moving to column MIN-INDENT.
  17965. (let ((buffer-invisibility-spec nil))
  17966. (org-move-to-column min-indent t))
  17967. (insert comment-start))
  17968. (forward-line)))))))))
  17969. (defun org-comment-dwim (_arg)
  17970. "Call the comment command you mean.
  17971. Call `org-toggle-comment' if on a heading, otherwise call
  17972. `comment-dwim', within a source edit buffer if needed."
  17973. (interactive "*P")
  17974. (cond ((org-at-heading-p)
  17975. (call-interactively #'org-toggle-comment))
  17976. ((org-in-src-block-p)
  17977. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17978. (t (call-interactively #'comment-dwim))))
  17979. ;;; Timestamps API
  17980. ;; This section contains tools to operate on, or create, timestamp
  17981. ;; objects, as returned by, e.g. `org-element-context'.
  17982. (defun org-timestamp-from-string (s)
  17983. "Convert Org timestamp S, as a string, into a timestamp object.
  17984. Return nil if S is not a valid timestamp string."
  17985. (when (org-string-nw-p s)
  17986. (with-temp-buffer
  17987. (save-excursion (insert s))
  17988. (org-element-timestamp-parser))))
  17989. (defun org-timestamp-from-time (time &optional with-time inactive)
  17990. "Convert a time value into a timestamp object.
  17991. TIME is an Emacs internal time representation, as returned, e.g.,
  17992. by `current-time'.
  17993. When optional argument WITH-TIME is non-nil, return a timestamp
  17994. object with a time part, i.e., with hours and minutes.
  17995. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17996. return an active timestamp."
  17997. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17998. (org-element-create 'timestamp
  17999. (list :type (if inactive 'inactive 'active)
  18000. :year-start year
  18001. :month-start month
  18002. :day-start day
  18003. :hour-start (and with-time hour)
  18004. :minute-start (and with-time minute)))))
  18005. (defun org-timestamp-to-time (timestamp &optional end)
  18006. "Convert TIMESTAMP object into an Emacs internal time value.
  18007. Use end of date range or time range when END is non-nil.
  18008. Otherwise, use its start."
  18009. (org-encode-time
  18010. (append '(0)
  18011. (mapcar
  18012. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18013. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18014. '(:minute-start :hour-start :day-start :month-start
  18015. :year-start)))
  18016. '(nil -1 nil))))
  18017. (defun org-timestamp-has-time-p (timestamp)
  18018. "Non-nil when TIMESTAMP has a time specified."
  18019. (org-element-property :hour-start timestamp))
  18020. (defun org-timestamp-format (timestamp format &optional end utc)
  18021. "Format a TIMESTAMP object into a string.
  18022. FORMAT is a format specifier to be passed to
  18023. `format-time-string'.
  18024. When optional argument END is non-nil, use end of date-range or
  18025. time-range, if possible.
  18026. When optional argument UTC is non-nil, time is be expressed as
  18027. Universal Time."
  18028. (format-time-string format (org-timestamp-to-time timestamp end)
  18029. (and utc t)))
  18030. (defun org-timestamp-split-range (timestamp &optional end)
  18031. "Extract a TIMESTAMP object from a date or time range.
  18032. END, when non-nil, means extract the end of the range.
  18033. Otherwise, extract its start.
  18034. Return a new timestamp object."
  18035. (let ((type (org-element-property :type timestamp)))
  18036. (if (memq type '(active inactive diary)) timestamp
  18037. (let ((split-ts (org-element-copy timestamp)))
  18038. ;; Set new type.
  18039. (org-element-put-property
  18040. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18041. ;; Copy start properties over end properties if END is
  18042. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18043. (let ((p-alist '((:minute-start . :minute-end)
  18044. (:hour-start . :hour-end)
  18045. (:day-start . :day-end)
  18046. (:month-start . :month-end)
  18047. (:year-start . :year-end))))
  18048. (dolist (p-cell p-alist)
  18049. (org-element-put-property
  18050. split-ts
  18051. (funcall (if end #'car #'cdr) p-cell)
  18052. (org-element-property
  18053. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18054. ;; Eventually refresh `:raw-value'.
  18055. (org-element-put-property split-ts :raw-value nil)
  18056. (org-element-put-property
  18057. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18058. (defun org-timestamp-translate (timestamp &optional boundary)
  18059. "Translate TIMESTAMP object to custom format.
  18060. Format string is defined in `org-time-stamp-custom-formats',
  18061. which see.
  18062. When optional argument BOUNDARY is non-nil, it is either the
  18063. symbol `start' or `end'. In this case, only translate the
  18064. starting or ending part of TIMESTAMP if it is a date or time
  18065. range. Otherwise, translate both parts.
  18066. Return timestamp as-is if `org-display-custom-times' is nil or if
  18067. it has a `diary' type."
  18068. (let ((type (org-element-property :type timestamp)))
  18069. (if (or (not org-display-custom-times) (eq type 'diary))
  18070. (org-element-interpret-data timestamp)
  18071. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18072. org-time-stamp-custom-formats)))
  18073. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18074. (concat (org-timestamp-format timestamp fmt)
  18075. "--"
  18076. (org-timestamp-format timestamp fmt t))
  18077. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18078. ;;; Other stuff
  18079. (defvar reftex-docstruct-symbol)
  18080. (defvar org--rds)
  18081. (defun org-reftex-citation ()
  18082. "Use `reftex-citation' to insert a citation into the buffer.
  18083. This looks for a line like
  18084. #+BIBLIOGRAPHY: foo plain option:-d
  18085. and derives from it that foo.bib is the bibliography file relevant
  18086. for this document. It then installs the necessary environment for RefTeX
  18087. to work in this buffer and calls `reftex-citation' to insert a citation
  18088. into the buffer.
  18089. Export of such citations to both LaTeX and HTML is handled by the contributed
  18090. package ox-bibtex by Taru Karttunen."
  18091. (interactive)
  18092. (let ((reftex-docstruct-symbol 'org--rds)
  18093. org--rds bib)
  18094. (org-with-wide-buffer
  18095. (let ((case-fold-search t)
  18096. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18097. (if (not (save-excursion
  18098. (or (re-search-forward re nil t)
  18099. (re-search-backward re nil t))))
  18100. (user-error "No bibliography defined in file")
  18101. (setq bib (concat (match-string 1) ".bib")
  18102. org--rds (list (list 'bib bib))))))
  18103. (call-interactively 'reftex-citation)))
  18104. ;;;; Functions extending outline functionality
  18105. (defun org-beginning-of-line (&optional n)
  18106. "Go to the beginning of the current visible line.
  18107. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18108. symbol `reversed', on the first attempt move to where the
  18109. headline text starts, and only move to beginning of line when the
  18110. cursor is already before the start of the text of the headline.
  18111. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18112. start of the text on the second attempt.
  18113. With argument N not nil or 1, move forward N - 1 lines first."
  18114. (interactive "^p")
  18115. (let ((origin (point))
  18116. (special (pcase org-special-ctrl-a/e
  18117. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18118. deactivate-mark)
  18119. ;; First move to a visible line.
  18120. (if (bound-and-true-p visual-line-mode)
  18121. (beginning-of-visual-line n)
  18122. (move-beginning-of-line n)
  18123. ;; `move-beginning-of-line' may leave point after invisible
  18124. ;; characters if line starts with such of these (e.g., with
  18125. ;; a link at column 0). Really move to the beginning of the
  18126. ;; current visible line.
  18127. (beginning-of-line))
  18128. (cond
  18129. ;; No special behavior. Point is already at the beginning of
  18130. ;; a line, logical or visual.
  18131. ((not special))
  18132. ;; `beginning-of-visual-line' left point before logical beginning
  18133. ;; of line: point is at the beginning of a visual line. Bail
  18134. ;; out.
  18135. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18136. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18137. ;; At a headline, special position is before the title, but
  18138. ;; after any TODO keyword or priority cookie.
  18139. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18140. (line-end-position)))
  18141. (bol (point)))
  18142. (if (eq special 'reversed)
  18143. (when (and (= origin bol) (eq last-command this-command))
  18144. (goto-char refpos))
  18145. (when (or (> origin refpos) (= origin bol))
  18146. (goto-char refpos)))))
  18147. ((and (looking-at org-list-full-item-re)
  18148. (memq (org-element-type (save-match-data (org-element-at-point)))
  18149. '(item plain-list)))
  18150. ;; Set special position at first white space character after
  18151. ;; bullet, and check-box, if any.
  18152. (let ((after-bullet
  18153. (let ((box (match-end 3)))
  18154. (cond ((not box) (match-end 1))
  18155. ((eq (char-after box) ?\s) (1+ box))
  18156. (t box)))))
  18157. (if (eq special 'reversed)
  18158. (when (and (= (point) origin) (eq last-command this-command))
  18159. (goto-char after-bullet))
  18160. (when (or (> origin after-bullet) (= (point) origin))
  18161. (goto-char after-bullet)))))
  18162. ;; No special context. Point is already at beginning of line.
  18163. (t nil))))
  18164. (defun org-end-of-line (&optional n)
  18165. "Go to the end of the line, but before ellipsis, if any.
  18166. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18167. symbol `reversed', ignore tags on the first attempt, and only
  18168. move to after the tags when the cursor is already beyond the end
  18169. of the headline.
  18170. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18171. on the second attempt.
  18172. With argument N not nil or 1, move forward N - 1 lines first."
  18173. (interactive "^p")
  18174. (let ((origin (point))
  18175. (special (pcase org-special-ctrl-a/e
  18176. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18177. deactivate-mark)
  18178. ;; First move to a visible line.
  18179. (if (bound-and-true-p visual-line-mode)
  18180. (beginning-of-visual-line n)
  18181. (move-beginning-of-line n))
  18182. (cond
  18183. ;; At a headline, with tags.
  18184. ((and special
  18185. (save-excursion
  18186. (beginning-of-line)
  18187. (let ((case-fold-search nil))
  18188. (looking-at org-complex-heading-regexp)))
  18189. (match-end 5))
  18190. (let ((tags (save-excursion
  18191. (goto-char (match-beginning 5))
  18192. (skip-chars-backward " \t")
  18193. (point)))
  18194. (visual-end (and (bound-and-true-p visual-line-mode)
  18195. (save-excursion
  18196. (end-of-visual-line)
  18197. (point)))))
  18198. ;; If `end-of-visual-line' brings us before end of line or
  18199. ;; even tags, i.e., the headline spans over multiple visual
  18200. ;; lines, move there.
  18201. (cond ((and visual-end
  18202. (< visual-end tags)
  18203. (<= origin visual-end))
  18204. (goto-char visual-end))
  18205. ((eq special 'reversed)
  18206. (if (and (= origin (line-end-position))
  18207. (eq this-command last-command))
  18208. (goto-char tags)
  18209. (end-of-line)))
  18210. (t
  18211. (if (or (< origin tags) (= origin (line-end-position)))
  18212. (goto-char tags)
  18213. (end-of-line))))))
  18214. ((bound-and-true-p visual-line-mode)
  18215. (let ((bol (line-beginning-position)))
  18216. (end-of-visual-line)
  18217. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18218. ;; end of a line, backtrack and use `end-of-line' instead.
  18219. (when (/= bol (line-beginning-position))
  18220. (goto-char bol)
  18221. (end-of-line))))
  18222. (t (end-of-line)))))
  18223. (defun org-backward-sentence (&optional _arg)
  18224. "Go to beginning of sentence, or beginning of table field.
  18225. This will call `backward-sentence' or `org-table-beginning-of-field',
  18226. depending on context."
  18227. (interactive)
  18228. (let* ((element (org-element-at-point))
  18229. (contents-begin (org-element-property :contents-begin element))
  18230. (table (org-element-lineage element '(table) t)))
  18231. (if (and table
  18232. (> (point) contents-begin)
  18233. (<= (point) (org-element-property :contents-end table)))
  18234. (call-interactively #'org-table-beginning-of-field)
  18235. (save-restriction
  18236. (when (and contents-begin
  18237. (< (point-min) contents-begin)
  18238. (> (point) contents-begin))
  18239. (narrow-to-region contents-begin
  18240. (org-element-property :contents-end element)))
  18241. (call-interactively #'backward-sentence)))))
  18242. (defun org-forward-sentence (&optional _arg)
  18243. "Go to end of sentence, or end of table field.
  18244. This will call `forward-sentence' or `org-table-end-of-field',
  18245. depending on context."
  18246. (interactive)
  18247. (if (and (org-at-heading-p)
  18248. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18249. (save-restriction
  18250. (narrow-to-region (line-beginning-position) (line-end-position))
  18251. (call-interactively #'forward-sentence))
  18252. (let* ((element (org-element-at-point))
  18253. (contents-end (org-element-property :contents-end element))
  18254. (table (org-element-lineage element '(table) t)))
  18255. (if (and table
  18256. (>= (point) (org-element-property :contents-begin table))
  18257. (< (point) contents-end))
  18258. (call-interactively #'org-table-end-of-field)
  18259. (save-restriction
  18260. (when (and contents-end
  18261. (> (point-max) contents-end)
  18262. ;; Skip blank lines between elements.
  18263. (< (org-element-property :end element)
  18264. (save-excursion (goto-char contents-end)
  18265. (skip-chars-forward " \r\t\n"))))
  18266. (narrow-to-region (org-element-property :contents-begin element)
  18267. contents-end))
  18268. ;; End of heading is considered as the end of a sentence.
  18269. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18270. (call-interactively #'forward-sentence)))))))
  18271. (defun org-kill-line (&optional _arg)
  18272. "Kill line, to tags or end of line."
  18273. (interactive)
  18274. (cond
  18275. ((or (not org-special-ctrl-k)
  18276. (bolp)
  18277. (not (org-at-heading-p)))
  18278. (when (and (org-invisible-p (line-end-position))
  18279. org-ctrl-k-protect-subtree
  18280. (or (eq org-ctrl-k-protect-subtree 'error)
  18281. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18282. (user-error
  18283. (substitute-command-keys
  18284. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18285. (call-interactively
  18286. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18287. ((org-match-line org-tag-line-re)
  18288. (let ((end (save-excursion
  18289. (goto-char (match-beginning 1))
  18290. (skip-chars-backward " \t")
  18291. (point))))
  18292. (if (<= end (point)) ;on tags part
  18293. (kill-region (point) (line-end-position))
  18294. (kill-region (point) end)))
  18295. ;; Only align tags when we are still on a heading:
  18296. (if (org-at-heading-p) (org-align-tags)))
  18297. (t (kill-region (point) (line-end-position)))))
  18298. (defun org-yank (&optional arg)
  18299. "Yank. If the kill is a subtree, treat it specially.
  18300. This command will look at the current kill and check if is a single
  18301. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18302. cursor is at the beginning of a line or after the stars of a currently
  18303. empty headline, then the yank is handled specially. How exactly depends
  18304. on the value of the following variables.
  18305. `org-yank-folded-subtrees'
  18306. By default, this variable is non-nil, which results in
  18307. subtree(s) being folded after insertion, except if doing so
  18308. would swallow text after the yanked text.
  18309. `org-yank-adjusted-subtrees'
  18310. When non-nil (the default value is nil), the subtree will be
  18311. promoted or demoted in order to fit into the local outline tree
  18312. structure, which means that the level will be adjusted so that it
  18313. becomes the smaller one of the two *visible* surrounding headings.
  18314. Any prefix to this command will cause `yank' to be called directly with
  18315. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18316. will just
  18317. plainly yank the text as it is.
  18318. \[1] The test checks if the first non-white line is a heading
  18319. and if there are no other headings with fewer stars."
  18320. (interactive "P")
  18321. (org-yank-generic 'yank arg))
  18322. (defun org-yank-generic (command arg)
  18323. "Perform some yank-like command.
  18324. This function implements the behavior described in the `org-yank'
  18325. documentation. However, it has been generalized to work for any
  18326. interactive command with similar behavior."
  18327. ;; pretend to be command COMMAND
  18328. (setq this-command command)
  18329. (if arg
  18330. (call-interactively command)
  18331. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18332. (and (org-kill-is-subtree-p)
  18333. (or (bolp)
  18334. (and (looking-at "[ \t]*$")
  18335. (string-match
  18336. "\\`\\*+\\'"
  18337. (buffer-substring (line-beginning-position) (point)))))))
  18338. swallowp)
  18339. (cond
  18340. ((and subtreep org-yank-folded-subtrees)
  18341. (let ((beg (point))
  18342. end)
  18343. (if (and subtreep org-yank-adjusted-subtrees)
  18344. (org-paste-subtree nil nil 'for-yank)
  18345. (call-interactively command))
  18346. (setq end (point))
  18347. (goto-char beg)
  18348. (when (and (bolp) subtreep
  18349. (not (setq swallowp
  18350. (org-yank-folding-would-swallow-text beg end))))
  18351. (org-with-limited-levels
  18352. (or (looking-at org-outline-regexp)
  18353. (re-search-forward org-outline-regexp-bol end t))
  18354. (while (and (< (point) end) (looking-at org-outline-regexp))
  18355. (org-fold-subtree t)
  18356. (org-cycle-show-empty-lines 'folded)
  18357. (condition-case nil
  18358. (outline-forward-same-level 1)
  18359. (error (goto-char end))))))
  18360. (when swallowp
  18361. (message
  18362. "Inserted text not folded because that would swallow text"))
  18363. (goto-char end)
  18364. (skip-chars-forward " \t\n\r")
  18365. (beginning-of-line 1)
  18366. (push-mark beg 'nomsg)))
  18367. ((and subtreep org-yank-adjusted-subtrees)
  18368. (let ((beg (line-beginning-position)))
  18369. (org-paste-subtree nil nil 'for-yank)
  18370. (push-mark beg 'nomsg)))
  18371. (t
  18372. (call-interactively command))))))
  18373. (defun org-yank-folding-would-swallow-text (beg end)
  18374. "Would `hide-subtree' at BEG swallow any text after END?"
  18375. (let (level)
  18376. (org-with-limited-levels
  18377. (save-excursion
  18378. (goto-char beg)
  18379. (when (or (looking-at org-outline-regexp)
  18380. (re-search-forward org-outline-regexp-bol end t))
  18381. (setq level (org-outline-level)))
  18382. (goto-char end)
  18383. (skip-chars-forward " \t\r\n\v\f")
  18384. (not (or (eobp)
  18385. (and (bolp) (looking-at-p org-outline-regexp)
  18386. (<= (org-outline-level) level))))))))
  18387. (defun org-back-to-heading (&optional invisible-ok)
  18388. "Go back to beginning of heading."
  18389. (beginning-of-line)
  18390. (or (org-at-heading-p (not invisible-ok))
  18391. (if (org-element--cache-active-p)
  18392. (let ((heading (org-element-lineage (org-element-at-point)
  18393. '(headline inlinetask)
  18394. 'include-self)))
  18395. (when heading
  18396. (goto-char (org-element-property :begin heading)))
  18397. (while (and (not invisible-ok)
  18398. heading
  18399. (org-fold-folded-p))
  18400. (goto-char (org-fold-core-previous-visibility-change))
  18401. (setq heading (org-element-lineage (org-element-at-point)
  18402. '(headline inlinetask)
  18403. 'include-self))
  18404. (when heading
  18405. (goto-char (org-element-property :begin heading))))
  18406. (unless heading
  18407. (user-error "Before first headline at position %d in buffer %s"
  18408. (point) (current-buffer)))
  18409. (point))
  18410. (let (found)
  18411. (save-excursion
  18412. ;; At inlinetask end. Move to bol, so that the following
  18413. ;; search goes to the beginning of the inlinetask.
  18414. (when (and (featurep 'org-inlinetask)
  18415. (fboundp 'org-inlinetask-end-p)
  18416. (org-inlinetask-end-p))
  18417. (goto-char (line-beginning-position)))
  18418. (while (not found)
  18419. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18420. nil t)
  18421. (user-error "Before first headline at position %d in buffer %s"
  18422. (point) (current-buffer)))
  18423. ;; Skip inlinetask end.
  18424. (if (and (featurep 'org-inlinetask)
  18425. (fboundp 'org-inlinetask-end-p)
  18426. (org-inlinetask-end-p))
  18427. (org-inlinetask-goto-beginning)
  18428. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18429. (point))))))
  18430. (goto-char found)
  18431. found))))
  18432. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18433. "Go back to heading or first point in buffer.
  18434. If point is before first heading go to first point in buffer
  18435. instead of back to heading."
  18436. (if (org-before-first-heading-p)
  18437. (goto-char (point-min))
  18438. (org-back-to-heading invisible-ok)))
  18439. (defun org-before-first-heading-p ()
  18440. "Before first heading?
  18441. Respect narrowing."
  18442. (let ((cached (org-element-at-point nil 'cached)))
  18443. (if cached
  18444. (let ((cached-headline (org-element-lineage cached '(headline) t)))
  18445. (or (not cached-headline)
  18446. (< (org-element-property :begin cached-headline) (point-min))))
  18447. (org-with-limited-levels
  18448. (save-excursion
  18449. (end-of-line)
  18450. (null (re-search-backward org-outline-regexp-bol nil t)))))))
  18451. (defun org-at-heading-p (&optional invisible-not-ok)
  18452. "Return t if point is on a (possibly invisible) heading line.
  18453. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18454. (save-excursion
  18455. (beginning-of-line)
  18456. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18457. (looking-at outline-regexp))))
  18458. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18459. "Non-nil if point is under a commented heading.
  18460. This function also checks ancestors of the current headline,
  18461. unless optional argument NO-INHERITANCE is non-nil.
  18462. Optional argument ELEMENT contains element at point."
  18463. (save-match-data
  18464. (let ((el (or element
  18465. (org-element-at-point nil 'cached)
  18466. (org-with-wide-buffer
  18467. (org-back-to-heading-or-point-min t)
  18468. (org-element-at-point)))))
  18469. (catch :found
  18470. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18471. (if no-inheritance
  18472. (org-element-property :commentedp el)
  18473. (while el
  18474. (when (org-element-property :commentedp el)
  18475. (throw :found t))
  18476. (setq el (org-element-property :parent el))))))))
  18477. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18478. "Non-nil if point is under an archived heading.
  18479. This function also checks ancestors of the current headline,
  18480. unless optional argument NO-INHERITANCE is non-nil.
  18481. Optional argument ELEMENT contains element at point."
  18482. (cond
  18483. ((and (not element) (org-before-first-heading-p)) nil)
  18484. ((if element
  18485. (org-element-property :archivedp element)
  18486. (let ((tags (org-get-tags element 'local)))
  18487. (and tags
  18488. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18489. (no-inheritance nil)
  18490. (t
  18491. (if (or element (org-element--cache-active-p))
  18492. (catch :archived
  18493. (unless element (setq element (org-element-at-point)))
  18494. (while element
  18495. (when (org-element-property :archivedp element)
  18496. (throw :archived t))
  18497. (setq element (org-element-property :parent element))))
  18498. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18499. (defun org-at-comment-p nil
  18500. "Return t if cursor is in a commented line."
  18501. (save-excursion
  18502. (save-match-data
  18503. (beginning-of-line)
  18504. (looking-at org-comment-regexp))))
  18505. (defun org-at-keyword-p nil
  18506. "Return t if cursor is at a keyword-line."
  18507. (save-excursion
  18508. (move-beginning-of-line 1)
  18509. (looking-at org-keyword-regexp)))
  18510. (defun org-at-drawer-p nil
  18511. "Return t if cursor is at a drawer keyword."
  18512. (save-excursion
  18513. (move-beginning-of-line 1)
  18514. (looking-at org-drawer-regexp)))
  18515. (defun org-at-block-p nil
  18516. "Return t if cursor is at a block keyword."
  18517. (save-excursion
  18518. (move-beginning-of-line 1)
  18519. (looking-at org-block-regexp)))
  18520. (defun org-point-at-end-of-empty-headline ()
  18521. "If point is at the end of an empty headline, return t, else nil.
  18522. If the heading only contains a TODO keyword, it is still considered
  18523. empty."
  18524. (let ((case-fold-search nil))
  18525. (and (looking-at "[ \t]*$")
  18526. org-todo-line-regexp
  18527. (save-excursion
  18528. (beginning-of-line)
  18529. (looking-at org-todo-line-regexp)
  18530. (string= (match-string 3) "")))))
  18531. (defun org-at-heading-or-item-p ()
  18532. (or (org-at-heading-p) (org-at-item-p)))
  18533. (defun org-up-heading-all (arg)
  18534. "Move to the heading line of which the present line is a subheading.
  18535. This function considers both visible and invisible heading lines.
  18536. With argument, move up ARG levels."
  18537. (outline-up-heading arg t))
  18538. (defvar-local org--up-heading-cache nil
  18539. "Buffer-local `org-up-heading-safe' cache.")
  18540. (defvar-local org--up-heading-cache-tick nil
  18541. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18542. (defun org-up-heading-safe ()
  18543. "Move to the heading line of which the present line is a subheading.
  18544. This version will not throw an error. It will return the level of the
  18545. headline found, or nil if no higher level is found.
  18546. Also, this function will be a lot faster than `outline-up-heading',
  18547. because it relies on stars being the outline starters. This can really
  18548. make a significant difference in outlines with very many siblings."
  18549. (let ((element (and (org-element--cache-active-p)
  18550. (org-element-at-point nil t))))
  18551. (if element
  18552. (let* ((current-heading (org-element-lineage element '(headline inlinetask) 'with-self))
  18553. (parent (org-element-lineage current-heading '(headline))))
  18554. (if (and parent
  18555. (<= (point-min) (org-element-property :begin parent)))
  18556. (progn
  18557. (goto-char (org-element-property :begin parent))
  18558. (org-element-property :level parent))
  18559. (when (and current-heading
  18560. (<= (point-min) (org-element-property :begin current-heading)))
  18561. (goto-char (org-element-property :begin current-heading))
  18562. nil)))
  18563. (when (ignore-errors (org-back-to-heading t))
  18564. (let (level-cache)
  18565. (unless org--up-heading-cache
  18566. (setq org--up-heading-cache (make-hash-table)))
  18567. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18568. (setq level-cache (gethash (point) org--up-heading-cache)))
  18569. (when (<= (point-min) (car level-cache) (point-max))
  18570. ;; Parent is inside accessible part of the buffer.
  18571. (progn (goto-char (car level-cache))
  18572. (cdr level-cache)))
  18573. ;; Buffer modified. Invalidate cache.
  18574. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18575. (setq-local org--up-heading-cache-tick
  18576. (buffer-chars-modified-tick))
  18577. (clrhash org--up-heading-cache))
  18578. (let* ((level-up (1- (funcall outline-level)))
  18579. (pos (point))
  18580. (result (and (> level-up 0)
  18581. (re-search-backward
  18582. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18583. (funcall outline-level))))
  18584. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18585. result)))))))
  18586. (defun org-up-heading-or-point-min ()
  18587. "Move to the heading line of which the present is a subheading, or point-min.
  18588. This version is needed to make point-min behave like a virtual
  18589. heading of level 0 for property-inheritance. It will return the
  18590. level of the headline found (down to 0) or nil if already at a
  18591. point before the first headline or at point-min."
  18592. (when (ignore-errors (org-back-to-heading t))
  18593. (if (< 1 (funcall outline-level))
  18594. (or (org-up-heading-safe)
  18595. ;; The first heading may not be level 1 heading.
  18596. (goto-char (point-min)))
  18597. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18598. (defun org-first-sibling-p ()
  18599. "Is this heading the first child of its parents?"
  18600. (interactive)
  18601. (let ((re org-outline-regexp-bol)
  18602. level l)
  18603. (unless (org-at-heading-p t)
  18604. (user-error "Not at a heading"))
  18605. (setq level (funcall outline-level))
  18606. (save-excursion
  18607. (if (not (re-search-backward re nil t))
  18608. t
  18609. (setq l (funcall outline-level))
  18610. (< l level)))))
  18611. (defun org-goto-sibling (&optional previous)
  18612. "Goto the next sibling, even if it is invisible.
  18613. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18614. when a sibling was found. When none is found, return nil and don't
  18615. move point."
  18616. (let ((fun (if previous 're-search-backward 're-search-forward))
  18617. (pos (point))
  18618. (re org-outline-regexp-bol)
  18619. level l)
  18620. (when (ignore-errors (org-back-to-heading t))
  18621. (setq level (funcall outline-level))
  18622. (catch 'exit
  18623. (or previous (forward-char 1))
  18624. (while (funcall fun re nil t)
  18625. (setq l (funcall outline-level))
  18626. (when (< l level) (goto-char pos) (throw 'exit nil))
  18627. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18628. (goto-char pos)
  18629. nil))))
  18630. (defun org-goto-first-child (&optional element)
  18631. "Goto the first child, even if it is invisible.
  18632. Return t when a child was found. Otherwise don't move point and
  18633. return nil."
  18634. (if (org-element--cache-active-p)
  18635. (let ((heading (org-element-lineage
  18636. (or element (org-element-at-point))
  18637. '(headline inlinetask org-data)
  18638. t)))
  18639. (when heading
  18640. (unless (or (eq 'inlinetask (org-element-type heading))
  18641. (not (org-element-property :contents-begin heading)))
  18642. (let ((pos (point)))
  18643. (goto-char (org-element-property :contents-begin heading))
  18644. (if (re-search-forward
  18645. org-outline-regexp-bol
  18646. (org-element-property :end heading)
  18647. t)
  18648. (progn (goto-char (match-beginning 0)) t)
  18649. (goto-char pos) nil)))))
  18650. (let (level (pos (point)) (re org-outline-regexp-bol))
  18651. (when (org-back-to-heading-or-point-min t)
  18652. (setq level (org-outline-level))
  18653. (forward-char 1)
  18654. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18655. (progn (goto-char (match-beginning 0)) t)
  18656. (goto-char pos) nil)))))
  18657. (defun org-get-next-sibling ()
  18658. "Move to next heading of the same level, and return point.
  18659. If there is no such heading, return nil.
  18660. This is like outline-next-sibling, but invisible headings are ok."
  18661. (let ((level (funcall outline-level)))
  18662. (outline-next-heading)
  18663. (while (and (not (eobp)) (> (funcall outline-level) level))
  18664. (outline-next-heading))
  18665. (unless (or (eobp) (< (funcall outline-level) level))
  18666. (point))))
  18667. (defun org-get-previous-sibling ()
  18668. "Move to previous heading of the same level, and return point.
  18669. If there is no such heading, return nil."
  18670. (let ((opoint (point))
  18671. (level (funcall outline-level)))
  18672. (outline-previous-heading)
  18673. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18674. (while (and (> (funcall outline-level) level)
  18675. (not (bobp)))
  18676. (outline-previous-heading))
  18677. (unless (< (funcall outline-level) level)
  18678. (point)))))
  18679. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18680. "Goto to the end of a subtree at point or for ELEMENT heading."
  18681. ;; This contains an exact copy of the original function, but it uses
  18682. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18683. ;; trees and before first headline. And is uses an invisible-ok argument.
  18684. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18685. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18686. ;; with many children and grandchildren etc, this can be much faster
  18687. ;; than the outline version.
  18688. (if element
  18689. (setq element (org-element-lineage element '(headline inlinetask) 'include-self))
  18690. (org-back-to-heading-or-point-min invisible-ok))
  18691. (unless (and (org-element--cache-active-p)
  18692. (let ((cached (or element (org-element-at-point nil t))))
  18693. (and cached
  18694. (eq 'headline (org-element-type cached))
  18695. (goto-char (org-element-property
  18696. :end cached)))))
  18697. (let ((first t)
  18698. (level (funcall outline-level)))
  18699. (cond ((= level 0)
  18700. (goto-char (point-max)))
  18701. ((and (derived-mode-p 'org-mode) (< level 1000))
  18702. ;; A true heading (not a plain list item), in Org
  18703. ;; This means we can easily find the end by looking
  18704. ;; only for the right number of stars. Using a regexp to do
  18705. ;; this is so much faster than using a Lisp loop.
  18706. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18707. (forward-char 1)
  18708. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18709. (t
  18710. ;; something else, do it the slow way
  18711. (while (and (not (eobp))
  18712. (or first (> (funcall outline-level) level)))
  18713. (setq first nil)
  18714. (outline-next-heading))))))
  18715. (unless to-heading
  18716. (when (memq (preceding-char) '(?\n ?\^M))
  18717. ;; Go to end of line before heading
  18718. (forward-char -1)
  18719. (when (memq (preceding-char) '(?\n ?\^M))
  18720. ;; leave blank line before heading
  18721. (forward-char -1))))
  18722. (point))
  18723. (defun org-end-of-meta-data (&optional full)
  18724. "Skip planning line and properties drawer in current entry.
  18725. When optional argument FULL is t, also skip planning information,
  18726. clocking lines and any kind of drawer.
  18727. When FULL is non-nil but not t, skip planning information,
  18728. properties, clocking lines and logbook drawers."
  18729. (org-back-to-heading t)
  18730. (forward-line)
  18731. ;; Skip planning information.
  18732. (when (looking-at-p org-planning-line-re) (forward-line))
  18733. ;; Skip property drawer.
  18734. (when (looking-at org-property-drawer-re)
  18735. (goto-char (match-end 0))
  18736. (forward-line))
  18737. ;; When FULL is not nil, skip more.
  18738. (when (and full (not (org-at-heading-p)))
  18739. (catch 'exit
  18740. (let ((end (save-excursion (outline-next-heading) (point)))
  18741. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18742. (while (not (eobp))
  18743. (cond ;; Skip clock lines.
  18744. ((looking-at-p re) (forward-line))
  18745. ;; Skip logbook drawer.
  18746. ((looking-at-p org-logbook-drawer-re)
  18747. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18748. (forward-line)
  18749. (throw 'exit t)))
  18750. ;; When FULL is t, skip regular drawer too.
  18751. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18752. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18753. (forward-line)
  18754. (throw 'exit t)))
  18755. (t (throw 'exit t))))))))
  18756. (defun org--line-fully-invisible-p ()
  18757. "Return non-nil if the current line is fully invisible."
  18758. (let ((line-beg (line-beginning-position))
  18759. (line-pos (1- (line-end-position)))
  18760. (is-invisible t))
  18761. (while (and (< line-beg line-pos) is-invisible)
  18762. (setq is-invisible (org-invisible-p line-pos))
  18763. (setq line-pos (1- line-pos)))
  18764. is-invisible))
  18765. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18766. "Move forward to the ARG'th subheading at same level as this one.
  18767. Stop at the first and last subheadings of a superior heading.
  18768. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18769. non-nil it will also look at invisible ones."
  18770. (interactive "p")
  18771. (let ((backward? (and arg (< arg 0))))
  18772. (if (org-before-first-heading-p)
  18773. (if backward? (goto-char (point-min)) (outline-next-heading))
  18774. (org-back-to-heading invisible-ok)
  18775. (unless backward? (end-of-line)) ;do not match current headline
  18776. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18777. (f (if backward? #'re-search-backward #'re-search-forward))
  18778. (count (if arg (abs arg) 1))
  18779. (result (point)))
  18780. (while (and (> count 0)
  18781. (funcall f org-outline-regexp-bol nil 'move))
  18782. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18783. (cond ((< l level) (setq count 0))
  18784. ((and (= l level)
  18785. (or invisible-ok
  18786. ;; FIXME: See commit a700fadd72 and the
  18787. ;; related discussion on why using
  18788. ;; `org--line-fully-invisible-p' is needed
  18789. ;; here, which is to serve the needs of an
  18790. ;; external package. If the change is
  18791. ;; wrong regarding Org itself, it should
  18792. ;; be removed.
  18793. (not (org--line-fully-invisible-p))))
  18794. (cl-decf count)
  18795. (when (= l level) (setq result (point)))))))
  18796. (goto-char result))
  18797. (beginning-of-line))))
  18798. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18799. "Move backward to the ARG'th subheading at same level as this one.
  18800. Stop at the first and last subheadings of a superior heading."
  18801. (interactive "p")
  18802. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18803. (defun org-next-visible-heading (arg)
  18804. "Move to the next visible heading line.
  18805. With ARG, repeats or can move backward if negative."
  18806. (interactive "p")
  18807. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18808. (if (< arg 0)
  18809. (beginning-of-line)
  18810. (end-of-line))
  18811. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18812. (unless (bobp)
  18813. (when (org-fold-folded-p)
  18814. (goto-char (org-fold-previous-visibility-change))
  18815. (unless (looking-at-p regexp)
  18816. (re-search-backward regexp nil :mode))))
  18817. (cl-incf arg))
  18818. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18819. (when (org-fold-folded-p)
  18820. (goto-char (org-fold-next-visibility-change))
  18821. (skip-chars-forward " \t\n")
  18822. (end-of-line))
  18823. (cl-decf arg))
  18824. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18825. (defun org-previous-visible-heading (arg)
  18826. "Move to the previous visible heading.
  18827. With ARG, repeats or can move forward if negative."
  18828. (interactive "p")
  18829. (org-next-visible-heading (- arg)))
  18830. (defun org-forward-paragraph (&optional arg)
  18831. "Move forward by a paragraph, or equivalent, unit.
  18832. With argument ARG, do it ARG times;
  18833. a negative argument ARG = -N means move backward N paragraphs.
  18834. The function moves point between two structural
  18835. elements (paragraphs, tables, lists, etc.).
  18836. It also provides the following special moves for convenience:
  18837. - on a table or a property drawer, move to its beginning;
  18838. - on comment, example, export, source and verse blocks, stop
  18839. at blank lines;
  18840. - skip consecutive clocks, diary S-exps, and keywords."
  18841. (interactive "^p")
  18842. (unless arg (setq arg 1))
  18843. (if (< arg 0) (org-backward-paragraph (- arg))
  18844. (while (and (> arg 0) (not (eobp)))
  18845. (org--forward-paragraph-once)
  18846. (cl-decf arg))
  18847. ;; Return moves left.
  18848. arg))
  18849. (defun org-backward-paragraph (&optional arg)
  18850. "Move backward by a paragraph, or equivalent, unit.
  18851. With argument ARG, do it ARG times;
  18852. a negative argument ARG = -N means move forward N paragraphs.
  18853. The function moves point between two structural
  18854. elements (paragraphs, tables, lists, etc.).
  18855. It also provides the following special moves for convenience:
  18856. - on a table or a property drawer, move to its beginning;
  18857. - on comment, example, export, source and verse blocks, stop
  18858. at blank lines;
  18859. - skip consecutive clocks, diary S-exps, and keywords."
  18860. (interactive "^p")
  18861. (unless arg (setq arg 1))
  18862. (if (< arg 0) (org-forward-paragraph (- arg))
  18863. (while (and (> arg 0) (not (bobp)))
  18864. (org--backward-paragraph-once)
  18865. (cl-decf arg))
  18866. ;; Return moves left.
  18867. arg))
  18868. (defvar org--single-lines-list-is-paragraph t
  18869. "Treat plain lists with single line items as a whole paragraph")
  18870. (defun org--paragraph-at-point ()
  18871. "Return paragraph, or equivalent, element at point.
  18872. Paragraph element at point is the element at point, with the
  18873. following special cases:
  18874. - treat table rows (resp. node properties) as the table
  18875. \(resp. property drawer) containing them.
  18876. - treat plain lists with an item every line as a whole.
  18877. - treat consecutive keywords, clocks, and diary-sexps as a single
  18878. block.
  18879. Function may return a real element, or a pseudo-element with type
  18880. `pseudo-paragraph'."
  18881. (let* ((e (org-element-at-point))
  18882. (type (org-element-type e))
  18883. ;; If we need to fake a new pseudo-element, triplet is
  18884. ;;
  18885. ;; (BEG END PARENT)
  18886. ;;
  18887. ;; where BEG and END are element boundaries, and PARENT the
  18888. ;; element containing it, or nil.
  18889. (triplet
  18890. (cond
  18891. ((memq type '(table property-drawer))
  18892. (list (org-element-property :begin e)
  18893. (org-element-property :end e)
  18894. (org-element-property :parent e)))
  18895. ((memq type '(node-property table-row))
  18896. (let ((e (org-element-property :parent e)))
  18897. (list (org-element-property :begin e)
  18898. (org-element-property :end e)
  18899. (org-element-property :parent e))))
  18900. ((memq type '(clock diary-sexp keyword))
  18901. (let* ((regexp (pcase type
  18902. (`clock org-clock-line-re)
  18903. (`diary-sexp "%%(")
  18904. (_ org-keyword-regexp)))
  18905. (end (if (< 0 (org-element-property :post-blank e))
  18906. (org-element-property :end e)
  18907. (org-with-wide-buffer
  18908. (forward-line)
  18909. (while (looking-at regexp) (forward-line))
  18910. (skip-chars-forward " \t\n")
  18911. (line-beginning-position))))
  18912. (begin (org-with-point-at (org-element-property :begin e)
  18913. (while (and (not (bobp)) (looking-at regexp))
  18914. (forward-line -1))
  18915. ;; We may have gotten one line too far.
  18916. (if (looking-at regexp)
  18917. (point)
  18918. (line-beginning-position 2)))))
  18919. (list begin end (org-element-property :parent e))))
  18920. ;; Find the full plain list containing point, the check it
  18921. ;; contains exactly one line per item.
  18922. ((let ((l (org-element-lineage e '(plain-list) t)))
  18923. (while (memq (org-element-type (org-element-property :parent l))
  18924. '(item plain-list))
  18925. (setq l (org-element-property :parent l)))
  18926. (and l org--single-lines-list-is-paragraph
  18927. (org-with-point-at (org-element-property :post-affiliated l)
  18928. (forward-line (length (org-element-property :structure l)))
  18929. (= (point) (org-element-property :contents-end l)))
  18930. ;; Return value.
  18931. (list (org-element-property :begin l)
  18932. (org-element-property :end l)
  18933. (org-element-property :parent l)))))
  18934. (t nil)))) ;no triplet: return element
  18935. (pcase triplet
  18936. (`(,b ,e ,p)
  18937. (org-element-create
  18938. 'pseudo-paragraph
  18939. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18940. (_ e))))
  18941. (defun org--forward-paragraph-once ()
  18942. "Move forward to end of paragraph or equivalent, once.
  18943. See `org-forward-paragraph'."
  18944. (interactive)
  18945. (save-restriction
  18946. (widen)
  18947. (skip-chars-forward " \t\n")
  18948. (cond
  18949. ((eobp) nil)
  18950. ;; When inside a folded part, move out of it.
  18951. ((when (org-invisible-p nil t)
  18952. (goto-char (cdr (org-fold-get-region-at-point)))
  18953. (forward-line)
  18954. t))
  18955. (t
  18956. (let* ((element (org--paragraph-at-point))
  18957. (type (org-element-type element))
  18958. (contents-begin (org-element-property :contents-begin element))
  18959. (end (org-element-property :end element))
  18960. (post-affiliated (org-element-property :post-affiliated element)))
  18961. (cond
  18962. ((eq type 'plain-list)
  18963. (forward-char)
  18964. (org--forward-paragraph-once))
  18965. ;; If the element is folded, skip it altogether.
  18966. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18967. (goto-char (cdr (org-fold-get-region-at-point
  18968. nil
  18969. (org-with-point-at post-affiliated
  18970. (line-end-position)))))
  18971. (forward-line)
  18972. t))
  18973. ;; At a greater element, move inside.
  18974. ((and contents-begin
  18975. (> contents-begin (point))
  18976. (not (eq type 'paragraph)))
  18977. (goto-char contents-begin)
  18978. ;; Items and footnote definitions contents may not start at
  18979. ;; the beginning of the line. In this case, skip until the
  18980. ;; next paragraph.
  18981. (cond
  18982. ((not (bolp)) (org--forward-paragraph-once))
  18983. ((org-previous-line-empty-p) (forward-line -1))
  18984. (t nil)))
  18985. ;; Move between empty lines in some blocks.
  18986. ((memq type '(comment-block example-block export-block src-block
  18987. verse-block))
  18988. (let ((contents-start
  18989. (org-with-point-at post-affiliated
  18990. (line-beginning-position 2))))
  18991. (if (< (point) contents-start)
  18992. (goto-char contents-start)
  18993. (let ((contents-end
  18994. (org-with-point-at end
  18995. (skip-chars-backward " \t\n")
  18996. (line-beginning-position))))
  18997. (cond
  18998. ((>= (point) contents-end)
  18999. (goto-char end)
  19000. (skip-chars-backward " \t\n")
  19001. (forward-line))
  19002. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19003. (forward-line -1))
  19004. (t nil))))))
  19005. (t
  19006. ;; Move to element's end.
  19007. (goto-char end)
  19008. (skip-chars-backward " \t\n")
  19009. (forward-line))))))))
  19010. (defun org--backward-paragraph-once ()
  19011. "Move backward to start of paragraph or equivalent, once.
  19012. See `org-backward-paragraph'."
  19013. (interactive)
  19014. (save-restriction
  19015. (widen)
  19016. (cond
  19017. ((bobp) nil)
  19018. ;; Blank lines at the beginning of the buffer.
  19019. ((and (org-match-line "^[ \t]*$")
  19020. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19021. (goto-char (point-min)))
  19022. ;; When inside a folded part, move out of it.
  19023. ((when (org-invisible-p (1- (point)) t)
  19024. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  19025. (org--backward-paragraph-once)
  19026. t))
  19027. (t
  19028. (let* ((element (org--paragraph-at-point))
  19029. (type (org-element-type element))
  19030. (begin (org-element-property :begin element))
  19031. (post-affiliated (org-element-property :post-affiliated element))
  19032. (contents-end (org-element-property :contents-end element))
  19033. (end (org-element-property :end element))
  19034. (parent (org-element-property :parent element))
  19035. (reach
  19036. ;; Move to the visible empty line above position P, or
  19037. ;; to position P. Return t.
  19038. (lambda (p)
  19039. (goto-char p)
  19040. (when (and (org-previous-line-empty-p)
  19041. (let ((end (line-end-position 0)))
  19042. (or (= end (point-min))
  19043. (not (org-invisible-p (1- end))))))
  19044. (forward-line -1))
  19045. t)))
  19046. (cond
  19047. ;; Already at the beginning of an element.
  19048. ((= begin (point))
  19049. (cond
  19050. ;; There is a blank line above. Move there.
  19051. ((and (org-previous-line-empty-p)
  19052. (not (org-invisible-p (1- (line-end-position 0)))))
  19053. (forward-line -1))
  19054. ;; At the beginning of the first element within a greater
  19055. ;; element. Move to the beginning of the greater element.
  19056. ((and parent
  19057. (not (eq 'section (org-element-type parent)))
  19058. (= begin (org-element-property :contents-begin parent)))
  19059. (funcall reach (org-element-property :begin parent)))
  19060. ;; Since we have to move anyway, find the beginning
  19061. ;; position of the element above.
  19062. (t
  19063. (forward-char -1)
  19064. (org--backward-paragraph-once))))
  19065. ;; Skip paragraphs at the very beginning of footnote
  19066. ;; definitions or items.
  19067. ((and (eq type 'paragraph)
  19068. (org-with-point-at begin (not (bolp))))
  19069. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19070. ;; If the element is folded, skip it altogether.
  19071. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  19072. (funcall reach begin))
  19073. ;; At the end of a greater element, move inside.
  19074. ((and contents-end
  19075. (<= contents-end (point))
  19076. (not (eq type 'paragraph)))
  19077. (cond
  19078. ((memq type '(footnote-definition plain-list))
  19079. (skip-chars-backward " \t\n")
  19080. (org--backward-paragraph-once))
  19081. ((= contents-end (point))
  19082. (forward-char -1)
  19083. (org--backward-paragraph-once))
  19084. (t
  19085. (goto-char contents-end))))
  19086. ;; Move between empty lines in some blocks.
  19087. ((and (memq type '(comment-block example-block export-block src-block
  19088. verse-block))
  19089. (let ((contents-start
  19090. (org-with-point-at post-affiliated
  19091. (line-beginning-position 2))))
  19092. (when (> (point) contents-start)
  19093. (let ((contents-end
  19094. (org-with-point-at end
  19095. (skip-chars-backward " \t\n")
  19096. (line-beginning-position))))
  19097. (if (> (point) contents-end)
  19098. (progn (goto-char contents-end) t)
  19099. (skip-chars-backward " \t\n" begin)
  19100. (re-search-backward "^[ \t]*\n" contents-start :move)
  19101. t))))))
  19102. ;; Move to element's start.
  19103. (t
  19104. (funcall reach begin))))))))
  19105. (defun org-forward-element ()
  19106. "Move forward by one element.
  19107. Move to the next element at the same level, when possible."
  19108. (interactive)
  19109. (cond ((eobp) (user-error "Cannot move further down"))
  19110. ((org-with-limited-levels (org-at-heading-p))
  19111. (let ((origin (point)))
  19112. (goto-char (org-end-of-subtree nil t))
  19113. (unless (org-with-limited-levels (org-at-heading-p))
  19114. (goto-char origin)
  19115. (user-error "Cannot move further down"))))
  19116. (t
  19117. (let* ((elem (org-element-at-point))
  19118. (end (org-element-property :end elem))
  19119. (parent (org-element-property :parent elem)))
  19120. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19121. (goto-char (org-element-property :end parent)))
  19122. ((integer-or-marker-p end) (goto-char end))
  19123. (t (message "No element at point")))))))
  19124. (defun org-backward-element ()
  19125. "Move backward by one element.
  19126. Move to the previous element at the same level, when possible."
  19127. (interactive)
  19128. (cond ((bobp) (user-error "Cannot move further up"))
  19129. ((org-with-limited-levels (org-at-heading-p))
  19130. ;; At a headline, move to the previous one, if any, or stay
  19131. ;; here.
  19132. (let ((origin (point)))
  19133. (org-with-limited-levels (org-backward-heading-same-level 1))
  19134. ;; When current headline has no sibling above, move to its
  19135. ;; parent.
  19136. (when (= (point) origin)
  19137. (or (org-with-limited-levels (org-up-heading-safe))
  19138. (progn (goto-char origin)
  19139. (user-error "Cannot move further up"))))))
  19140. (t
  19141. (let* ((elem (org-element-at-point))
  19142. (beg (org-element-property :begin elem)))
  19143. (cond
  19144. ;; Move to beginning of current element if point isn't
  19145. ;; there already.
  19146. ((null beg) (message "No element at point"))
  19147. ((/= (point) beg) (goto-char beg))
  19148. (t (goto-char beg)
  19149. (skip-chars-backward " \r\t\n")
  19150. (unless (bobp)
  19151. (let ((prev (org-element-at-point)))
  19152. (goto-char (org-element-property :begin prev))
  19153. (while (and (setq prev (org-element-property :parent prev))
  19154. (<= (org-element-property :end prev) beg))
  19155. (goto-char (org-element-property :begin prev)))))))))))
  19156. (defun org-up-element ()
  19157. "Move to upper element."
  19158. (interactive)
  19159. (if (org-with-limited-levels (org-at-heading-p))
  19160. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19161. (let* ((elem (org-element-at-point))
  19162. (parent (org-element-property :parent elem)))
  19163. (if (and parent
  19164. (not (memq (org-element-type parent) '(section org-data))))
  19165. (goto-char (org-element-property :begin parent))
  19166. (if (org-with-limited-levels (org-before-first-heading-p))
  19167. (user-error "No surrounding element")
  19168. (org-with-limited-levels (org-back-to-heading)))))))
  19169. (defun org-down-element ()
  19170. "Move to inner element."
  19171. (interactive)
  19172. (let ((element (org-element-at-point)))
  19173. (cond
  19174. ((memq (org-element-type element) '(plain-list table))
  19175. (goto-char (org-element-property :contents-begin element))
  19176. (forward-char))
  19177. ((memq (org-element-type element) org-element-greater-elements)
  19178. ;; If contents are hidden, first disclose them.
  19179. (when (org-invisible-p (line-end-position)) (org-cycle))
  19180. (goto-char (or (org-element-property :contents-begin element)
  19181. (user-error "No content for this element"))))
  19182. (t (user-error "No inner element")))))
  19183. (defun org-drag-element-backward ()
  19184. "Move backward element at point."
  19185. (interactive)
  19186. (let ((elem (or (org-element-at-point)
  19187. (user-error "No element at point"))))
  19188. (if (eq (org-element-type elem) 'headline)
  19189. ;; Preserve point when moving a whole tree, even if point was
  19190. ;; on blank lines below the headline.
  19191. (let ((offset (skip-chars-backward " \t\n")))
  19192. (unwind-protect (org-move-subtree-up)
  19193. (forward-char (- offset))))
  19194. (let ((prev-elem
  19195. (save-excursion
  19196. (goto-char (org-element-property :begin elem))
  19197. (skip-chars-backward " \r\t\n")
  19198. (unless (bobp)
  19199. (let* ((beg (org-element-property :begin elem))
  19200. (prev (org-element-at-point))
  19201. (up prev))
  19202. (while (and (setq up (org-element-property :parent up))
  19203. (<= (org-element-property :end up) beg))
  19204. (setq prev up))
  19205. prev)))))
  19206. ;; Error out if no previous element or previous element is
  19207. ;; a parent of the current one.
  19208. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19209. (user-error "Cannot drag element backward")
  19210. (let ((pos (point)))
  19211. (org-element-swap-A-B prev-elem elem)
  19212. (goto-char (+ (org-element-property :begin prev-elem)
  19213. (- pos (org-element-property :begin elem))))))))))
  19214. (defun org-drag-element-forward ()
  19215. "Move forward element at point."
  19216. (interactive)
  19217. (let* ((pos (point))
  19218. (elem (or (org-element-at-point)
  19219. (user-error "No element at point"))))
  19220. (when (= (point-max) (org-element-property :end elem))
  19221. (user-error "Cannot drag element forward"))
  19222. (goto-char (org-element-property :end elem))
  19223. (let ((next-elem (org-element-at-point)))
  19224. (when (or (org-element-nested-p elem next-elem)
  19225. (and (eq (org-element-type next-elem) 'headline)
  19226. (not (eq (org-element-type elem) 'headline))))
  19227. (goto-char pos)
  19228. (user-error "Cannot drag element forward"))
  19229. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19230. ;; body's length (without final blanks) and by the length of
  19231. ;; blanks between ELEM and NEXT-ELEM.
  19232. (let ((size-next (- (save-excursion
  19233. (goto-char (org-element-property :end next-elem))
  19234. (skip-chars-backward " \r\t\n")
  19235. (forward-line)
  19236. ;; Small correction if buffer doesn't end
  19237. ;; with a newline character.
  19238. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19239. (org-element-property :begin next-elem)))
  19240. (size-blank (- (org-element-property :end elem)
  19241. (save-excursion
  19242. (goto-char (org-element-property :end elem))
  19243. (skip-chars-backward " \r\t\n")
  19244. (forward-line)
  19245. (point)))))
  19246. (org-element-swap-A-B elem next-elem)
  19247. (goto-char (+ pos size-next size-blank))))))
  19248. (defun org-drag-line-forward (arg)
  19249. "Drag the line at point ARG lines forward."
  19250. (interactive "p")
  19251. (dotimes (_ (abs arg))
  19252. (let ((c (current-column)))
  19253. (if (< 0 arg)
  19254. (progn
  19255. (beginning-of-line 2)
  19256. (transpose-lines 1)
  19257. (beginning-of-line 0))
  19258. (transpose-lines 1)
  19259. (beginning-of-line -1))
  19260. (org-move-to-column c))))
  19261. (defun org-drag-line-backward (arg)
  19262. "Drag the line at point ARG lines backward."
  19263. (interactive "p")
  19264. (org-drag-line-forward (- arg)))
  19265. (defun org-mark-element ()
  19266. "Put point at beginning of this element, mark at end.
  19267. Interactively, if this command is repeated or (in Transient Mark
  19268. mode) if the mark is active, it marks the next element after the
  19269. ones already marked."
  19270. (interactive)
  19271. (let (deactivate-mark)
  19272. (if (and (called-interactively-p 'any)
  19273. (or (and (eq last-command this-command) (mark t))
  19274. (and transient-mark-mode mark-active)))
  19275. (set-mark
  19276. (save-excursion
  19277. (goto-char (mark))
  19278. (goto-char (org-element-property :end (org-element-at-point)))
  19279. (point)))
  19280. (let ((element (org-element-at-point)))
  19281. (end-of-line)
  19282. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19283. (goto-char (org-element-property :begin element))))))
  19284. (defun org-narrow-to-element ()
  19285. "Narrow buffer to current element."
  19286. (interactive)
  19287. (let ((elem (org-element-at-point)))
  19288. (cond
  19289. ((eq (car elem) 'headline)
  19290. (narrow-to-region
  19291. (org-element-property :begin elem)
  19292. (org-element-property :end elem)))
  19293. ((memq (car elem) org-element-greater-elements)
  19294. (narrow-to-region
  19295. (org-element-property :contents-begin elem)
  19296. (org-element-property :contents-end elem)))
  19297. (t
  19298. (narrow-to-region
  19299. (org-element-property :begin elem)
  19300. (org-element-property :end elem))))))
  19301. (defun org-transpose-element ()
  19302. "Transpose current and previous elements, keeping blank lines between.
  19303. Point is moved after both elements."
  19304. (interactive)
  19305. (org-skip-whitespace)
  19306. (let ((end (org-element-property :end (org-element-at-point))))
  19307. (org-drag-element-backward)
  19308. (goto-char end)))
  19309. (defun org-unindent-buffer ()
  19310. "Un-indent the visible part of the buffer.
  19311. Relative indentation (between items, inside blocks, etc.) isn't
  19312. modified."
  19313. (interactive)
  19314. (unless (eq major-mode 'org-mode)
  19315. (user-error "Cannot un-indent a buffer not in Org mode"))
  19316. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19317. (unindent-tree
  19318. (lambda (contents)
  19319. (dolist (element (reverse contents))
  19320. (if (memq (org-element-type element) '(headline section))
  19321. (funcall unindent-tree (org-element-contents element))
  19322. (save-excursion
  19323. (save-restriction
  19324. (narrow-to-region
  19325. (org-element-property :begin element)
  19326. (org-element-property :end element))
  19327. (org-do-remove-indentation))))))))
  19328. (funcall unindent-tree (org-element-contents parse-tree))))
  19329. (defun org-make-options-regexp (kwds &optional extra)
  19330. "Make a regular expression for keyword lines.
  19331. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19332. when non-nil, is a regexp matching keywords names."
  19333. (concat "^[ \t]*#\\+\\("
  19334. (regexp-opt kwds)
  19335. (and extra (concat (and kwds "\\|") extra))
  19336. "\\):[ \t]*\\(.*\\)"))
  19337. ;;; Conveniently switch to Info nodes
  19338. (defun org-info-find-node (&optional nodename)
  19339. "Find Info documentation NODENAME or Org documentation according context.
  19340. Started from `gnus-info-find-node'."
  19341. (interactive)
  19342. (Info-goto-node
  19343. (or nodename
  19344. (let ((default-org-info-node "(org) Top"))
  19345. (cond
  19346. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19347. ((eq 'org-mode major-mode)
  19348. (let* ((context (org-element-at-point))
  19349. (element-info-nodes ; compare to `org-element-all-elements'.
  19350. `((babel-call . "(org) Evaluating Code Blocks")
  19351. (center-block . "(org) Paragraphs")
  19352. (clock . ,default-org-info-node)
  19353. (comment . "(org) Comment Lines")
  19354. (comment-block . "(org) Comment Lines")
  19355. (diary-sexp . ,default-org-info-node)
  19356. (drawer . "(org) Drawers")
  19357. (dynamic-block . "(org) Dynamic Blocks")
  19358. (example-block . "(org) Literal Examples")
  19359. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19360. (fixed-width . ,default-org-info-node)
  19361. (footnote-definition . "(org) Creating Footnotes")
  19362. (headline . "(org) Document Structure")
  19363. (horizontal-rule . "(org) Built-in Table Editor")
  19364. (inlinetask . ,default-org-info-node)
  19365. (item . "(org) Plain Lists")
  19366. (keyword . "(org) Per-file keywords")
  19367. (latex-environment . "(org) LaTeX Export")
  19368. (node-property . "(org) Properties and Columns")
  19369. (paragraph . "(org) Paragraphs")
  19370. (plain-list . "(org) Plain Lists")
  19371. (planning . "(org) Deadlines and Scheduling")
  19372. (property-drawer . "(org) Properties and Columns")
  19373. (quote-block . "(org) Paragraphs")
  19374. (section . ,default-org-info-node)
  19375. (special-block . ,default-org-info-node)
  19376. (src-block . "(org) Working with Source Code")
  19377. (table . "(org) Tables")
  19378. (table-row . "(org) Tables")
  19379. (verse-block . "(org) Paragraphs"))))
  19380. (or (cdr (assoc (car context) element-info-nodes))
  19381. default-org-info-node)))
  19382. (t default-org-info-node))))))
  19383. ;;; Finish up
  19384. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19385. (lambda () (add-hook 'change-major-mode-hook
  19386. 'org-fold-show-all 'append 'local)))
  19387. (provide 'org)
  19388. (run-hooks 'org-load-hook)
  19389. ;;; org.el ends here