org.el 902 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2019 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.2.2
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  111. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  112. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  113. (declare-function org-clock-cancel "org-clock" ())
  114. (declare-function org-clock-display "org-clock" (&optional arg))
  115. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  116. (declare-function org-clock-goto "org-clock" (&optional select))
  117. (declare-function org-clock-in "org-clock" (&optional select start-time))
  118. (declare-function org-clock-in-last "org-clock" (&optional arg))
  119. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  120. (declare-function org-clock-out-if-current "org-clock" ())
  121. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  122. (declare-function org-clock-report "org-clock" (&optional arg))
  123. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  124. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  125. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  126. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  127. (declare-function org-clock-update-time-maybe "org-clock" ())
  128. (declare-function org-clocking-buffer "org-clock" ())
  129. (declare-function org-clocktable-shift "org-clock" (dir n))
  130. (declare-function org-columns-insert-dblock "org-colview" ())
  131. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  132. (declare-function org-element-at-point "org-element" ())
  133. (declare-function org-element-cache-refresh "org-element" (pos))
  134. (declare-function org-element-cache-reset "org-element" (&optional all))
  135. (declare-function org-element-contents "org-element" (element))
  136. (declare-function org-element-context "org-element" (&optional element))
  137. (declare-function org-element-copy "org-element" (datum))
  138. (declare-function org-element-create "org-element" (type &optional props &rest children))
  139. (declare-function org-element-interpret-data "org-element" (data))
  140. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  141. (declare-function org-element-link-parser "org-element" ())
  142. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  143. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  144. (declare-function org-element-property "org-element" (property element))
  145. (declare-function org-element-put-property "org-element" (element property value))
  146. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  147. (declare-function org-element-timestamp-parser "org-element" ())
  148. (declare-function org-element-type "org-element" (element))
  149. (declare-function org-element-update-syntax "org-element" ())
  150. (declare-function org-export-dispatch "ox" (&optional arg))
  151. (declare-function org-export-get-backend "ox" (name))
  152. (declare-function org-export-get-backend "ox" (name))
  153. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  154. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  155. (declare-function org-feed-goto-inbox "org-feed" (feed))
  156. (declare-function org-feed-update-all "org-feed" ())
  157. (declare-function org-goto "org-goto" (&optional alternative-interface))
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  168. (declare-function org-table-align "org-table" ())
  169. (declare-function org-table-begin "org-table" (&optional table-type))
  170. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  171. (declare-function org-table-blank-field "org-table" ())
  172. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  173. (declare-function org-table-copy-down "org-table" (N))
  174. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  175. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  176. (declare-function org-table-create-with-table.el "org-table" ())
  177. (declare-function org-table-cut-region "org-table" (beg end))
  178. (declare-function org-table-edit-field "org-table" (arg))
  179. (declare-function org-table-end "org-table" (&optional table-type))
  180. (declare-function org-table-end-of-field "org-table" (&optional n))
  181. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  182. (declare-function org-table-field-info "org-table" (arg))
  183. (declare-function org-table-insert-row "org-table" (&optional arg))
  184. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  185. (declare-function org-table-maybe-eval-formula "org-table" ())
  186. (declare-function org-table-maybe-recalculate-line "org-table" ())
  187. (declare-function org-table-next-row "org-table" ())
  188. (declare-function org-table-paste-rectangle "org-table" ())
  189. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  190. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  191. (declare-function org-table-shrink "org-table" (&optional begin end))
  192. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  193. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  194. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  195. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  196. (declare-function org-table-toggle-formula-debugger "org-table" ())
  197. (declare-function org-table-wrap-region "org-table" (arg))
  198. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  199. (declare-function org-timer "org-timer" (&optional restart no-insert))
  200. (declare-function org-timer-item "org-timer" (&optional arg))
  201. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  202. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  203. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  204. (declare-function org-timer-start "org-timer" (&optional offset))
  205. (declare-function org-timer-stop "org-timer" ())
  206. (declare-function org-timer-stop "org-timer" ())
  207. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  208. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  209. (declare-function orgtbl-mode "org-table" (&optional arg))
  210. (defvar ffap-url-regexp)
  211. (defvar org-element-paragraph-separate)
  212. (defvar org-indent-indentation-per-level)
  213. ;; load languages based on value of `org-babel-load-languages'
  214. (defvar org-babel-load-languages)
  215. ;;;###autoload
  216. (defun org-babel-do-load-languages (sym value)
  217. "Load the languages defined in `org-babel-load-languages'."
  218. (set-default sym value)
  219. (dolist (pair org-babel-load-languages)
  220. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  221. (if active
  222. (require (intern (concat "ob-" lang)))
  223. (fmakunbound
  224. (intern (concat "org-babel-execute:" lang)))
  225. (fmakunbound
  226. (intern (concat "org-babel-expand-body:" lang)))))))
  227. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  228. ;;;###autoload
  229. (defun org-babel-load-file (file &optional compile)
  230. "Load Emacs Lisp source code blocks in the Org FILE.
  231. This function exports the source code using `org-babel-tangle'
  232. and then loads the resulting file using `load-file'. With prefix
  233. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  234. file to byte-code before it is loaded."
  235. (interactive "fFile to load: \nP")
  236. (let* ((age (lambda (file)
  237. (float-time
  238. (time-subtract (current-time)
  239. (file-attribute-modification-time
  240. (or (file-attributes (file-truename file))
  241. (file-attributes file)))))))
  242. (base-name (file-name-sans-extension file))
  243. (exported-file (concat base-name ".el")))
  244. ;; tangle if the Org file is newer than the elisp file
  245. (unless (and (file-exists-p exported-file)
  246. (> (funcall age file) (funcall age exported-file)))
  247. ;; Tangle-file traversal returns reversed list of tangled files
  248. ;; and we want to evaluate the first target.
  249. (setq exported-file
  250. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  251. (message "%s %s"
  252. (if compile
  253. (progn (byte-compile-file exported-file 'load)
  254. "Compiled and loaded")
  255. (progn (load-file exported-file) "Loaded"))
  256. exported-file)))
  257. (defcustom org-babel-load-languages '((emacs-lisp . t))
  258. "Languages which can be evaluated in Org buffers.
  259. \\<org-mode-map>
  260. This list can be used to load support for any of the languages
  261. below. Each language will depend on a different set of system
  262. executables and/or 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 "Asymptote" asymptote)
  280. (const :tag "Calc" calc)
  281. (const :tag "Clojure" clojure)
  282. (const :tag "CSS" css)
  283. (const :tag "Ditaa" ditaa)
  284. (const :tag "Dot" dot)
  285. (const :tag "Ebnf2ps" ebnf2ps)
  286. (const :tag "Emacs Lisp" emacs-lisp)
  287. (const :tag "Forth" forth)
  288. (const :tag "Fortran" fortran)
  289. (const :tag "Gnuplot" gnuplot)
  290. (const :tag "Haskell" haskell)
  291. (const :tag "hledger" hledger)
  292. (const :tag "IO" io)
  293. (const :tag "J" J)
  294. (const :tag "Java" java)
  295. (const :tag "Javascript" js)
  296. (const :tag "LaTeX" latex)
  297. (const :tag "Ledger" ledger)
  298. (const :tag "Lilypond" lilypond)
  299. (const :tag "Lisp" lisp)
  300. (const :tag "Makefile" makefile)
  301. (const :tag "Maxima" maxima)
  302. (const :tag "Matlab" matlab)
  303. (const :tag "Mscgen" mscgen)
  304. (const :tag "Ocaml" ocaml)
  305. (const :tag "Octave" octave)
  306. (const :tag "Org" org)
  307. (const :tag "Perl" perl)
  308. (const :tag "Pico Lisp" picolisp)
  309. (const :tag "PlantUML" plantuml)
  310. (const :tag "Python" python)
  311. (const :tag "Ruby" ruby)
  312. (const :tag "Sass" sass)
  313. (const :tag "Scala" scala)
  314. (const :tag "Scheme" scheme)
  315. (const :tag "Screen" screen)
  316. (const :tag "Shell Script" shell)
  317. (const :tag "Shen" shen)
  318. (const :tag "Sql" sql)
  319. (const :tag "Sqlite" sqlite)
  320. (const :tag "Stan" stan)
  321. (const :tag "Vala" vala))
  322. :value-type (boolean :tag "Activate" :value t)))
  323. ;;;; Customization variables
  324. (defcustom org-clone-delete-id nil
  325. "Remove ID property of clones of a subtree.
  326. When non-nil, clones of a subtree don't inherit the ID property.
  327. Otherwise they inherit the ID property with a new unique
  328. identifier."
  329. :type 'boolean
  330. :version "24.1"
  331. :group 'org-id)
  332. ;;; Version
  333. (org-check-version)
  334. ;;;###autoload
  335. (defun org-version (&optional here full message)
  336. "Show the Org version.
  337. Interactively, or when MESSAGE is non-nil, show it in echo area.
  338. With prefix argument, or when HERE is non-nil, insert it at point.
  339. In non-interactive uses, a reduced version string is output unless
  340. FULL is given."
  341. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  342. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  343. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  344. (load-suffixes (list ".el"))
  345. (org-install-dir
  346. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  347. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  348. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  349. (let* ((load-suffixes save-load-suffixes)
  350. (release (org-release))
  351. (git-version (org-git-version))
  352. (version (format "Org mode version %s (%s @ %s)"
  353. release
  354. git-version
  355. (if org-install-dir
  356. (if (string= org-dir org-install-dir)
  357. org-install-dir
  358. (concat "mixed installation! "
  359. org-install-dir
  360. " and "
  361. org-dir))
  362. "org-loaddefs.el can not be found!")))
  363. (version1 (if full version release)))
  364. (when here (insert version1))
  365. (when message (message "%s" version1))
  366. version1)))
  367. (defconst org-version (org-version))
  368. ;;; Syntax Constants
  369. ;;;; Block
  370. (defconst org-block-regexp
  371. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  372. "Regular expression for hiding blocks.")
  373. (defconst org-dblock-start-re
  374. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  375. "Matches the start line of a dynamic block, with parameters.")
  376. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  377. "Matches the end of a dynamic block.")
  378. ;;;; Clock and Planning
  379. (defconst org-clock-string "CLOCK:"
  380. "String used as prefix for timestamps clocking work hours on an item.")
  381. (defvar org-closed-string "CLOSED:"
  382. "String used as the prefix for timestamps logging closing a TODO entry.")
  383. (defvar org-deadline-string "DEADLINE:"
  384. "String to mark deadline entries.
  385. \\<org-mode-map>
  386. A deadline is this string, followed by a time stamp. It must be
  387. a word, terminated by a colon. You can insert a schedule keyword
  388. and a timestamp with `\\[org-deadline]'.")
  389. (defvar org-scheduled-string "SCHEDULED:"
  390. "String to mark scheduled TODO entries.
  391. \\<org-mode-map>
  392. A schedule is this string, followed by a time stamp. It must be
  393. a word, terminated by a colon. You can insert a schedule keyword
  394. and a timestamp with `\\[org-schedule]'.")
  395. (defconst org-ds-keyword-length
  396. (+ 2
  397. (apply #'max
  398. (mapcar #'length
  399. (list org-deadline-string org-scheduled-string
  400. org-clock-string org-closed-string))))
  401. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  402. (defconst org-planning-line-re
  403. (concat "^[ \t]*"
  404. (regexp-opt
  405. (list org-closed-string org-deadline-string org-scheduled-string)
  406. t))
  407. "Matches a line with planning info.
  408. Matched keyword is in group 1.")
  409. (defconst org-clock-line-re
  410. (concat "^[ \t]*" org-clock-string)
  411. "Matches a line with clock info.")
  412. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  413. "Matches the DEADLINE keyword.")
  414. (defconst org-deadline-time-regexp
  415. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  416. "Matches the DEADLINE keyword together with a time stamp.")
  417. (defconst org-deadline-time-hour-regexp
  418. (concat "\\<" org-deadline-string
  419. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  420. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  421. (defconst org-deadline-line-regexp
  422. (concat "\\<\\(" org-deadline-string "\\).*")
  423. "Matches the DEADLINE keyword and the rest of the line.")
  424. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  425. "Matches the SCHEDULED keyword.")
  426. (defconst org-scheduled-time-regexp
  427. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  428. "Matches the SCHEDULED keyword together with a time stamp.")
  429. (defconst org-scheduled-time-hour-regexp
  430. (concat "\\<" org-scheduled-string
  431. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  432. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  433. (defconst org-closed-time-regexp
  434. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  435. "Matches the CLOSED keyword together with a time stamp.")
  436. (defconst org-keyword-time-regexp
  437. (concat "\\<"
  438. (regexp-opt
  439. (list org-scheduled-string org-deadline-string org-closed-string
  440. org-clock-string)
  441. t)
  442. " *[[<]\\([^]>]+\\)[]>]")
  443. "Matches any of the 4 keywords, together with the time stamp.")
  444. (defconst org-keyword-time-not-clock-regexp
  445. (concat
  446. "\\<"
  447. (regexp-opt
  448. (list org-scheduled-string org-deadline-string org-closed-string) t)
  449. " *[[<]\\([^]>]+\\)[]>]")
  450. "Matches any of the 3 keywords, together with the time stamp.")
  451. (defconst org-maybe-keyword-time-regexp
  452. (concat "\\(\\<"
  453. (regexp-opt
  454. (list org-scheduled-string org-deadline-string org-closed-string
  455. org-clock-string)
  456. t)
  457. "\\)?"
  458. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  459. "\\|"
  460. "<%%([^\r\n>]*>\\)")
  461. "Matches a timestamp, possibly preceded by a keyword.")
  462. (defconst org-all-time-keywords
  463. (mapcar (lambda (w) (substring w 0 -1))
  464. (list org-scheduled-string org-deadline-string
  465. org-clock-string org-closed-string))
  466. "List of time keywords.")
  467. ;;;; Drawer
  468. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  469. "Matches first or last line of a hidden block.
  470. Group 1 contains drawer's name or \"END\".")
  471. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  472. "Regular expression matching the first line of a property drawer.")
  473. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  474. "Regular expression matching the last line of a property drawer.")
  475. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  476. "Regular expression matching the first line of a clock drawer.")
  477. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  478. "Regular expression matching the last line of a clock drawer.")
  479. (defconst org-property-drawer-re
  480. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  481. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  482. "[ \t]*:END:[ \t]*$")
  483. "Matches an entire property drawer.")
  484. (defconst org-clock-drawer-re
  485. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  486. org-clock-drawer-end-re "\\)\n?")
  487. "Matches an entire clock drawer.")
  488. ;;;; Headline
  489. (defconst org-heading-keyword-regexp-format
  490. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  491. "Printf format for a regexp matching a headline with some keyword.
  492. This regexp will match the headline of any node which has the
  493. exact keyword that is put into the format. The keyword isn't in
  494. any group by default, but the stars and the body are.")
  495. (defconst org-heading-keyword-maybe-regexp-format
  496. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  497. "Printf format for a regexp matching a headline, possibly with some keyword.
  498. This regexp can match any headline with the specified keyword, or
  499. without a keyword. The keyword isn't in any group by default,
  500. but the stars and the body are.")
  501. (defconst org-archive-tag "ARCHIVE"
  502. "The tag that marks a subtree as archived.
  503. An archived subtree does not open during visibility cycling, and does
  504. not contribute to the agenda listings.")
  505. (defconst org-tag-re "[[:alnum:]_@#%]+"
  506. "Regexp matching a single tag.")
  507. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  508. "Regexp matching the tag group at the end of a line, with leading spaces.
  509. Tags are stored in match group 1. Match group 2 stores the tags
  510. without the enclosing colons.")
  511. (defconst org-tag-line-re
  512. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  513. "Regexp matching tags in a headline.
  514. Tags are stored in match group 1. Match group 2 stores the tags
  515. without the enclosing colons.")
  516. (eval-and-compile
  517. (defconst org-comment-string "COMMENT"
  518. "Entries starting with this keyword will never be exported.
  519. \\<org-mode-map>
  520. An entry can be toggled between COMMENT and normal with
  521. `\\[org-toggle-comment]'."))
  522. ;;;; LaTeX Environments and Fragments
  523. (defconst org-latex-regexps
  524. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  525. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  526. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  527. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  528. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  529. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  530. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  531. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  532. "Regular expressions for matching embedded LaTeX.")
  533. ;;;; Node Property
  534. (defconst org-effort-property "Effort"
  535. "The property that is being used to keep track of effort estimates.
  536. Effort estimates given in this property need to have the format H:MM.")
  537. ;;;; Table
  538. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  539. "Detect an org-type or table-type table.")
  540. (defconst org-table-line-regexp "^[ \t]*|"
  541. "Detect an org-type table line.")
  542. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  543. "Detect an org-type table line.")
  544. (defconst org-table-hline-regexp "^[ \t]*|-"
  545. "Detect an org-type table hline.")
  546. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  547. "Detect a table-type table hline.")
  548. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  549. "Detect the first line outside a table when searching from within it.
  550. This works for both table types.")
  551. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  552. "Detect a #+TBLFM line.")
  553. ;;;; Timestamp
  554. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  555. "Regular expression for fast time stamp matching.")
  556. (defconst org-ts-regexp-inactive
  557. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  558. "Regular expression for fast inactive time stamp matching.")
  559. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  560. "Regular expression for fast time stamp matching.")
  561. (defconst org-ts-regexp0
  562. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  563. "Regular expression matching time strings for analysis.
  564. This one does not require the space after the date, so it can be used
  565. on a string that terminates immediately after the date.")
  566. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  567. "Regular expression matching time strings for analysis.")
  568. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  569. "Regular expression matching time stamps, with groups.")
  570. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  571. "Regular expression matching time stamps (also [..]), with groups.")
  572. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  573. "Regular expression matching a time stamp range.")
  574. (defconst org-tr-regexp-both
  575. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  576. "Regular expression matching a time stamp range.")
  577. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  578. org-ts-regexp "\\)?")
  579. "Regular expression matching a time stamp or time stamp range.")
  580. (defconst org-tsr-regexp-both
  581. (concat org-ts-regexp-both "\\(--?-?"
  582. org-ts-regexp-both "\\)?")
  583. "Regular expression matching a time stamp or time stamp range.
  584. The time stamps may be either active or inactive.")
  585. (defconst org-repeat-re
  586. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  587. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  588. "Regular expression for specifying repeated events.
  589. After a match, group 1 contains the repeat expression.")
  590. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  591. "Formats for `format-time-string' which are used for time stamps.")
  592. ;;; The custom variables
  593. (defgroup org nil
  594. "Outline-based notes management and organizer."
  595. :tag "Org"
  596. :group 'outlines
  597. :group 'calendar)
  598. (defcustom org-mode-hook nil
  599. "Mode hook for Org mode, run after the mode was turned on."
  600. :group 'org
  601. :type 'hook)
  602. (defcustom org-load-hook nil
  603. "Hook that is run after org.el has been loaded."
  604. :group 'org
  605. :type 'hook)
  606. (defcustom org-log-buffer-setup-hook nil
  607. "Hook that is run after an Org log buffer is created."
  608. :group 'org
  609. :version "24.1"
  610. :type 'hook)
  611. (defvar org-modules) ; defined below
  612. (defvar org-modules-loaded nil
  613. "Have the modules been loaded already?")
  614. (defun org-load-modules-maybe (&optional force)
  615. "Load all extensions listed in `org-modules'."
  616. (when (or force (not org-modules-loaded))
  617. (dolist (ext org-modules)
  618. (condition-case nil (require ext)
  619. (error (message "Problems while trying to load feature `%s'" ext))))
  620. (setq org-modules-loaded t)))
  621. (defun org-set-modules (var value)
  622. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  623. (set var value)
  624. (when (featurep 'org)
  625. (org-load-modules-maybe 'force)
  626. (org-element-cache-reset 'all)))
  627. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  628. "Modules that should always be loaded together with org.el.
  629. If a description starts with <C>, the file is not part of Emacs
  630. and loading it will require that you have downloaded and properly
  631. installed the Org mode distribution.
  632. You can also use this system to load external packages (i.e. neither Org
  633. core modules, nor modules from the CONTRIB directory). Just add symbols
  634. to the end of the list. If the package is called org-xyz.el, then you need
  635. to add the symbol `xyz', and the package must have a call to:
  636. (provide \\='org-xyz)
  637. For export specific modules, see also `org-export-backends'."
  638. :group 'org
  639. :set 'org-set-modules
  640. :version "26.1"
  641. :package-version '(Org . "9.2")
  642. :type
  643. '(set :greedy t
  644. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  645. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  646. (const :tag " crypt: Encryption of subtrees" org-crypt)
  647. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  648. (const :tag " docview: Links to doc-view buffers" org-docview)
  649. (const :tag " eww: Store link to url of eww" org-eww)
  650. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  651. (const :tag " habit: Track your consistency with habits" org-habit)
  652. (const :tag " id: Global IDs for identifying entries" org-id)
  653. (const :tag " info: Links to Info nodes" org-info)
  654. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  655. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  656. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  657. (const :tag " mouse: Additional mouse support" org-mouse)
  658. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  659. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  660. (const :tag " tempo: Fast completion for structures" org-tempo)
  661. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  662. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  663. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  664. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  665. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  666. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  667. (const :tag "C collector: Collect properties into tables" org-collector)
  668. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  669. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  670. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  671. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  672. (const :tag "C eval: Include command output as text" org-eval)
  673. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  674. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  675. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  676. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  677. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  678. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  679. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  680. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  681. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  682. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  683. (const :tag "C notify: Notifications for Org-mode" org-notify)
  684. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  685. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  686. (const :tag "C registry: A registry for Org links" org-registry)
  687. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  688. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  689. (const :tag "C secretary: Team management with Org" org-secretary)
  690. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  691. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  692. (const :tag "C track: Keep up with Org mode development" org-track)
  693. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  694. (const :tag "C vm: Links to VM folders/messages" org-vm)
  695. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  696. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  697. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  698. (defvar org-export-registered-backends) ; From ox.el.
  699. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  700. (declare-function org-export-backend-name "ox" (backend) t)
  701. (defcustom org-export-backends '(ascii html icalendar latex odt)
  702. "List of export back-ends that should be always available.
  703. If a description starts with <C>, the file is not part of Emacs
  704. and loading it will require that you have downloaded and properly
  705. installed the Org mode distribution.
  706. Unlike to `org-modules', libraries in this list will not be
  707. loaded along with Org, but only once the export framework is
  708. needed.
  709. This variable needs to be set before org.el is loaded. If you
  710. need to make a change while Emacs is running, use the customize
  711. interface or run the following code, where VAL stands for the new
  712. value of the variable, after updating it:
  713. (progn
  714. (setq org-export-registered-backends
  715. (cl-remove-if-not
  716. (lambda (backend)
  717. (let ((name (org-export-backend-name backend)))
  718. (or (memq name val)
  719. (catch \\='parentp
  720. (dolist (b val)
  721. (and (org-export-derived-backend-p b name)
  722. (throw \\='parentp t)))))))
  723. org-export-registered-backends))
  724. (let ((new-list (mapcar #\\='org-export-backend-name
  725. org-export-registered-backends)))
  726. (dolist (backend val)
  727. (cond
  728. ((not (load (format \"ox-%s\" backend) t t))
  729. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  730. backend))
  731. ((not (memq backend new-list)) (push backend new-list))))
  732. (set-default \\='org-export-backends new-list)))
  733. Adding a back-end to this list will also pull the back-end it
  734. depends on, if any."
  735. :group 'org
  736. :group 'org-export
  737. :version "26.1"
  738. :package-version '(Org . "9.0")
  739. :initialize 'custom-initialize-set
  740. :set (lambda (var val)
  741. (if (not (featurep 'ox)) (set-default var val)
  742. ;; Any back-end not required anymore (not present in VAL and not
  743. ;; a parent of any back-end in the new value) is removed from the
  744. ;; list of registered back-ends.
  745. (setq org-export-registered-backends
  746. (cl-remove-if-not
  747. (lambda (backend)
  748. (let ((name (org-export-backend-name backend)))
  749. (or (memq name val)
  750. (catch 'parentp
  751. (dolist (b val)
  752. (and (org-export-derived-backend-p b name)
  753. (throw 'parentp t)))))))
  754. org-export-registered-backends))
  755. ;; Now build NEW-LIST of both new back-ends and required
  756. ;; parents.
  757. (let ((new-list (mapcar #'org-export-backend-name
  758. org-export-registered-backends)))
  759. (dolist (backend val)
  760. (cond
  761. ((not (load (format "ox-%s" backend) t t))
  762. (message "Problems while trying to load export back-end `%s'"
  763. backend))
  764. ((not (memq backend new-list)) (push backend new-list))))
  765. ;; Set VAR to that list with fixed dependencies.
  766. (set-default var new-list))))
  767. :type '(set :greedy t
  768. (const :tag " ascii Export buffer to ASCII format" ascii)
  769. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  770. (const :tag " html Export buffer to HTML format" html)
  771. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  772. (const :tag " latex Export buffer to LaTeX format" latex)
  773. (const :tag " man Export buffer to MAN format" man)
  774. (const :tag " md Export buffer to Markdown format" md)
  775. (const :tag " odt Export buffer to ODT format" odt)
  776. (const :tag " org Export buffer to Org format" org)
  777. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  778. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  779. (const :tag "C deck Export buffer to deck.js presentations" deck)
  780. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  781. (const :tag "C groff Export buffer to Groff format" groff)
  782. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  783. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  784. (const :tag "C s5 Export buffer to s5 presentations" s5)
  785. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  786. (eval-after-load 'ox
  787. '(dolist (backend org-export-backends)
  788. (condition-case nil (require (intern (format "ox-%s" backend)))
  789. (error (message "Problems while trying to load export back-end `%s'"
  790. backend)))))
  791. (defcustom org-support-shift-select nil
  792. "Non-nil means make shift-cursor commands select text when possible.
  793. \\<org-mode-map>\
  794. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  795. start selecting a region, or enlarge regions started in this way.
  796. In Org mode, in special contexts, these same keys are used for
  797. other purposes, important enough to compete with shift selection.
  798. Org tries to balance these needs by supporting `shift-select-mode'
  799. outside these special contexts, under control of this variable.
  800. The default of this variable is nil, to avoid confusing behavior. Shifted
  801. cursor keys will then execute Org commands in the following contexts:
  802. - on a headline, changing TODO state (left/right) and priority (up/down)
  803. - on a time stamp, changing the time
  804. - in a plain list item, changing the bullet type
  805. - in a property definition line, switching between allowed values
  806. - in the BEGIN line of a clock table (changing the time block).
  807. Outside these contexts, the commands will throw an error.
  808. When this variable is t and the cursor is not in a special
  809. context, Org mode will support shift-selection for making and
  810. enlarging regions. To make this more effective, the bullet
  811. cycling will no longer happen anywhere in an item line, but only
  812. if the cursor is exactly on the bullet.
  813. If you set this variable to the symbol `always', then the keys
  814. will not be special in headlines, property lines, and item lines,
  815. to make shift selection work there as well. If this is what you
  816. want, you can use the following alternative commands:
  817. `\\[org-todo]' and `\\[org-priority]' \
  818. to change TODO state and priority,
  819. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  820. can be used to switch TODO sets,
  821. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  822. and properties can be edited by hand or in column view.
  823. However, when the cursor is on a timestamp, shift-cursor commands
  824. will still edit the time stamp - this is just too good to give up."
  825. :group 'org
  826. :type '(choice
  827. (const :tag "Never" nil)
  828. (const :tag "When outside special context" t)
  829. (const :tag "Everywhere except timestamps" always)))
  830. (defcustom org-loop-over-headlines-in-active-region nil
  831. "Shall some commands act upon headlines in the active region?
  832. When set to t, some commands will be performed in all headlines
  833. within the active region.
  834. When set to `start-level', some commands will be performed in all
  835. headlines within the active region, provided that these headlines
  836. are of the same level than the first one.
  837. When set to a string, those commands will be performed on the
  838. matching headlines within the active region. Such string must be
  839. a tags/property/todo match as it is used in the agenda tags view.
  840. The list of commands is: `org-schedule', `org-deadline',
  841. `org-todo', `org-set-tags-command', `org-archive-subtree',
  842. `org-archive-set-tag', `org-toggle-archive-tag' and
  843. `org-archive-to-archive-sibling'. The archiving commands skip
  844. already archived entries."
  845. :type '(choice (const :tag "Don't loop" nil)
  846. (const :tag "All headlines in active region" t)
  847. (const :tag "In active region, headlines at the same level than the first one" start-level)
  848. (string :tag "Tags/Property/Todo matcher"))
  849. :version "24.1"
  850. :group 'org-todo
  851. :group 'org-archive)
  852. (defcustom org-startup-folded t
  853. "Non-nil means entering Org mode will switch to OVERVIEW.
  854. This can also be configured on a per-file basis by adding one of
  855. the following lines anywhere in the buffer:
  856. #+STARTUP: fold (or `overview', this is equivalent)
  857. #+STARTUP: nofold (or `showall', this is equivalent)
  858. #+STARTUP: content
  859. #+STARTUP: showeverything
  860. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  861. to ignore this option when Org opens agenda files for the first
  862. time."
  863. :group 'org-startup
  864. :type '(choice
  865. (const :tag "nofold: show all" nil)
  866. (const :tag "fold: overview" t)
  867. (const :tag "content: all headlines" content)
  868. (const :tag "show everything, even drawers" showeverything)))
  869. (defcustom org-startup-truncated t
  870. "Non-nil means entering Org mode will set `truncate-lines'.
  871. This is useful since some lines containing links can be very long and
  872. uninteresting. Also tables look terrible when wrapped.
  873. The variable `org-startup-truncated' allows to configure
  874. truncation for Org mode different to the other modes that use the
  875. variable `truncate-lines' and as a shortcut instead of putting
  876. the variable `truncate-lines' into the `org-mode-hook'. If one
  877. wants to configure truncation for Org mode not statically but
  878. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  879. the variable `truncate-lines' has to be used because in such a
  880. case it is too late to set the variable `org-startup-truncated'."
  881. :group 'org-startup
  882. :type 'boolean)
  883. (defcustom org-startup-indented nil
  884. "Non-nil means turn on `org-indent-mode' on startup.
  885. This can also be configured on a per-file basis by adding one of
  886. the following lines anywhere in the buffer:
  887. #+STARTUP: indent
  888. #+STARTUP: noindent"
  889. :group 'org-structure
  890. :type '(choice
  891. (const :tag "Not" nil)
  892. (const :tag "Globally (slow on startup in large files)" t)))
  893. (defcustom org-use-sub-superscripts t
  894. "Non-nil means interpret \"_\" and \"^\" for display.
  895. If you want to control how Org exports those characters, see
  896. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  897. used to be an alias for `org-export-with-sub-superscripts' in
  898. Org <8.0, it is not anymore.
  899. When this option is turned on, you can use TeX-like syntax for
  900. sub- and superscripts within the buffer. Several characters after
  901. \"_\" or \"^\" will be considered as a single item - so grouping
  902. with {} is normally not needed. For example, the following things
  903. will be parsed as single sub- or superscripts:
  904. 10^24 or 10^tau several digits will be considered 1 item.
  905. 10^-12 or 10^-tau a leading sign with digits or a word
  906. x^2-y^3 will be read as x^2 - y^3, because items are
  907. terminated by almost any nonword/nondigit char.
  908. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  909. Still, ambiguity is possible. So when in doubt, use {} to enclose
  910. the sub/superscript. If you set this variable to the symbol `{}',
  911. the braces are *required* in order to trigger interpretations as
  912. sub/superscript. This can be helpful in documents that need \"_\"
  913. frequently in plain text."
  914. :group 'org-startup
  915. :version "24.4"
  916. :package-version '(Org . "8.0")
  917. :type '(choice
  918. (const :tag "Always interpret" t)
  919. (const :tag "Only with braces" {})
  920. (const :tag "Never interpret" nil)))
  921. (defcustom org-startup-with-beamer-mode nil
  922. "Non-nil means turn on `org-beamer-mode' on startup.
  923. This can also be configured on a per-file basis by adding one of
  924. the following lines anywhere in the buffer:
  925. #+STARTUP: beamer"
  926. :group 'org-startup
  927. :version "24.1"
  928. :type 'boolean)
  929. (defcustom org-startup-align-all-tables nil
  930. "Non-nil means align all tables when visiting a file.
  931. This can also be configured on a per-file basis by adding one of
  932. the following lines anywhere in the buffer:
  933. #+STARTUP: align
  934. #+STARTUP: noalign"
  935. :group 'org-startup
  936. :type 'boolean)
  937. (defcustom org-startup-shrink-all-tables nil
  938. "Non-nil means shrink all table columns with a width cookie.
  939. This can also be configured on a per-file basis by adding one of
  940. the following lines anywhere in the buffer:
  941. #+STARTUP: shrink"
  942. :group 'org-startup
  943. :type 'boolean
  944. :version "27.1"
  945. :package-version '(Org . "9.2")
  946. :safe #'booleanp)
  947. (defcustom org-startup-with-inline-images nil
  948. "Non-nil means show inline images when loading a new Org file.
  949. This can also be configured on a per-file basis by adding one of
  950. the following lines anywhere in the buffer:
  951. #+STARTUP: inlineimages
  952. #+STARTUP: noinlineimages"
  953. :group 'org-startup
  954. :version "24.1"
  955. :type 'boolean)
  956. (defcustom org-startup-with-latex-preview nil
  957. "Non-nil means preview LaTeX fragments when loading a new Org file.
  958. This can also be configured on a per-file basis by adding one of
  959. the following lines anywhere in the buffer:
  960. #+STARTUP: latexpreview
  961. #+STARTUP: nolatexpreview"
  962. :group 'org-startup
  963. :version "24.4"
  964. :package-version '(Org . "8.0")
  965. :type 'boolean)
  966. (defcustom org-insert-mode-line-in-empty-file nil
  967. "Non-nil means insert the first line setting Org mode in empty files.
  968. When the function `org-mode' is called interactively in an empty file, this
  969. normally means that the file name does not automatically trigger Org mode.
  970. To ensure that the file will always be in Org mode in the future, a
  971. line enforcing Org mode will be inserted into the buffer, if this option
  972. has been set."
  973. :group 'org-startup
  974. :type 'boolean)
  975. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  976. (defcustom org-replace-disputed-keys nil
  977. "Non-nil means use alternative key bindings for some keys.
  978. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  979. These keys are also used by other packages like Shift Select mode,
  980. CUA mode or Windmove. If you want to use Org mode together with
  981. one of these other modes, or more generally if you would like to
  982. move some Org mode commands to other keys, set this variable and
  983. configure the keys with the variable `org-disputed-keys'.
  984. This option is only relevant at load-time of Org mode, and must be set
  985. *before* org.el is loaded. Changing it requires a restart of Emacs to
  986. become effective."
  987. :group 'org-startup
  988. :type 'boolean)
  989. (defcustom org-use-extra-keys nil
  990. "Non-nil means use extra key sequence definitions for certain commands.
  991. This happens automatically if `window-system' is nil. This
  992. variable lets you do the same manually. You must set it before
  993. loading Org."
  994. :group 'org-startup
  995. :type 'boolean)
  996. (defcustom org-disputed-keys
  997. '(([(shift up)] . [(meta p)])
  998. ([(shift down)] . [(meta n)])
  999. ([(shift left)] . [(meta -)])
  1000. ([(shift right)] . [(meta +)])
  1001. ([(control shift right)] . [(meta shift +)])
  1002. ([(control shift left)] . [(meta shift -)]))
  1003. "Keys for which Org mode and other modes compete.
  1004. This is an alist, cars are the default keys, second element specifies
  1005. the alternative to use when `org-replace-disputed-keys' is t.
  1006. Keys can be specified in any syntax supported by `define-key'.
  1007. The value of this option takes effect only at Org mode startup,
  1008. therefore you'll have to restart Emacs to apply it after changing."
  1009. :group 'org-startup
  1010. :type 'alist)
  1011. (defun org-key (key)
  1012. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  1013. Or return the original if not disputed."
  1014. (when org-replace-disputed-keys
  1015. (let* ((nkey (key-description key))
  1016. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  1017. org-disputed-keys)))
  1018. (setq key (if x (cdr x) key))))
  1019. key)
  1020. (defun org-defkey (keymap key def)
  1021. "Define a key, possibly translated, as returned by `org-key'."
  1022. (define-key keymap (org-key key) def))
  1023. (defcustom org-ellipsis nil
  1024. "The ellipsis to use in the Org mode outline.
  1025. When nil, just use the standard three dots. When a non-empty string,
  1026. use that string instead.
  1027. The change affects only Org mode (which will then use its own display table).
  1028. Changing this requires executing `\\[org-mode]' in a buffer to become
  1029. effective."
  1030. :group 'org-startup
  1031. :type '(choice (const :tag "Default" nil)
  1032. (string :tag "String" :value "...#"))
  1033. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  1034. (defvar org-display-table nil
  1035. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  1036. (defgroup org-keywords nil
  1037. "Keywords in Org mode."
  1038. :tag "Org Keywords"
  1039. :group 'org)
  1040. (defcustom org-closed-keep-when-no-todo nil
  1041. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1042. :group 'org-todo
  1043. :group 'org-keywords
  1044. :version "24.4"
  1045. :package-version '(Org . "8.0")
  1046. :type 'boolean)
  1047. (defgroup org-structure nil
  1048. "Options concerning the general structure of Org files."
  1049. :tag "Org Structure"
  1050. :group 'org)
  1051. (defgroup org-reveal-location nil
  1052. "Options about how to make context of a location visible."
  1053. :tag "Org Reveal Location"
  1054. :group 'org-structure)
  1055. (defcustom org-show-context-detail '((agenda . local)
  1056. (bookmark-jump . lineage)
  1057. (isearch . lineage)
  1058. (default . ancestors))
  1059. "Alist between context and visibility span when revealing a location.
  1060. \\<org-mode-map>Some actions may move point into invisible
  1061. locations. As a consequence, Org always expose a neighborhood
  1062. around point. How much is shown depends on the initial action,
  1063. or context. Valid contexts are
  1064. agenda when exposing an entry from the agenda
  1065. org-goto when using the command `org-goto' (`\\[org-goto]')
  1066. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1067. tags-tree when constructing a sparse tree based on tags matches
  1068. link-search when exposing search matches associated with a link
  1069. mark-goto when exposing the jump goal of a mark
  1070. bookmark-jump when exposing a bookmark location
  1071. isearch when exiting from an incremental search
  1072. default default for all contexts not set explicitly
  1073. Allowed visibility spans are
  1074. minimal show current headline; if point is not on headline,
  1075. also show entry
  1076. local show current headline, entry and next headline
  1077. ancestors show current headline and its direct ancestors; if
  1078. point is not on headline, also show entry
  1079. lineage show current headline, its direct ancestors and all
  1080. their children; if point is not on headline, also show
  1081. entry and first child
  1082. tree show current headline, its direct ancestors and all
  1083. their children; if point is not on headline, also show
  1084. entry and all children
  1085. canonical show current headline, its direct ancestors along with
  1086. their entries and children; if point is not located on
  1087. the headline, also show current entry and all children
  1088. As special cases, a nil or t value means show all contexts in
  1089. `minimal' or `canonical' view, respectively.
  1090. Some views can make displayed information very compact, but also
  1091. make it harder to edit the location of the match. In such
  1092. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1093. more context."
  1094. :group 'org-reveal-location
  1095. :version "26.1"
  1096. :package-version '(Org . "9.0")
  1097. :type '(choice
  1098. (const :tag "Canonical" t)
  1099. (const :tag "Minimal" nil)
  1100. (repeat :greedy t :tag "Individual contexts"
  1101. (cons
  1102. (choice :tag "Context"
  1103. (const agenda)
  1104. (const org-goto)
  1105. (const occur-tree)
  1106. (const tags-tree)
  1107. (const link-search)
  1108. (const mark-goto)
  1109. (const bookmark-jump)
  1110. (const isearch)
  1111. (const default))
  1112. (choice :tag "Detail level"
  1113. (const minimal)
  1114. (const local)
  1115. (const ancestors)
  1116. (const lineage)
  1117. (const tree)
  1118. (const canonical))))))
  1119. (defcustom org-indirect-buffer-display 'other-window
  1120. "How should indirect tree buffers be displayed?
  1121. This applies to indirect buffers created with the commands
  1122. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1123. Valid values are:
  1124. current-window Display in the current window
  1125. other-window Just display in another window.
  1126. dedicated-frame Create one new frame, and re-use it each time.
  1127. new-frame Make a new frame each time. Note that in this case
  1128. previously-made indirect buffers are kept, and you need to
  1129. kill these buffers yourself."
  1130. :group 'org-structure
  1131. :group 'org-agenda-windows
  1132. :type '(choice
  1133. (const :tag "In current window" current-window)
  1134. (const :tag "In current frame, other window" other-window)
  1135. (const :tag "Each time a new frame" new-frame)
  1136. (const :tag "One dedicated frame" dedicated-frame)))
  1137. (defcustom org-use-speed-commands nil
  1138. "Non-nil means activate single letter commands at beginning of a headline.
  1139. This may also be a function to test for appropriate locations where speed
  1140. commands should be active.
  1141. For example, to activate speed commands when the point is on any
  1142. star at the beginning of the headline, you can do this:
  1143. (setq org-use-speed-commands
  1144. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1145. :group 'org-structure
  1146. :type '(choice
  1147. (const :tag "Never" nil)
  1148. (const :tag "At beginning of headline stars" t)
  1149. (function)))
  1150. (defcustom org-speed-commands-user nil
  1151. "Alist of additional speed commands.
  1152. This list will be checked before `org-speed-commands-default'
  1153. when the variable `org-use-speed-commands' is non-nil
  1154. and when the cursor is at the beginning of a headline.
  1155. The car of each entry is a string with a single letter, which must
  1156. be assigned to `self-insert-command' in the global map.
  1157. The cdr is either a command to be called interactively, a function
  1158. to be called, or a form to be evaluated.
  1159. An entry that is just a list with a single string will be interpreted
  1160. as a descriptive headline that will be added when listing the speed
  1161. commands in the Help buffer using the `?' speed command."
  1162. :group 'org-structure
  1163. :type '(repeat :value ("k" . ignore)
  1164. (choice :value ("k" . ignore)
  1165. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1166. (cons :tag "Letter and Command"
  1167. (string :tag "Command letter")
  1168. (choice
  1169. (function)
  1170. (sexp))))))
  1171. (defcustom org-bookmark-names-plist
  1172. '(:last-capture "org-capture-last-stored"
  1173. :last-refile "org-refile-last-stored"
  1174. :last-capture-marker "org-capture-last-stored-marker")
  1175. "Names for bookmarks automatically set by some Org commands.
  1176. This can provide strings as names for a number of bookmarks Org sets
  1177. automatically. The following keys are currently implemented:
  1178. :last-capture
  1179. :last-capture-marker
  1180. :last-refile
  1181. When a key does not show up in the property list, the corresponding bookmark
  1182. is not set."
  1183. :group 'org-structure
  1184. :type 'plist)
  1185. (defgroup org-cycle nil
  1186. "Options concerning visibility cycling in Org mode."
  1187. :tag "Org Cycle"
  1188. :group 'org-structure)
  1189. (defcustom org-cycle-skip-children-state-if-no-children t
  1190. "Non-nil means skip CHILDREN state in entries that don't have any."
  1191. :group 'org-cycle
  1192. :type 'boolean)
  1193. (defcustom org-cycle-max-level nil
  1194. "Maximum level which should still be subject to visibility cycling.
  1195. Levels higher than this will, for cycling, be treated as text, not a headline.
  1196. When `org-odd-levels-only' is set, a value of N in this variable actually
  1197. means 2N-1 stars as the limiting headline.
  1198. When nil, cycle all levels.
  1199. Note that the limiting level of cycling is also influenced by
  1200. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1201. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1202. than its value."
  1203. :group 'org-cycle
  1204. :type '(choice
  1205. (const :tag "No limit" nil)
  1206. (integer :tag "Maximum level")))
  1207. (defcustom org-hide-block-startup nil
  1208. "Non-nil means entering Org mode will fold all blocks.
  1209. This can also be set in on a per-file basis with
  1210. #+STARTUP: hideblocks
  1211. #+STARTUP: showblocks"
  1212. :group 'org-startup
  1213. :group 'org-cycle
  1214. :type 'boolean)
  1215. (defcustom org-cycle-global-at-bob nil
  1216. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1217. This makes it possible to do global cycling without having to use `S-TAB'
  1218. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1219. line of the buffer
  1220. must not be a headline -- it may be empty or some other text.
  1221. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1222. sure the cursor stays at the beginning of the buffer.
  1223. When this option is nil, don't do anything special at the beginning of
  1224. the buffer."
  1225. :group 'org-cycle
  1226. :type 'boolean)
  1227. (defcustom org-cycle-level-after-item/entry-creation t
  1228. "Non-nil means cycle entry level or item indentation in new empty entries.
  1229. When the cursor is at the end of an empty headline, i.e., with only stars
  1230. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1231. and then all possible ancestor states, before returning to the original state.
  1232. This makes data entry extremely fast: M-RET to create a new headline,
  1233. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1234. When the cursor is at the end of an empty plain list item, one TAB will
  1235. make it a subitem, two or more tabs will back up to make this an item
  1236. higher up in the item hierarchy."
  1237. :group 'org-cycle
  1238. :type 'boolean)
  1239. (defcustom org-cycle-emulate-tab t
  1240. "Where should `org-cycle' emulate TAB.
  1241. nil Never
  1242. white Only in completely white lines
  1243. whitestart Only at the beginning of lines, before the first non-white char
  1244. t Everywhere except in headlines
  1245. exc-hl-bol Everywhere except at the start of a headline
  1246. If TAB is used in a place where it does not emulate TAB, the current subtree
  1247. visibility is cycled."
  1248. :group 'org-cycle
  1249. :type '(choice (const :tag "Never" nil)
  1250. (const :tag "Only in completely white lines" white)
  1251. (const :tag "Before first char in a line" whitestart)
  1252. (const :tag "Everywhere except in headlines" t)
  1253. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1254. (defcustom org-cycle-separator-lines 2
  1255. "Number of empty lines needed to keep an empty line between collapsed trees.
  1256. If you leave an empty line between the end of a subtree and the following
  1257. headline, this empty line is hidden when the subtree is folded.
  1258. Org mode will leave (exactly) one empty line visible if the number of
  1259. empty lines is equal or larger to the number given in this variable.
  1260. So the default 2 means at least 2 empty lines after the end of a subtree
  1261. are needed to produce free space between a collapsed subtree and the
  1262. following headline.
  1263. If the number is negative, and the number of empty lines is at least -N,
  1264. all empty lines are shown.
  1265. Special case: when 0, never leave empty lines in collapsed view."
  1266. :group 'org-cycle
  1267. :type 'integer)
  1268. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1269. (defcustom org-pre-cycle-hook nil
  1270. "Hook that is run before visibility cycling is happening.
  1271. The function(s) in this hook must accept a single argument which indicates
  1272. the new state that will be set right after running this hook. The
  1273. argument is a symbol. Before a global state change, it can have the values
  1274. `overview', `content', or `all'. Before a local state change, it can have
  1275. the values `folded', `children', or `subtree'."
  1276. :group 'org-cycle
  1277. :type 'hook)
  1278. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1279. org-cycle-show-empty-lines
  1280. org-optimize-window-after-visibility-change)
  1281. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1282. The function(s) in this hook must accept a single argument which indicates
  1283. the new state that was set by the most recent `org-cycle' command. The
  1284. argument is a symbol. After a global state change, it can have the values
  1285. `overview', `contents', or `all'. After a local state change, it can have
  1286. the values `folded', `children', or `subtree'."
  1287. :group 'org-cycle
  1288. :type 'hook
  1289. :version "26.1"
  1290. :package-version '(Org . "8.3"))
  1291. (defgroup org-edit-structure nil
  1292. "Options concerning structure editing in Org mode."
  1293. :tag "Org Edit Structure"
  1294. :group 'org-structure)
  1295. (defcustom org-odd-levels-only nil
  1296. "Non-nil means skip even levels and only use odd levels for the outline.
  1297. This has the effect that two stars are being added/taken away in
  1298. promotion/demotion commands. It also influences how levels are
  1299. handled by the exporters.
  1300. Changing it requires restart of `font-lock-mode' to become effective
  1301. for fontification also in regions already fontified.
  1302. You may also set this on a per-file basis by adding one of the following
  1303. lines to the buffer:
  1304. #+STARTUP: odd
  1305. #+STARTUP: oddeven"
  1306. :group 'org-edit-structure
  1307. :group 'org-appearance
  1308. :type 'boolean)
  1309. (defcustom org-adapt-indentation t
  1310. "Non-nil means adapt indentation to outline node level.
  1311. When this variable is set, Org assumes that you write outlines by
  1312. indenting text in each node to align with the headline (after the
  1313. stars). The following issues are influenced by this variable:
  1314. - The indentation is increased by one space in a demotion
  1315. command, and decreased by one in a promotion command. However,
  1316. in the latter case, if shifting some line in the entry body
  1317. would alter document structure (e.g., insert a new headline),
  1318. indentation is not changed at all.
  1319. - Property drawers and planning information is inserted indented
  1320. when this variable is set. When nil, they will not be indented.
  1321. - TAB indents a line relative to current level. The lines below
  1322. a headline will be indented when this variable is set.
  1323. Note that this is all about true indentation, by adding and
  1324. removing space characters. See also \"org-indent.el\" which does
  1325. level-dependent indentation in a virtual way, i.e. at display
  1326. time in Emacs."
  1327. :group 'org-edit-structure
  1328. :type 'boolean
  1329. :safe #'booleanp)
  1330. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1331. (defcustom org-special-ctrl-a/e nil
  1332. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1333. When t, `C-a' will bring back the cursor to the beginning of the
  1334. headline text, i.e. after the stars and after a possible TODO
  1335. keyword. In an item, this will be the position after bullet and
  1336. check-box, if any. When the cursor is already at that position,
  1337. another `C-a' will bring it to the beginning of the line.
  1338. `C-e' will jump to the end of the headline, ignoring the presence
  1339. of tags in the headline. A second `C-e' will then jump to the
  1340. true end of the line, after any tags. This also means that, when
  1341. this variable is non-nil, `C-e' also will never jump beyond the
  1342. end of the heading of a folded section, i.e. not after the
  1343. ellipses.
  1344. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1345. normally, going to the true line boundary first. Only a directly
  1346. following, identical keypress will bring the cursor to the
  1347. special positions.
  1348. This may also be a cons cell where the behavior for `C-a' and
  1349. `C-e' is set separately."
  1350. :group 'org-edit-structure
  1351. :type '(choice
  1352. (const :tag "off" nil)
  1353. (const :tag "on: after stars/bullet and before tags first" t)
  1354. (const :tag "reversed: true line boundary first" reversed)
  1355. (cons :tag "Set C-a and C-e separately"
  1356. (choice :tag "Special C-a"
  1357. (const :tag "off" nil)
  1358. (const :tag "on: after stars/bullet first" t)
  1359. (const :tag "reversed: before stars/bullet first" reversed))
  1360. (choice :tag "Special C-e"
  1361. (const :tag "off" nil)
  1362. (const :tag "on: before tags first" t)
  1363. (const :tag "reversed: after tags first" reversed)))))
  1364. (defcustom org-special-ctrl-k nil
  1365. "Non-nil means `C-k' will behave specially in headlines.
  1366. When nil, `C-k' will call the default `kill-line' command.
  1367. When t, the following will happen while the cursor is in the headline:
  1368. - When the cursor is at the beginning of a headline, kill the entire
  1369. line and possible the folded subtree below the line.
  1370. - When in the middle of the headline text, kill the headline up to the tags.
  1371. - When after the headline text, kill the tags."
  1372. :group 'org-edit-structure
  1373. :type 'boolean)
  1374. (defcustom org-ctrl-k-protect-subtree nil
  1375. "Non-nil means, do not delete a hidden subtree with C-k.
  1376. When set to the symbol `error', simply throw an error when C-k is
  1377. used to kill (part-of) a headline that has hidden text behind it.
  1378. Any other non-nil value will result in a query to the user, if it is
  1379. OK to kill that hidden subtree. When nil, kill without remorse."
  1380. :group 'org-edit-structure
  1381. :version "24.1"
  1382. :type '(choice
  1383. (const :tag "Do not protect hidden subtrees" nil)
  1384. (const :tag "Protect hidden subtrees with a security query" t)
  1385. (const :tag "Never kill a hidden subtree with C-k" error)))
  1386. (defcustom org-special-ctrl-o t
  1387. "Non-nil means, make `C-o' insert a row in tables."
  1388. :group 'org-edit-structure
  1389. :type 'boolean)
  1390. (defcustom org-catch-invisible-edits nil
  1391. "Check if in invisible region before inserting or deleting a character.
  1392. Valid values are:
  1393. nil Do not check, so just do invisible edits.
  1394. error Throw an error and do nothing.
  1395. show Make point visible, and do the requested edit.
  1396. show-and-error Make point visible, then throw an error and abort the edit.
  1397. smart Make point visible, and do insertion/deletion if it is
  1398. adjacent to visible text and the change feels predictable.
  1399. Never delete a previously invisible character or add in the
  1400. middle or right after an invisible region. Basically, this
  1401. allows insertion and backward-delete right before ellipses.
  1402. FIXME: maybe in this case we should not even show?"
  1403. :group 'org-edit-structure
  1404. :version "24.1"
  1405. :type '(choice
  1406. (const :tag "Do not check" nil)
  1407. (const :tag "Throw error when trying to edit" error)
  1408. (const :tag "Unhide, but do not do the edit" show-and-error)
  1409. (const :tag "Show invisible part and do the edit" show)
  1410. (const :tag "Be smart and do the right thing" smart)))
  1411. (defcustom org-yank-folded-subtrees t
  1412. "Non-nil means when yanking subtrees, fold them.
  1413. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1414. it starts with a heading and all other headings in it are either children
  1415. or siblings, then fold all the subtrees. However, do this only if no
  1416. text after the yank would be swallowed into a folded tree by this action."
  1417. :group 'org-edit-structure
  1418. :type 'boolean)
  1419. (defcustom org-yank-adjusted-subtrees nil
  1420. "Non-nil means when yanking subtrees, adjust the level.
  1421. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1422. this function for details."
  1423. :group 'org-edit-structure
  1424. :type 'boolean)
  1425. (defcustom org-M-RET-may-split-line '((default . t))
  1426. "Non-nil means M-RET will split the line at the cursor position.
  1427. When nil, it will go to the end of the line before making a
  1428. new line.
  1429. You may also set this option in a different way for different
  1430. contexts. Valid contexts are:
  1431. headline when creating a new headline
  1432. item when creating a new item
  1433. table in a table field
  1434. default the value to be used for all contexts not explicitly
  1435. customized"
  1436. :group 'org-structure
  1437. :group 'org-table
  1438. :type '(choice
  1439. (const :tag "Always" t)
  1440. (const :tag "Never" nil)
  1441. (repeat :greedy t :tag "Individual contexts"
  1442. (cons
  1443. (choice :tag "Context"
  1444. (const headline)
  1445. (const item)
  1446. (const table)
  1447. (const default))
  1448. (boolean)))))
  1449. (defcustom org-insert-heading-respect-content nil
  1450. "Non-nil means insert new headings after the current subtree.
  1451. \\<org-mode-map>
  1452. When nil, the new heading is created directly after the current line.
  1453. The commands `\\[org-insert-heading-respect-content]' and \
  1454. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1455. for the duration of the command."
  1456. :group 'org-structure
  1457. :type 'boolean)
  1458. (defcustom org-blank-before-new-entry '((heading . auto)
  1459. (plain-list-item . auto))
  1460. "Should `org-insert-heading' leave a blank line before new heading/item?
  1461. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1462. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1463. which case Org will look at the surrounding headings/items and try to
  1464. make an intelligent decision whether to insert a blank line or not."
  1465. :group 'org-edit-structure
  1466. :type '(list
  1467. (cons (const heading)
  1468. (choice (const :tag "Never" nil)
  1469. (const :tag "Always" t)
  1470. (const :tag "Auto" auto)))
  1471. (cons (const plain-list-item)
  1472. (choice (const :tag "Never" nil)
  1473. (const :tag "Always" t)
  1474. (const :tag "Auto" auto)))))
  1475. (defcustom org-insert-heading-hook nil
  1476. "Hook being run after inserting a new heading."
  1477. :group 'org-edit-structure
  1478. :type 'hook)
  1479. (defcustom org-enable-fixed-width-editor t
  1480. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1481. This currently only means they are never auto-wrapped.
  1482. When nil, such lines will be treated like ordinary lines."
  1483. :group 'org-edit-structure
  1484. :type 'boolean)
  1485. (defgroup org-sparse-trees nil
  1486. "Options concerning sparse trees in Org mode."
  1487. :tag "Org Sparse Trees"
  1488. :group 'org-structure)
  1489. (defcustom org-highlight-sparse-tree-matches t
  1490. "Non-nil means highlight all matches that define a sparse tree.
  1491. The highlights will automatically disappear the next time the buffer is
  1492. changed by an edit command."
  1493. :group 'org-sparse-trees
  1494. :type 'boolean)
  1495. (defcustom org-remove-highlights-with-change t
  1496. "Non-nil means any change to the buffer will remove temporary highlights.
  1497. \\<org-mode-map>\
  1498. Such highlights are created by `org-occur' and `org-clock-display'.
  1499. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1500. to get rid of the highlights.
  1501. The highlights created by `org-toggle-latex-fragment' always need
  1502. `\\[org-toggle-latex-fragment]' to be removed."
  1503. :group 'org-sparse-trees
  1504. :group 'org-time
  1505. :type 'boolean)
  1506. (defcustom org-occur-case-fold-search t
  1507. "Non-nil means `org-occur' should be case-insensitive.
  1508. If set to `smart' the search will be case-insensitive only if it
  1509. doesn't specify any upper case character."
  1510. :group 'org-sparse-trees
  1511. :version "26.1"
  1512. :type '(choice
  1513. (const :tag "Case-sensitive" nil)
  1514. (const :tag "Case-insensitive" t)
  1515. (const :tag "Case-insensitive for lower case searches only" smart)))
  1516. (defcustom org-occur-hook '(org-first-headline-recenter)
  1517. "Hook that is run after `org-occur' has constructed a sparse tree.
  1518. This can be used to recenter the window to show as much of the structure
  1519. as possible."
  1520. :group 'org-sparse-trees
  1521. :type 'hook)
  1522. (defgroup org-table nil
  1523. "Options concerning tables in Org mode."
  1524. :tag "Org Table"
  1525. :group 'org)
  1526. (defcustom org-self-insert-cluster-for-undo nil
  1527. "Non-nil means cluster self-insert commands for undo when possible.
  1528. If this is set, then, like in the Emacs command loop, 20 consecutive
  1529. characters will be undone together.
  1530. This is configurable, because there is some impact on typing performance."
  1531. :group 'org-table
  1532. :type 'boolean)
  1533. (defcustom org-table-tab-recognizes-table.el t
  1534. "Non-nil means TAB will automatically notice a table.el table.
  1535. When it sees such a table, it moves point into it and - if necessary -
  1536. calls `table-recognize-table'."
  1537. :group 'org-table-editing
  1538. :type 'boolean)
  1539. (defgroup org-link nil
  1540. "Options concerning links in Org mode."
  1541. :tag "Org Link"
  1542. :group 'org)
  1543. (defvar-local org-link-abbrev-alist-local nil
  1544. "Buffer-local version of `org-link-abbrev-alist', which see.
  1545. The value of this is taken from the #+LINK lines.")
  1546. (defcustom org-link-parameters
  1547. '(("doi" :follow org--open-doi-link)
  1548. ("elisp" :follow org--open-elisp-link)
  1549. ("file" :complete org-file-complete-link)
  1550. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1551. ("help" :follow org--open-help-link)
  1552. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1553. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1554. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1555. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1556. ("shell" :follow org--open-shell-link))
  1557. "An alist of properties that defines all the links in Org mode.
  1558. The key in each association is a string of the link type.
  1559. Subsequent optional elements make up a p-list of link properties.
  1560. :follow - A function that takes the link path as an argument.
  1561. :export - A function that takes the link path, description and
  1562. export-backend as arguments.
  1563. :store - A function responsible for storing the link. See the
  1564. function `org-store-link-functions'.
  1565. :complete - A function that inserts a link with completion. The
  1566. function takes one optional prefix arg.
  1567. :face - A face for the link, or a function that returns a face.
  1568. The function takes one argument which is the link path. The
  1569. default face is `org-link'.
  1570. :mouse-face - The mouse-face. The default is `highlight'.
  1571. :display - `full' will not fold the link in descriptive
  1572. display. Default is `org-link'.
  1573. :help-echo - A string or function that takes (window object position)
  1574. as arguments and returns a string.
  1575. :keymap - A keymap that is active on the link. The default is
  1576. `org-mouse-map'.
  1577. :htmlize-link - A function for the htmlize-link. Defaults
  1578. to (list :uri \"type:path\")
  1579. :activate-func - A function to run at the end of font-lock
  1580. activation. The function must accept (link-start link-end path bracketp)
  1581. as arguments."
  1582. :group 'org-link
  1583. :type '(alist :tag "Link display parameters"
  1584. :value-type plist)
  1585. :version "26.1"
  1586. :package-version '(Org . "9.1"))
  1587. (defun org-link-get-parameter (type key)
  1588. "Get TYPE link property for KEY.
  1589. TYPE is a string and KEY is a plist keyword."
  1590. (plist-get
  1591. (cdr (assoc type org-link-parameters))
  1592. key))
  1593. (defun org-link-set-parameters (type &rest parameters)
  1594. "Set link TYPE properties to PARAMETERS.
  1595. PARAMETERS should be :key val pairs."
  1596. (let ((data (assoc type org-link-parameters)))
  1597. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1598. (push (cons type parameters) org-link-parameters)
  1599. (org-make-link-regexps)
  1600. (org-element-update-syntax))))
  1601. (defun org-link-types ()
  1602. "Return a list of known link types."
  1603. (mapcar #'car org-link-parameters))
  1604. (defcustom org-link-abbrev-alist nil
  1605. "Alist of link abbreviations.
  1606. The car of each element is a string, to be replaced at the start of a link.
  1607. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1608. links in Org buffers can have an optional tag after a double colon, e.g.,
  1609. [[linkkey:tag][description]]
  1610. The `linkkey' must be a single word, starting with a letter, followed
  1611. by letters, numbers, `-' or `_'.
  1612. If REPLACE is a string, the tag will simply be appended to create the link.
  1613. If the string contains \"%s\", the tag will be inserted there. If the string
  1614. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1615. at that point (see the function `url-hexify-string'). If the string contains
  1616. the specifier \"%(my-function)\", then the custom function `my-function' will
  1617. be invoked: this function takes the tag as its only argument and must return
  1618. a string.
  1619. REPLACE may also be a function that will be called with the tag as the
  1620. only argument to create the link, which should be returned as a string.
  1621. See the manual for examples."
  1622. :group 'org-link
  1623. :type '(repeat
  1624. (cons
  1625. (string :tag "Protocol")
  1626. (choice
  1627. (string :tag "Format")
  1628. (function)))))
  1629. (defcustom org-descriptive-links t
  1630. "Non-nil means Org will display descriptive links.
  1631. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1632. \"Org Website\", hiding the link itself and just displaying its
  1633. description. When set to nil, Org will display the full links
  1634. literally.
  1635. You can interactively set the value of this variable by calling
  1636. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1637. :group 'org-link
  1638. :type 'boolean)
  1639. (defcustom org-link-file-path-type 'adaptive
  1640. "How the path name in file links should be stored.
  1641. Valid values are:
  1642. relative Relative to the current directory, i.e. the directory of the file
  1643. into which the link is being inserted.
  1644. absolute Absolute path, if possible with ~ for home directory.
  1645. noabbrev Absolute path, no abbreviation of home directory.
  1646. adaptive Use relative path for files in the current directory and sub-
  1647. directories of it. For other files, use an absolute path."
  1648. :group 'org-link
  1649. :type '(choice
  1650. (const relative)
  1651. (const absolute)
  1652. (const noabbrev)
  1653. (const adaptive)))
  1654. (defvaralias 'org-activate-links 'org-highlight-links)
  1655. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1656. "Types of links that should be highlighted in Org files.
  1657. This is a list of symbols, each one of them leading to the
  1658. highlighting of a certain link type.
  1659. You can still open links that are not highlighted.
  1660. In principle, it does not hurt to turn on highlighting for all
  1661. link types. There may be a small gain when turning off unused
  1662. link types. The types are:
  1663. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1664. angle Links in angular brackets that may contain whitespace like
  1665. <bbdb:Carsten Dominik>.
  1666. plain Plain links in normal text, no whitespace, like http://google.com.
  1667. radio Text that is matched by a radio target, see manual for details.
  1668. tag Tag settings in a headline (link to tag search).
  1669. date Time stamps (link to calendar).
  1670. footnote Footnote labels.
  1671. If you set this variable during an Emacs session, use `org-mode-restart'
  1672. in the Org buffer so that the change takes effect."
  1673. :group 'org-link
  1674. :group 'org-appearance
  1675. :type '(set :greedy t
  1676. (const :tag "Double bracket links" bracket)
  1677. (const :tag "Angular bracket links" angle)
  1678. (const :tag "Plain text links" plain)
  1679. (const :tag "Radio target matches" radio)
  1680. (const :tag "Tags" tag)
  1681. (const :tag "Timestamps" date)
  1682. (const :tag "Footnotes" footnote)))
  1683. (defcustom org-make-link-description-function nil
  1684. "Function to use for generating link descriptions from links.
  1685. This function must take two parameters: the first one is the
  1686. link, the second one is the description generated by
  1687. `org-insert-link'. The function should return the description to
  1688. use."
  1689. :group 'org-link
  1690. :type '(choice (const nil) (function)))
  1691. (defgroup org-link-store nil
  1692. "Options concerning storing links in Org mode."
  1693. :tag "Org Store Link"
  1694. :group 'org-link)
  1695. (defcustom org-url-hexify-p t
  1696. "When non-nil, hexify URL when creating a link."
  1697. :type 'boolean
  1698. :version "24.3"
  1699. :group 'org-link-store)
  1700. (defcustom org-email-link-description-format "Email %c: %.30s"
  1701. "Format of the description part of a link to an email or usenet message.
  1702. The following %-escapes will be replaced by corresponding information:
  1703. %F full \"From\" field
  1704. %f name, taken from \"From\" field, address if no name
  1705. %T full \"To\" field
  1706. %t first name in \"To\" field, address if no name
  1707. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1708. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1709. %s subject
  1710. %d date
  1711. %m message-id.
  1712. You may use normal field width specification between the % and the letter.
  1713. This is for example useful to limit the length of the subject.
  1714. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1715. :group 'org-link-store
  1716. :type 'string)
  1717. (defcustom org-from-is-user-regexp
  1718. (let (r1 r2)
  1719. (when (and user-mail-address (not (string= user-mail-address "")))
  1720. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1721. (when (and user-full-name (not (string= user-full-name "")))
  1722. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1723. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1724. "Regexp matched against the \"From:\" header of an email or usenet message.
  1725. It should match if the message is from the user him/herself."
  1726. :group 'org-link-store
  1727. :type 'regexp)
  1728. (defcustom org-context-in-file-links t
  1729. "Non-nil means file links from `org-store-link' contain context.
  1730. \\<org-mode-map>
  1731. A search string will be added to the file name with :: as separator
  1732. and used to find the context when the link is activated by the command
  1733. `org-open-at-point'. When this option is t, the entire active region
  1734. will be placed in the search string of the file link. If set to a
  1735. positive integer, only the first n lines of context will be stored.
  1736. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1737. \\[org-store-link]')
  1738. negates this setting for the duration of the command."
  1739. :group 'org-link-store
  1740. :type '(choice boolean integer))
  1741. (defcustom org-keep-stored-link-after-insertion nil
  1742. "Non-nil means keep link in list for entire session.
  1743. \\<org-mode-map>
  1744. The command `org-store-link' adds a link pointing to the current
  1745. location to an internal list. These links accumulate during a session.
  1746. The command `org-insert-link' can be used to insert links into any
  1747. Org file (offering completion for all stored links).
  1748. When this option is nil, every link which has been inserted once using
  1749. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1750. unused
  1751. links more efficient."
  1752. :group 'org-link-store
  1753. :type 'boolean)
  1754. (defgroup org-link-follow nil
  1755. "Options concerning following links in Org mode."
  1756. :tag "Org Follow Link"
  1757. :group 'org-link)
  1758. (defcustom org-link-translation-function nil
  1759. "Function to translate links with different syntax to Org syntax.
  1760. This can be used to translate links created for example by the Planner
  1761. or emacs-wiki packages to Org syntax.
  1762. The function must accept two parameters, a TYPE containing the link
  1763. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1764. which is everything after the link protocol. It should return a cons
  1765. with possibly modified values of type and path.
  1766. Org contains a function for this, so if you set this variable to
  1767. `org-translate-link-from-planner', you should be able follow many
  1768. links created by planner."
  1769. :group 'org-link-follow
  1770. :type '(choice (const nil) (function)))
  1771. (defcustom org-follow-link-hook nil
  1772. "Hook that is run after a link has been followed."
  1773. :group 'org-link-follow
  1774. :type 'hook)
  1775. (defcustom org-tab-follows-link nil
  1776. "Non-nil means on links TAB will follow the link.
  1777. Needs to be set before org.el is loaded.
  1778. This really should not be used, it does not make sense, and the
  1779. implementation is bad."
  1780. :group 'org-link-follow
  1781. :type 'boolean)
  1782. (defcustom org-return-follows-link nil
  1783. "Non-nil means on links RET will follow the link.
  1784. In tables, the special behavior of RET has precedence."
  1785. :group 'org-link-follow
  1786. :type 'boolean)
  1787. (defcustom org-mouse-1-follows-link
  1788. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1789. "Non-nil means mouse-1 on a link will follow the link.
  1790. A longer mouse click will still set point. Needs to be set
  1791. before org.el is loaded."
  1792. :group 'org-link-follow
  1793. :version "26.1"
  1794. :package-version '(Org . "8.3")
  1795. :type '(choice
  1796. (const :tag "A double click follows the link" double)
  1797. (const :tag "Unconditionally follow the link with mouse-1" t)
  1798. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1799. (defcustom org-mark-ring-length 4
  1800. "Number of different positions to be recorded in the ring.
  1801. Changing this requires a restart of Emacs to work correctly."
  1802. :group 'org-link-follow
  1803. :type 'integer)
  1804. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1805. "Non-nil means internal fuzzy links can only match headlines.
  1806. When nil, the a fuzzy link may point to a target or a named
  1807. construct in the document. When set to the special value
  1808. `query-to-create', offer to create a new headline when none
  1809. matched.
  1810. Spaces and statistics cookies are ignored during heading searches."
  1811. :group 'org-link-follow
  1812. :version "24.1"
  1813. :type '(choice
  1814. (const :tag "Use fuzzy text search" nil)
  1815. (const :tag "Match only exact headline" t)
  1816. (const :tag "Match exact headline or query to create it"
  1817. query-to-create))
  1818. :safe #'symbolp)
  1819. (defcustom org-link-frame-setup
  1820. '((vm . vm-visit-folder-other-frame)
  1821. (vm-imap . vm-visit-imap-folder-other-frame)
  1822. (gnus . org-gnus-no-new-news)
  1823. (file . find-file-other-window)
  1824. (wl . wl-other-frame))
  1825. "Setup the frame configuration for following links.
  1826. When following a link with Emacs, it may often be useful to display
  1827. this link in another window or frame. This variable can be used to
  1828. set this up for the different types of links.
  1829. For VM, use any of
  1830. `vm-visit-folder'
  1831. `vm-visit-folder-other-window'
  1832. `vm-visit-folder-other-frame'
  1833. For Gnus, use any of
  1834. `gnus'
  1835. `gnus-other-frame'
  1836. `org-gnus-no-new-news'
  1837. For FILE, use any of
  1838. `find-file'
  1839. `find-file-other-window'
  1840. `find-file-other-frame'
  1841. For Wanderlust use any of
  1842. `wl'
  1843. `wl-other-frame'
  1844. For the calendar, use the variable `calendar-setup'.
  1845. For BBDB, it is currently only possible to display the matches in
  1846. another window."
  1847. :group 'org-link-follow
  1848. :type '(list
  1849. (cons (const vm)
  1850. (choice
  1851. (const vm-visit-folder)
  1852. (const vm-visit-folder-other-window)
  1853. (const vm-visit-folder-other-frame)))
  1854. (cons (const vm-imap)
  1855. (choice
  1856. (const vm-visit-imap-folder)
  1857. (const vm-visit-imap-folder-other-window)
  1858. (const vm-visit-imap-folder-other-frame)))
  1859. (cons (const gnus)
  1860. (choice
  1861. (const gnus)
  1862. (const gnus-other-frame)
  1863. (const org-gnus-no-new-news)))
  1864. (cons (const file)
  1865. (choice
  1866. (const find-file)
  1867. (const find-file-other-window)
  1868. (const find-file-other-frame)))
  1869. (cons (const wl)
  1870. (choice
  1871. (const wl)
  1872. (const wl-other-frame)))))
  1873. (defcustom org-display-internal-link-with-indirect-buffer nil
  1874. "Non-nil means use indirect buffer to display infile links.
  1875. Activating internal links (from one location in a file to another location
  1876. in the same file) normally just jumps to the location. When the link is
  1877. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1878. is displayed in
  1879. another window. When this option is set, the other window actually displays
  1880. an indirect buffer clone of the current buffer, to avoid any visibility
  1881. changes to the current buffer."
  1882. :group 'org-link-follow
  1883. :type 'boolean)
  1884. (defcustom org-open-non-existing-files nil
  1885. "Non-nil means `org-open-file' will open non-existing files.
  1886. When nil, an error will be generated.
  1887. This variable applies only to external applications because they
  1888. might choke on non-existing files. If the link is to a file that
  1889. will be opened in Emacs, the variable is ignored."
  1890. :group 'org-link-follow
  1891. :type 'boolean)
  1892. (defcustom org-open-directory-means-index-dot-org nil
  1893. "Non-nil means a link to a directory really means to index.org.
  1894. When nil, following a directory link will run dired or open a finder/explorer
  1895. window on that directory."
  1896. :group 'org-link-follow
  1897. :type 'boolean)
  1898. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1899. "Non-nil means ask for confirmation before executing shell links.
  1900. Shell links can be dangerous: just think about a link
  1901. [[shell:rm -rf ~/*][Google Search]]
  1902. This link would show up in your Org document as \"Google Search\",
  1903. but really it would remove your entire home directory.
  1904. Therefore we advise against setting this variable to nil.
  1905. Just change it to `y-or-n-p' if you want to confirm with a
  1906. single keystroke rather than having to type \"yes\"."
  1907. :group 'org-link-follow
  1908. :type '(choice
  1909. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1910. (const :tag "with y-or-n (faster)" y-or-n-p)
  1911. (const :tag "no confirmation (dangerous)" nil)))
  1912. (put 'org-confirm-shell-link-function
  1913. 'safe-local-variable
  1914. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1915. (defcustom org-confirm-shell-link-not-regexp ""
  1916. "A regexp to skip confirmation for shell links."
  1917. :group 'org-link-follow
  1918. :version "24.1"
  1919. :type 'regexp)
  1920. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1921. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1922. Elisp links can be dangerous: just think about a link
  1923. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1924. This link would show up in your Org document as \"Google Search\",
  1925. but really it would remove your entire home directory.
  1926. Therefore we advise against setting this variable to nil.
  1927. Just change it to `y-or-n-p' if you want to confirm with a
  1928. single keystroke rather than having to type \"yes\"."
  1929. :group 'org-link-follow
  1930. :type '(choice
  1931. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1932. (const :tag "with y-or-n (faster)" y-or-n-p)
  1933. (const :tag "no confirmation (dangerous)" nil)))
  1934. (put 'org-confirm-shell-link-function
  1935. 'safe-local-variable
  1936. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1937. (defcustom org-confirm-elisp-link-not-regexp ""
  1938. "A regexp to skip confirmation for Elisp links."
  1939. :group 'org-link-follow
  1940. :version "24.1"
  1941. :type 'regexp)
  1942. (defconst org-file-apps-defaults-gnu
  1943. '((remote . emacs)
  1944. (system . mailcap)
  1945. (t . mailcap))
  1946. "Default file applications on a UNIX or GNU/Linux system.
  1947. See `org-file-apps'.")
  1948. (defconst org-file-apps-defaults-macosx
  1949. '((remote . emacs)
  1950. (system . "open %s")
  1951. ("ps.gz" . "gv %s")
  1952. ("eps.gz" . "gv %s")
  1953. ("dvi" . "xdvi %s")
  1954. ("fig" . "xfig %s")
  1955. (t . "open %s"))
  1956. "Default file applications on a macOS system.
  1957. The system \"open\" is known as a default, but we use X11 applications
  1958. for some files for which the OS does not have a good default.
  1959. See `org-file-apps'.")
  1960. (defconst org-file-apps-defaults-windowsnt
  1961. (list '(remote . emacs)
  1962. (cons 'system (lambda (file _path)
  1963. (with-no-warnings (w32-shell-execute "open" file))))
  1964. (cons t (lambda (file _path)
  1965. (with-no-warnings (w32-shell-execute "open" file)))))
  1966. "Default file applications on a Windows NT system.
  1967. The system \"open\" is used for most files.
  1968. See `org-file-apps'.")
  1969. (defcustom org-file-apps
  1970. '((auto-mode . emacs)
  1971. ("\\.mm\\'" . default)
  1972. ("\\.x?html?\\'" . default)
  1973. ("\\.pdf\\'" . default))
  1974. "External applications for opening `file:path' items in a document.
  1975. \\<org-mode-map>\
  1976. Org mode uses system defaults for different file types, but
  1977. you can use this variable to set the application for a given file
  1978. extension. The entries in this list are cons cells where the car identifies
  1979. files and the cdr the corresponding command.
  1980. Possible values for the file identifier are:
  1981. \"string\" A string as a file identifier can be interpreted in different
  1982. ways, depending on its contents:
  1983. - Alphanumeric characters only:
  1984. Match links with this file extension.
  1985. Example: (\"pdf\" . \"evince %s\")
  1986. to open PDFs with evince.
  1987. - Regular expression: Match links where the
  1988. filename matches the regexp. If you want to
  1989. use groups here, use shy groups.
  1990. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1991. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1992. to open *.html and *.xhtml with firefox.
  1993. - Regular expression which contains (non-shy) groups:
  1994. Match links where the whole link, including \"::\", and
  1995. anything after that, matches the regexp.
  1996. In a custom command string, %1, %2, etc. are replaced with
  1997. the parts of the link that were matched by the groups.
  1998. For backwards compatibility, if a command string is given
  1999. that does not use any of the group matches, this case is
  2000. handled identically to the second one (i.e. match against
  2001. file name only).
  2002. In a custom function, you can access the group matches with
  2003. (match-string n link).
  2004. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  2005. \"evince -p %1 %s\")
  2006. to open [[file:document.pdf::5]] with evince at page 5.
  2007. `directory' Matches a directory
  2008. `remote' Matches a remote file, accessible through tramp or efs.
  2009. Remote files most likely should be visited through Emacs
  2010. because external applications cannot handle such paths.
  2011. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2012. so all files Emacs knows how to handle. Using this with
  2013. command `emacs' will open most files in Emacs. Beware that this
  2014. will also open html files inside Emacs, unless you add
  2015. (\"html\" . default) to the list as well.
  2016. `system' The system command to open files, like `open' on Windows
  2017. and macOS, and mailcap under GNU/Linux. This is the command
  2018. that will be selected if you call `org-open-at-point' with a
  2019. double prefix argument (`\\[universal-argument] \
  2020. \\[universal-argument] \\[org-open-at-point]').
  2021. t Default for files not matched by any of the other options.
  2022. Possible values for the command are:
  2023. `emacs' The file will be visited by the current Emacs process.
  2024. `default' Use the default application for this file type, which is the
  2025. association for t in the list, most likely in the system-specific
  2026. part. This can be used to overrule an unwanted setting in the
  2027. system-specific variable.
  2028. `system' Use the system command for opening files, like \"open\".
  2029. This command is specified by the entry whose car is `system'.
  2030. Most likely, the system-specific version of this variable
  2031. does define this command, but you can overrule/replace it
  2032. here.
  2033. `mailcap' Use command specified in the mailcaps.
  2034. string A command to be executed by a shell; %s will be replaced
  2035. by the path to the file.
  2036. function A Lisp function, which will be called with two arguments:
  2037. the file path and the original link string, without the
  2038. \"file:\" prefix.
  2039. For more examples, see the system specific constants
  2040. `org-file-apps-defaults-macosx'
  2041. `org-file-apps-defaults-windowsnt'
  2042. `org-file-apps-defaults-gnu'."
  2043. :group 'org-link-follow
  2044. :type '(repeat
  2045. (cons (choice :value ""
  2046. (string :tag "Extension")
  2047. (const :tag "System command to open files" system)
  2048. (const :tag "Default for unrecognized files" t)
  2049. (const :tag "Remote file" remote)
  2050. (const :tag "Links to a directory" directory)
  2051. (const :tag "Any files that have Emacs modes"
  2052. auto-mode))
  2053. (choice :value ""
  2054. (const :tag "Visit with Emacs" emacs)
  2055. (const :tag "Use default" default)
  2056. (const :tag "Use the system command" system)
  2057. (string :tag "Command")
  2058. (function :tag "Function")))))
  2059. (defcustom org-doi-server-url "http://dx.doi.org/"
  2060. "The URL of the DOI server."
  2061. :type 'string
  2062. :version "24.3"
  2063. :group 'org-link-follow)
  2064. (defgroup org-refile nil
  2065. "Options concerning refiling entries in Org mode."
  2066. :tag "Org Refile"
  2067. :group 'org)
  2068. (defcustom org-directory "~/org"
  2069. "Directory with Org files.
  2070. This is just a default location to look for Org files. There is no need
  2071. at all to put your files into this directory. It is used in the
  2072. following situations:
  2073. 1. When a capture template specifies a target file that is not an
  2074. absolute path. The path will then be interpreted relative to
  2075. `org-directory'
  2076. 2. When the value of variable `org-agenda-files' is a single file, any
  2077. relative paths in this file will be taken as relative to
  2078. `org-directory'."
  2079. :group 'org-refile
  2080. :group 'org-capture
  2081. :type 'directory)
  2082. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2083. "Default target for storing notes.
  2084. Used as a fall back file for org-capture.el, for templates that
  2085. do not specify a target file."
  2086. :group 'org-refile
  2087. :group 'org-capture
  2088. :type 'file)
  2089. (defcustom org-reverse-note-order nil
  2090. "Non-nil means store new notes at the beginning of a file or entry.
  2091. When nil, new notes will be filed to the end of a file or entry.
  2092. This can also be a list with cons cells of regular expressions that
  2093. are matched against file names, and values."
  2094. :group 'org-capture
  2095. :group 'org-refile
  2096. :type '(choice
  2097. (const :tag "Reverse always" t)
  2098. (const :tag "Reverse never" nil)
  2099. (repeat :tag "By file name regexp"
  2100. (cons regexp boolean))))
  2101. (defcustom org-log-refile nil
  2102. "Information to record when a task is refiled.
  2103. Possible values are:
  2104. nil Don't add anything
  2105. time Add a time stamp to the task
  2106. note Prompt for a note and add it with template `org-log-note-headings'
  2107. This option can also be set with on a per-file-basis with
  2108. #+STARTUP: nologrefile
  2109. #+STARTUP: logrefile
  2110. #+STARTUP: lognoterefile
  2111. You can have local logging settings for a subtree by setting the LOGGING
  2112. property to one or more of these keywords.
  2113. When bulk-refiling from the agenda, the value `note' is forbidden and
  2114. will temporarily be changed to `time'."
  2115. :group 'org-refile
  2116. :group 'org-progress
  2117. :version "24.1"
  2118. :type '(choice
  2119. (const :tag "No logging" nil)
  2120. (const :tag "Record timestamp" time)
  2121. (const :tag "Record timestamp with note." note)))
  2122. (defcustom org-refile-targets nil
  2123. "Targets for refiling entries with `\\[org-refile]'.
  2124. This is a list of cons cells. Each cell contains:
  2125. - a specification of the files to be considered, either a list of files,
  2126. or a symbol whose function or variable value will be used to retrieve
  2127. a file name or a list of file names. If you use `org-agenda-files' for
  2128. that, all agenda files will be scanned for targets. Nil means consider
  2129. headings in the current buffer.
  2130. - A specification of how to find candidate refile targets. This may be
  2131. any of:
  2132. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2133. This tag has to be present in all target headlines, inheritance will
  2134. not be considered.
  2135. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2136. todo keyword.
  2137. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2138. headlines that are refiling targets.
  2139. - a cons cell (:level . N). Any headline of level N is considered a target.
  2140. Note that, when `org-odd-levels-only' is set, level corresponds to
  2141. order in hierarchy, not to the number of stars.
  2142. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2143. Note that, when `org-odd-levels-only' is set, level corresponds to
  2144. order in hierarchy, not to the number of stars.
  2145. Each element of this list generates a set of possible targets.
  2146. The union of these sets is presented (with completion) to
  2147. the user by `org-refile'.
  2148. You can set the variable `org-refile-target-verify-function' to a function
  2149. to verify each headline found by the simple criteria above.
  2150. When this variable is nil, all top-level headlines in the current buffer
  2151. are used, equivalent to the value `((nil . (:level . 1))'."
  2152. :group 'org-refile
  2153. :type '(repeat
  2154. (cons
  2155. (choice :value org-agenda-files
  2156. (const :tag "All agenda files" org-agenda-files)
  2157. (const :tag "Current buffer" nil)
  2158. (function) (variable) (file))
  2159. (choice :tag "Identify target headline by"
  2160. (cons :tag "Specific tag" (const :value :tag) (string))
  2161. (cons :tag "TODO keyword" (const :value :todo) (string))
  2162. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2163. (cons :tag "Level number" (const :value :level) (integer))
  2164. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2165. (defcustom org-refile-target-verify-function nil
  2166. "Function to verify if the headline at point should be a refile target.
  2167. The function will be called without arguments, with point at the
  2168. beginning of the headline. It should return t and leave point
  2169. where it is if the headline is a valid target for refiling.
  2170. If the target should not be selected, the function must return nil.
  2171. In addition to this, it may move point to a place from where the search
  2172. should be continued. For example, the function may decide that the entire
  2173. subtree of the current entry should be excluded and move point to the end
  2174. of the subtree."
  2175. :group 'org-refile
  2176. :type '(choice
  2177. (const nil)
  2178. (function)))
  2179. (defcustom org-refile-use-cache nil
  2180. "Non-nil means cache refile targets to speed up the process.
  2181. \\<org-mode-map>\
  2182. The cache for a particular file will be updated automatically when
  2183. the buffer has been killed, or when any of the marker used for flagging
  2184. refile targets no longer points at a live buffer.
  2185. If you have added new entries to a buffer that might themselves be targets,
  2186. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2187. if you find that easier, \
  2188. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2189. \\[org-refile]'."
  2190. :group 'org-refile
  2191. :version "24.1"
  2192. :type 'boolean)
  2193. (defcustom org-refile-use-outline-path nil
  2194. "Non-nil means provide refile targets as paths.
  2195. So a level 3 headline will be available as level1/level2/level3.
  2196. When the value is `file', also include the file name (without directory)
  2197. into the path. In this case, you can also stop the completion after
  2198. the file name, to get entries inserted as top level in the file.
  2199. When `full-file-path', include the full file path.
  2200. When `buffer-name', use the buffer name."
  2201. :group 'org-refile
  2202. :type '(choice
  2203. (const :tag "Not" nil)
  2204. (const :tag "Yes" t)
  2205. (const :tag "Start with file name" file)
  2206. (const :tag "Start with full file path" full-file-path)
  2207. (const :tag "Start with buffer name" buffer-name)))
  2208. (defcustom org-outline-path-complete-in-steps t
  2209. "Non-nil means complete the outline path in hierarchical steps.
  2210. When Org uses the refile interface to select an outline path (see
  2211. `org-refile-use-outline-path'), the completion of the path can be
  2212. done in a single go, or it can be done in steps down the headline
  2213. hierarchy. Going in steps is probably the best if you do not use
  2214. a special completion package like `ido' or `icicles'. However,
  2215. when using these packages, going in one step can be very fast,
  2216. while still showing the whole path to the entry."
  2217. :group 'org-refile
  2218. :type 'boolean)
  2219. (defcustom org-refile-allow-creating-parent-nodes nil
  2220. "Non-nil means allow the creation of new nodes as refile targets.
  2221. New nodes are then created by adding \"/new node name\" to the completion
  2222. of an existing node. When the value of this variable is `confirm',
  2223. new node creation must be confirmed by the user (recommended).
  2224. When nil, the completion must match an existing entry.
  2225. Note that, if the new heading is not seen by the criteria
  2226. listed in `org-refile-targets', multiple instances of the same
  2227. heading would be created by trying again to file under the new
  2228. heading."
  2229. :group 'org-refile
  2230. :type '(choice
  2231. (const :tag "Never" nil)
  2232. (const :tag "Always" t)
  2233. (const :tag "Prompt for confirmation" confirm)))
  2234. (defcustom org-refile-active-region-within-subtree nil
  2235. "Non-nil means also refile active region within a subtree.
  2236. By default `org-refile' doesn't allow refiling regions if they
  2237. don't contain a set of subtrees, but it might be convenient to
  2238. do so sometimes: in that case, the first line of the region is
  2239. converted to a headline before refiling."
  2240. :group 'org-refile
  2241. :version "24.1"
  2242. :type 'boolean)
  2243. (defgroup org-todo nil
  2244. "Options concerning TODO items in Org mode."
  2245. :tag "Org TODO"
  2246. :group 'org)
  2247. (defgroup org-progress nil
  2248. "Options concerning Progress logging in Org mode."
  2249. :tag "Org Progress"
  2250. :group 'org-time)
  2251. (defvar org-todo-interpretation-widgets
  2252. '((:tag "Sequence (cycling hits every state)" sequence)
  2253. (:tag "Type (cycling directly to DONE)" type))
  2254. "The available interpretation symbols for customizing `org-todo-keywords'.
  2255. Interested libraries should add to this list.")
  2256. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2257. "List of TODO entry keyword sequences and their interpretation.
  2258. \\<org-mode-map>This is a list of sequences.
  2259. Each sequence starts with a symbol, either `sequence' or `type',
  2260. indicating if the keywords should be interpreted as a sequence of
  2261. action steps, or as different types of TODO items. The first
  2262. keywords are states requiring action - these states will select a headline
  2263. for inclusion into the global TODO list Org produces. If one of the
  2264. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2265. signify that no further action is necessary. If \"|\" is not found,
  2266. the last keyword is treated as the only DONE state of the sequence.
  2267. The command `\\[org-todo]' cycles an entry through these states, and one
  2268. additional state where no keyword is present. For details about this
  2269. cycling, see the manual.
  2270. TODO keywords and interpretation can also be set on a per-file basis with
  2271. the special #+SEQ_TODO and #+TYP_TODO lines.
  2272. Each keyword can optionally specify a character for fast state selection
  2273. \(in combination with the variable `org-use-fast-todo-selection')
  2274. and specifiers for state change logging, using the same syntax that
  2275. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2276. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2277. indicates to record a time stamp each time this state is selected.
  2278. Each keyword may also specify if a timestamp or a note should be
  2279. recorded when entering or leaving the state, by adding additional
  2280. characters in the parenthesis after the keyword. This looks like this:
  2281. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2282. record only the time of the state change. With X and Y being either
  2283. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2284. Y when leaving the state if and only if the *target* state does not
  2285. define X. You may omit any of the fast-selection key or X or /Y,
  2286. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2287. For backward compatibility, this variable may also be just a list
  2288. of keywords. In this case the interpretation (sequence or type) will be
  2289. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2290. :group 'org-todo
  2291. :group 'org-keywords
  2292. :type '(choice
  2293. (repeat :tag "Old syntax, just keywords"
  2294. (string :tag "Keyword"))
  2295. (repeat :tag "New syntax"
  2296. (cons
  2297. (choice
  2298. :tag "Interpretation"
  2299. ;;Quick and dirty way to see
  2300. ;;`org-todo-interpretations'. This takes the
  2301. ;;place of item arguments
  2302. :convert-widget
  2303. (lambda (widget)
  2304. (widget-put widget
  2305. :args (mapcar
  2306. (lambda (x)
  2307. (widget-convert
  2308. (cons 'const x)))
  2309. org-todo-interpretation-widgets))
  2310. widget))
  2311. (repeat
  2312. (string :tag "Keyword"))))))
  2313. (defvar-local org-todo-keywords-1 nil
  2314. "All TODO and DONE keywords active in a buffer.")
  2315. (defvar org-todo-keywords-for-agenda nil)
  2316. (defvar org-done-keywords-for-agenda nil)
  2317. (defvar org-todo-keyword-alist-for-agenda nil)
  2318. (defvar org-tag-alist-for-agenda nil
  2319. "Alist of all tags from all agenda files.")
  2320. (defvar org-tag-groups-alist-for-agenda nil
  2321. "Alist of all groups tags from all current agenda files.")
  2322. (defvar-local org-tag-groups-alist nil)
  2323. (defvar org-agenda-contributing-files nil)
  2324. (defvar-local org-current-tag-alist nil
  2325. "Alist of all tag groups in current buffer.
  2326. This variable takes into consideration `org-tag-alist',
  2327. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2328. (defvar-local org-not-done-keywords nil)
  2329. (defvar-local org-done-keywords nil)
  2330. (defvar-local org-todo-heads nil)
  2331. (defvar-local org-todo-sets nil)
  2332. (defvar-local org-todo-log-states nil)
  2333. (defvar-local org-todo-kwd-alist nil)
  2334. (defvar-local org-todo-key-alist nil)
  2335. (defvar-local org-todo-key-trigger nil)
  2336. (defcustom org-todo-interpretation 'sequence
  2337. "Controls how TODO keywords are interpreted.
  2338. This variable is in principle obsolete and is only used for
  2339. backward compatibility, if the interpretation of todo keywords is
  2340. not given already in `org-todo-keywords'. See that variable for
  2341. more information."
  2342. :group 'org-todo
  2343. :group 'org-keywords
  2344. :type '(choice (const sequence)
  2345. (const type)))
  2346. (defcustom org-use-fast-todo-selection t
  2347. "\\<org-mode-map>\
  2348. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2349. This variable describes if and under what circumstances the cycling
  2350. mechanism for TODO keywords will be replaced by a single-key, direct
  2351. selection scheme.
  2352. When nil, fast selection is never used.
  2353. When the symbol `prefix', it will be used when `org-todo' is called
  2354. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2355. in an Org buffer, and
  2356. `\\[universal-argument] t' in an agenda buffer.
  2357. When t, fast selection is used by default. In this case, the prefix
  2358. argument forces cycling instead.
  2359. In all cases, the special interface is only used if access keys have
  2360. actually been assigned by the user, i.e. if keywords in the configuration
  2361. are followed by a letter in parenthesis, like TODO(t)."
  2362. :group 'org-todo
  2363. :type '(choice
  2364. (const :tag "Never" nil)
  2365. (const :tag "By default" t)
  2366. (const :tag "Only with C-u C-c C-t" prefix)))
  2367. (defcustom org-provide-todo-statistics t
  2368. "Non-nil means update todo statistics after insert and toggle.
  2369. ALL-HEADLINES means update todo statistics by including headlines
  2370. with no TODO keyword as well, counting them as not done.
  2371. A list of TODO keywords means the same, but skip keywords that are
  2372. not in this list.
  2373. When set to a list of two lists, the first list contains keywords
  2374. to consider as TODO keywords, the second list contains keywords
  2375. to consider as DONE keywords.
  2376. When this is set, todo statistics is updated in the parent of the
  2377. current entry each time a todo state is changed."
  2378. :group 'org-todo
  2379. :type '(choice
  2380. (const :tag "Yes, only for TODO entries" t)
  2381. (const :tag "Yes, including all entries" all-headlines)
  2382. (repeat :tag "Yes, for TODOs in this list"
  2383. (string :tag "TODO keyword"))
  2384. (list :tag "Yes, for TODOs and DONEs in these lists"
  2385. (repeat (string :tag "TODO keyword"))
  2386. (repeat (string :tag "DONE keyword")))
  2387. (other :tag "No TODO statistics" nil)))
  2388. (defcustom org-hierarchical-todo-statistics t
  2389. "Non-nil means TODO statistics covers just direct children.
  2390. When nil, all entries in the subtree are considered.
  2391. This has only an effect if `org-provide-todo-statistics' is set.
  2392. To set this to nil for only a single subtree, use a COOKIE_DATA
  2393. property and include the word \"recursive\" into the value."
  2394. :group 'org-todo
  2395. :type 'boolean)
  2396. (defcustom org-after-todo-state-change-hook nil
  2397. "Hook which is run after the state of a TODO item was changed.
  2398. The new state (a string with a TODO keyword, or nil) is available in the
  2399. Lisp variable `org-state'."
  2400. :group 'org-todo
  2401. :type 'hook)
  2402. (defvar org-blocker-hook nil
  2403. "Hook for functions that are allowed to block a state change.
  2404. Functions in this hook should not modify the buffer.
  2405. Each function gets as its single argument a property list,
  2406. see `org-trigger-hook' for more information about this list.
  2407. If any of the functions in this hook returns nil, the state change
  2408. is blocked.")
  2409. (defvar org-trigger-hook nil
  2410. "Hook for functions that are triggered by a state change.
  2411. Each function gets as its single argument a property list with at
  2412. least the following elements:
  2413. (:type type-of-change :position pos-at-entry-start
  2414. :from old-state :to new-state)
  2415. Depending on the type, more properties may be present.
  2416. This mechanism is currently implemented for:
  2417. TODO state changes
  2418. ------------------
  2419. :type todo-state-change
  2420. :from previous state (keyword as a string), or nil, or a symbol
  2421. `todo' or `done', to indicate the general type of state.
  2422. :to new state, like in :from")
  2423. (defcustom org-enforce-todo-dependencies nil
  2424. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2425. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2426. be blocked if any prior sibling is not yet done.
  2427. Finally, if the parent is blocked because of ordered siblings of its own,
  2428. the child will also be blocked."
  2429. :set (lambda (var val)
  2430. (set var val)
  2431. (if val
  2432. (add-hook 'org-blocker-hook
  2433. 'org-block-todo-from-children-or-siblings-or-parent)
  2434. (remove-hook 'org-blocker-hook
  2435. 'org-block-todo-from-children-or-siblings-or-parent)))
  2436. :group 'org-todo
  2437. :type 'boolean)
  2438. (defcustom org-enforce-todo-checkbox-dependencies nil
  2439. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2440. When this is nil, checkboxes have no influence on switching TODO states.
  2441. When non-nil, you first need to check off all check boxes before the TODO
  2442. entry can be switched to DONE.
  2443. This variable needs to be set before org.el is loaded, and you need to
  2444. restart Emacs after a change to make the change effective. The only way
  2445. to change it while Emacs is running is through the customize interface."
  2446. :set (lambda (var val)
  2447. (set var val)
  2448. (if val
  2449. (add-hook 'org-blocker-hook
  2450. 'org-block-todo-from-checkboxes)
  2451. (remove-hook 'org-blocker-hook
  2452. 'org-block-todo-from-checkboxes)))
  2453. :group 'org-todo
  2454. :type 'boolean)
  2455. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2456. "Non-nil means inserting a TODO heading is treated as state change.
  2457. So when the command `\\[org-insert-todo-heading]' is used, state change
  2458. logging will apply if appropriate. When nil, the new TODO item will
  2459. be inserted directly, and no logging will take place."
  2460. :group 'org-todo
  2461. :type 'boolean)
  2462. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2463. "Non-nil means switching TODO states with S-cursor counts as state change.
  2464. This is the default behavior. However, setting this to nil allows a
  2465. convenient way to select a TODO state and bypass any logging associated
  2466. with that."
  2467. :group 'org-todo
  2468. :type 'boolean)
  2469. (defcustom org-todo-state-tags-triggers nil
  2470. "Tag changes that should be triggered by TODO state changes.
  2471. This is a list. Each entry is
  2472. (state-change (tag . flag) .......)
  2473. State-change can be a string with a state, and empty string to indicate the
  2474. state that has no TODO keyword, or it can be one of the symbols `todo'
  2475. or `done', meaning any not-done or done state, respectively."
  2476. :group 'org-todo
  2477. :group 'org-tags
  2478. :type '(repeat
  2479. (cons (choice :tag "When changing to"
  2480. (const :tag "Not-done state" todo)
  2481. (const :tag "Done state" done)
  2482. (string :tag "State"))
  2483. (repeat
  2484. (cons :tag "Tag action"
  2485. (string :tag "Tag")
  2486. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2487. (defcustom org-log-done nil
  2488. "Information to record when a task moves to the DONE state.
  2489. Possible values are:
  2490. nil Don't add anything, just change the keyword
  2491. time Add a time stamp to the task
  2492. note Prompt for a note and add it with template `org-log-note-headings'
  2493. This option can also be set with on a per-file-basis with
  2494. #+STARTUP: nologdone
  2495. #+STARTUP: logdone
  2496. #+STARTUP: lognotedone
  2497. You can have local logging settings for a subtree by setting the LOGGING
  2498. property to one or more of these keywords."
  2499. :group 'org-todo
  2500. :group 'org-progress
  2501. :type '(choice
  2502. (const :tag "No logging" nil)
  2503. (const :tag "Record CLOSED timestamp" time)
  2504. (const :tag "Record CLOSED timestamp with note." note)))
  2505. ;; Normalize old uses of org-log-done.
  2506. (cond
  2507. ((eq org-log-done t) (setq org-log-done 'time))
  2508. ((and (listp org-log-done) (memq 'done org-log-done))
  2509. (setq org-log-done 'note)))
  2510. (defcustom org-log-reschedule nil
  2511. "Information to record when the scheduling date of a task is modified.
  2512. Possible values are:
  2513. nil Don't add anything, just change the date
  2514. time Add a time stamp to the task
  2515. note Prompt for a note and add it with template `org-log-note-headings'
  2516. This option can also be set with on a per-file-basis with
  2517. #+STARTUP: nologreschedule
  2518. #+STARTUP: logreschedule
  2519. #+STARTUP: lognotereschedule
  2520. You can have local logging settings for a subtree by setting the LOGGING
  2521. property to one or more of these keywords.
  2522. This variable has an effect when calling `org-schedule' or
  2523. `org-agenda-schedule' only."
  2524. :group 'org-todo
  2525. :group 'org-progress
  2526. :type '(choice
  2527. (const :tag "No logging" nil)
  2528. (const :tag "Record timestamp" time)
  2529. (const :tag "Record timestamp with note" note)))
  2530. (defcustom org-log-redeadline nil
  2531. "Information to record when the deadline date of a task is modified.
  2532. Possible values are:
  2533. nil Don't add anything, just change the date
  2534. time Add a time stamp to the task
  2535. note Prompt for a note and add it with template `org-log-note-headings'
  2536. This option can also be set with on a per-file-basis with
  2537. #+STARTUP: nologredeadline
  2538. #+STARTUP: logredeadline
  2539. #+STARTUP: lognoteredeadline
  2540. You can have local logging settings for a subtree by setting the LOGGING
  2541. property to one or more of these keywords.
  2542. This variable has an effect when calling `org-deadline' or
  2543. `org-agenda-deadline' only."
  2544. :group 'org-todo
  2545. :group 'org-progress
  2546. :type '(choice
  2547. (const :tag "No logging" nil)
  2548. (const :tag "Record timestamp" time)
  2549. (const :tag "Record timestamp with note." note)))
  2550. (defcustom org-log-note-clock-out nil
  2551. "Non-nil means record a note when clocking out of an item.
  2552. This can also be configured on a per-file basis by adding one of
  2553. the following lines anywhere in the buffer:
  2554. #+STARTUP: lognoteclock-out
  2555. #+STARTUP: nolognoteclock-out"
  2556. :group 'org-todo
  2557. :group 'org-progress
  2558. :type 'boolean)
  2559. (defcustom org-log-done-with-time t
  2560. "Non-nil means the CLOSED time stamp will contain date and time.
  2561. When nil, only the date will be recorded."
  2562. :group 'org-progress
  2563. :type 'boolean)
  2564. (defcustom org-log-note-headings
  2565. '((done . "CLOSING NOTE %t")
  2566. (state . "State %-12s from %-12S %t")
  2567. (note . "Note taken on %t")
  2568. (reschedule . "Rescheduled from %S on %t")
  2569. (delschedule . "Not scheduled, was %S on %t")
  2570. (redeadline . "New deadline from %S on %t")
  2571. (deldeadline . "Removed deadline, was %S on %t")
  2572. (refile . "Refiled on %t")
  2573. (clock-out . ""))
  2574. "Headings for notes added to entries.
  2575. The value is an alist, with the car being a symbol indicating the
  2576. note context, and the cdr is the heading to be used. The heading
  2577. may also be the empty string. The following placeholders can be
  2578. used:
  2579. %t a time stamp.
  2580. %T an active time stamp instead the default inactive one
  2581. %d a short-format time stamp.
  2582. %D an active short-format time stamp.
  2583. %s the new TODO state or time stamp (inactive), in double quotes.
  2584. %S the old TODO state or time stamp (inactive), in double quotes.
  2585. %u the user name.
  2586. %U full user name.
  2587. In fact, it is not a good idea to change the `state' entry,
  2588. because Agenda Log mode depends on the format of these entries."
  2589. :group 'org-todo
  2590. :group 'org-progress
  2591. :type '(list :greedy t
  2592. (cons (const :tag "Heading when closing an item" done) string)
  2593. (cons (const :tag
  2594. "Heading when changing todo state (todo sequence only)"
  2595. state) string)
  2596. (cons (const :tag "Heading when just taking a note" note) string)
  2597. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2598. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2599. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2600. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2601. (cons (const :tag "Heading when refiling" refile) string)
  2602. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2603. (unless (assq 'note org-log-note-headings)
  2604. (push '(note . "%t") org-log-note-headings))
  2605. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2606. (defcustom org-log-into-drawer nil
  2607. "Non-nil means insert state change notes and time stamps into a drawer.
  2608. When nil, state changes notes will be inserted after the headline and
  2609. any scheduling and clock lines, but not inside a drawer.
  2610. The value of this variable should be the name of the drawer to use.
  2611. LOGBOOK is proposed as the default drawer for this purpose, you can
  2612. also set this to a string to define the drawer of your choice.
  2613. A value of t is also allowed, representing \"LOGBOOK\".
  2614. A value of t or nil can also be set with on a per-file-basis with
  2615. #+STARTUP: logdrawer
  2616. #+STARTUP: nologdrawer
  2617. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2618. will be ignored.
  2619. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2620. a subtree.
  2621. Do not check directly this variable in a Lisp program. Call
  2622. function `org-log-into-drawer' instead."
  2623. :group 'org-todo
  2624. :group 'org-progress
  2625. :type '(choice
  2626. (const :tag "Not into a drawer" nil)
  2627. (const :tag "LOGBOOK" t)
  2628. (string :tag "Other")))
  2629. (defun org-log-into-drawer ()
  2630. "Name of the log drawer, as a string, or nil.
  2631. This is the value of `org-log-into-drawer'. However, if the
  2632. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2633. be used instead of the default value."
  2634. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2635. (cond ((equal p "nil") nil)
  2636. ((equal p "t") "LOGBOOK")
  2637. ((stringp p) p)
  2638. (p "LOGBOOK")
  2639. ((stringp org-log-into-drawer) org-log-into-drawer)
  2640. (org-log-into-drawer "LOGBOOK"))))
  2641. (defcustom org-log-state-notes-insert-after-drawers nil
  2642. "Non-nil means insert state change notes after any drawers in entry.
  2643. Only the drawers that *immediately* follow the headline and the
  2644. deadline/scheduled line are skipped.
  2645. When nil, insert notes right after the heading and perhaps the line
  2646. with deadline/scheduling if present.
  2647. This variable will have no effect if `org-log-into-drawer' is
  2648. set."
  2649. :group 'org-todo
  2650. :group 'org-progress
  2651. :type 'boolean)
  2652. (defcustom org-log-states-order-reversed t
  2653. "Non-nil means the latest state note will be directly after heading.
  2654. When nil, the state change notes will be ordered according to time.
  2655. This option can also be set with on a per-file-basis with
  2656. #+STARTUP: logstatesreversed
  2657. #+STARTUP: nologstatesreversed"
  2658. :group 'org-todo
  2659. :group 'org-progress
  2660. :type 'boolean)
  2661. (defcustom org-todo-repeat-to-state nil
  2662. "The TODO state to which a repeater should return the repeating task.
  2663. By default this is the first task of a TODO sequence or the
  2664. previous state of a TYPE_TODO set. But you can specify to use
  2665. the previous state in a TODO sequence or a string.
  2666. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2667. entry, which has precedence over this option."
  2668. :group 'org-todo
  2669. :version "24.1"
  2670. :type '(choice (const :tag "Use the previous TODO state" t)
  2671. (const :tag "Use the head of the TODO sequence" nil)
  2672. (string :tag "Use a specific TODO state")))
  2673. (defcustom org-log-repeat 'time
  2674. "Non-nil means record moving through the DONE state when triggering repeat.
  2675. An auto-repeating task is immediately switched back to TODO when
  2676. marked DONE. If you are not logging state changes (by adding \"@\"
  2677. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2678. record a closing note, there will be no record of the task moving
  2679. through DONE. This variable forces taking a note anyway.
  2680. nil Don't force a record
  2681. time Record a time stamp
  2682. note Prompt for a note and add it with template `org-log-note-headings'
  2683. This option can also be set with on a per-file-basis with
  2684. #+STARTUP: nologrepeat
  2685. #+STARTUP: logrepeat
  2686. #+STARTUP: lognoterepeat
  2687. You can have local logging settings for a subtree by setting the LOGGING
  2688. property to one or more of these keywords."
  2689. :group 'org-todo
  2690. :group 'org-progress
  2691. :type '(choice
  2692. (const :tag "Don't force a record" nil)
  2693. (const :tag "Force recording the DONE state" time)
  2694. (const :tag "Force recording a note with the DONE state" note)))
  2695. (defcustom org-todo-repeat-hook nil
  2696. "Hook that is run after a task has been repeated."
  2697. :package-version '(Org . "9.2")
  2698. :group 'org-todo
  2699. :type 'hook)
  2700. (defgroup org-priorities nil
  2701. "Priorities in Org mode."
  2702. :tag "Org Priorities"
  2703. :group 'org-todo)
  2704. (defcustom org-enable-priority-commands t
  2705. "Non-nil means priority commands are active.
  2706. When nil, these commands will be disabled, so that you never accidentally
  2707. set a priority."
  2708. :group 'org-priorities
  2709. :type 'boolean)
  2710. (defcustom org-highest-priority ?A
  2711. "The highest priority of TODO items. A character like ?A, ?B etc.
  2712. Must have a smaller ASCII number than `org-lowest-priority'."
  2713. :group 'org-priorities
  2714. :type 'character)
  2715. (defcustom org-lowest-priority ?C
  2716. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2717. Must have a larger ASCII number than `org-highest-priority'."
  2718. :group 'org-priorities
  2719. :type 'character)
  2720. (defcustom org-default-priority ?B
  2721. "The default priority of TODO items.
  2722. This is the priority an item gets if no explicit priority is given.
  2723. When starting to cycle on an empty priority the first step in the cycle
  2724. depends on `org-priority-start-cycle-with-default'. The resulting first
  2725. step priority must not exceed the range from `org-highest-priority' to
  2726. `org-lowest-priority' which means that `org-default-priority' has to be
  2727. in this range exclusive or inclusive the range boundaries. Else the
  2728. first step refuses to set the default and the second will fall back
  2729. to (depending on the command used) the highest or lowest priority."
  2730. :group 'org-priorities
  2731. :type 'character)
  2732. (defcustom org-priority-start-cycle-with-default t
  2733. "Non-nil means start with default priority when starting to cycle.
  2734. When this is nil, the first step in the cycle will be (depending on the
  2735. command used) one higher or lower than the default priority.
  2736. See also `org-default-priority'."
  2737. :group 'org-priorities
  2738. :type 'boolean)
  2739. (defcustom org-get-priority-function nil
  2740. "Function to extract the priority from a string.
  2741. The string is normally the headline. If this is nil Org computes the
  2742. priority from the priority cookie like [#A] in the headline. It returns
  2743. an integer, increasing by 1000 for each priority level.
  2744. The user can set a different function here, which should take a string
  2745. as an argument and return the numeric priority."
  2746. :group 'org-priorities
  2747. :version "24.1"
  2748. :type '(choice
  2749. (const nil)
  2750. (function)))
  2751. (defgroup org-time nil
  2752. "Options concerning time stamps and deadlines in Org mode."
  2753. :tag "Org Time"
  2754. :group 'org)
  2755. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2756. "Number of minutes to round time stamps to.
  2757. \\<org-mode-map>\
  2758. These are two values, the first applies when first creating a time stamp.
  2759. The second applies when changing it with the commands `S-up' and `S-down'.
  2760. When changing the time stamp, this means that it will change in steps
  2761. of N minutes, as given by the second value.
  2762. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2763. numbers should be factors of 60, so for example 5, 10, 15.
  2764. When this is larger than 1, you can still force an exact time stamp by using
  2765. a double prefix argument to a time stamp command like \
  2766. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2767. and by using a prefix arg to `S-up/down' to specify the exact number
  2768. of minutes to shift."
  2769. :group 'org-time
  2770. :get (lambda (var) ; Make sure both elements are there
  2771. (if (integerp (default-value var))
  2772. (list (default-value var) 5)
  2773. (default-value var)))
  2774. :type '(list
  2775. (integer :tag "when inserting times")
  2776. (integer :tag "when modifying times")))
  2777. ;; Normalize old customizations of this variable.
  2778. (when (integerp org-time-stamp-rounding-minutes)
  2779. (setq org-time-stamp-rounding-minutes
  2780. (list org-time-stamp-rounding-minutes
  2781. org-time-stamp-rounding-minutes)))
  2782. (defcustom org-display-custom-times nil
  2783. "Non-nil means overlay custom formats over all time stamps.
  2784. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2785. To turn this on on a per-file basis, insert anywhere in the file:
  2786. #+STARTUP: customtime"
  2787. :group 'org-time
  2788. :set 'set-default
  2789. :type 'sexp)
  2790. (make-variable-buffer-local 'org-display-custom-times)
  2791. (defcustom org-time-stamp-custom-formats
  2792. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2793. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2794. These are overlaid over the default ISO format if the variable
  2795. `org-display-custom-times' is set. Time like %H:%M should be at the
  2796. end of the second format. The custom formats are also honored by export
  2797. commands, if custom time display is turned on at the time of export."
  2798. :group 'org-time
  2799. :type 'sexp)
  2800. (defun org-time-stamp-format (&optional long inactive)
  2801. "Get the right format for a time string."
  2802. (let ((f (if long (cdr org-time-stamp-formats)
  2803. (car org-time-stamp-formats))))
  2804. (if inactive
  2805. (concat "[" (substring f 1 -1) "]")
  2806. f)))
  2807. (defcustom org-deadline-warning-days 14
  2808. "Number of days before expiration during which a deadline becomes active.
  2809. This variable governs the display in sparse trees and in the agenda.
  2810. When 0 or negative, it means use this number (the absolute value of it)
  2811. even if a deadline has a different individual lead time specified.
  2812. Custom commands can set this variable in the options section."
  2813. :group 'org-time
  2814. :group 'org-agenda-daily/weekly
  2815. :type 'integer)
  2816. (defcustom org-scheduled-delay-days 0
  2817. "Number of days before a scheduled item becomes active.
  2818. This variable governs the display in sparse trees and in the agenda.
  2819. The default value (i.e. 0) means: don't delay scheduled item.
  2820. When negative, it means use this number (the absolute value of it)
  2821. even if a scheduled item has a different individual delay time
  2822. specified.
  2823. Custom commands can set this variable in the options section."
  2824. :group 'org-time
  2825. :group 'org-agenda-daily/weekly
  2826. :version "24.4"
  2827. :package-version '(Org . "8.0")
  2828. :type 'integer)
  2829. (defcustom org-read-date-prefer-future t
  2830. "Non-nil means assume future for incomplete date input from user.
  2831. This affects the following situations:
  2832. 1. The user gives a month but not a year.
  2833. For example, if it is April and you enter \"feb 2\", this will be read
  2834. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2835. 2. The user gives a day, but no month.
  2836. For example, if today is the 15th, and you enter \"3\", Org will read
  2837. this as the third of *next* month. However, if you enter \"17\",
  2838. it will be considered as *this* month.
  2839. If you set this variable to the symbol `time', then also the following
  2840. will work:
  2841. 3. If the user gives a time.
  2842. If the time is before now, it will be interpreted as tomorrow.
  2843. Currently none of this works for ISO week specifications.
  2844. When this option is nil, the current day, month and year will always be
  2845. used as defaults.
  2846. See also `org-agenda-jump-prefer-future'."
  2847. :group 'org-time
  2848. :type '(choice
  2849. (const :tag "Never" nil)
  2850. (const :tag "Check month and day" t)
  2851. (const :tag "Check month, day, and time" time)))
  2852. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2853. "Should the agenda jump command prefer the future for incomplete dates?
  2854. The default is to do the same as configured in `org-read-date-prefer-future'.
  2855. But you can also set a deviating value here.
  2856. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2857. :group 'org-agenda
  2858. :group 'org-time
  2859. :version "24.1"
  2860. :type '(choice
  2861. (const :tag "Use org-read-date-prefer-future"
  2862. org-read-date-prefer-future)
  2863. (const :tag "Never" nil)
  2864. (const :tag "Always" t)))
  2865. (defcustom org-read-date-force-compatible-dates t
  2866. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2867. Depending on the system Emacs is running on, certain dates cannot
  2868. be represented with the type used internally to represent time.
  2869. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2870. correctly. Some systems allow for earlier dates, some for later,
  2871. some for both. One way to find out is to insert any date into an
  2872. Org buffer, putting the cursor on the year and hitting S-up and
  2873. S-down to test the range.
  2874. When this variable is set to t, the date/time prompt will not let
  2875. you specify dates outside the 1970-2037 range, so it is certain that
  2876. these dates will work in whatever version of Emacs you are
  2877. running, and also that you can move a file from one Emacs implementation
  2878. to another. Whenever Org is forcing the year for you, it will display
  2879. a message and beep.
  2880. When this variable is nil, Org will check if the date is
  2881. representable in the specific Emacs implementation you are using.
  2882. If not, it will force a year, usually the current year, and beep
  2883. to remind you. Currently this setting is not recommended because
  2884. the likelihood that you will open your Org files in an Emacs that
  2885. has limited date range is not negligible.
  2886. A workaround for this problem is to use diary sexp dates for time
  2887. stamps outside of this range."
  2888. :group 'org-time
  2889. :version "24.1"
  2890. :type 'boolean)
  2891. (defcustom org-read-date-display-live t
  2892. "Non-nil means display current interpretation of date prompt live.
  2893. This display will be in an overlay, in the minibuffer."
  2894. :group 'org-time
  2895. :type 'boolean)
  2896. (defvaralias 'org-popup-calendar-for-date-prompt
  2897. 'org-read-date-popup-calendar)
  2898. (defcustom org-read-date-popup-calendar t
  2899. "Non-nil means pop up a calendar when prompting for a date.
  2900. In the calendar, the date can be selected with mouse-1. However, the
  2901. minibuffer will also be active, and you can simply enter the date as well.
  2902. When nil, only the minibuffer will be available."
  2903. :group 'org-time
  2904. :type 'boolean)
  2905. (defcustom org-extend-today-until 0
  2906. "The hour when your day really ends. Must be an integer.
  2907. This has influence for the following applications:
  2908. - When switching the agenda to \"today\". It it is still earlier than
  2909. the time given here, the day recognized as TODAY is actually yesterday.
  2910. - When a date is read from the user and it is still before the time given
  2911. here, the current date and time will be assumed to be yesterday, 23:59.
  2912. Also, timestamps inserted in capture templates follow this rule.
  2913. IMPORTANT: This is a feature whose implementation is and likely will
  2914. remain incomplete. Really, it is only here because past midnight seems to
  2915. be the favorite working time of John Wiegley :-)"
  2916. :group 'org-time
  2917. :type 'integer)
  2918. (defcustom org-use-effective-time nil
  2919. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2920. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2921. \"effective time\" of any timestamps between midnight and 8am will be
  2922. 23:59 of the previous day."
  2923. :group 'org-time
  2924. :version "24.1"
  2925. :type 'boolean)
  2926. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2927. "When non-nil, use the last clock out time for `org-todo'.
  2928. Note that this option has precedence over the combined use of
  2929. `org-use-effective-time' and `org-extend-today-until'."
  2930. :group 'org-time
  2931. :version "24.4"
  2932. :package-version '(Org . "8.0")
  2933. :type 'boolean)
  2934. (defcustom org-edit-timestamp-down-means-later nil
  2935. "Non-nil means S-down will increase the time in a time stamp.
  2936. When nil, S-up will increase."
  2937. :group 'org-time
  2938. :type 'boolean)
  2939. (defcustom org-calendar-follow-timestamp-change t
  2940. "Non-nil means make the calendar window follow timestamp changes.
  2941. When a timestamp is modified and the calendar window is visible, it will be
  2942. moved to the new date."
  2943. :group 'org-time
  2944. :type 'boolean)
  2945. (defgroup org-tags nil
  2946. "Options concerning tags in Org mode."
  2947. :tag "Org Tags"
  2948. :group 'org)
  2949. (defcustom org-tag-alist nil
  2950. "Default tags available in Org files.
  2951. The value of this variable is an alist. Associations either:
  2952. (TAG)
  2953. (TAG . SELECT)
  2954. (SPECIAL)
  2955. where TAG is a tag as a string, SELECT is character, used to
  2956. select that tag through the fast tag selection interface, and
  2957. SPECIAL is one of the following keywords: `:startgroup',
  2958. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2959. `:newline'. These keywords are used to define a hierarchy of
  2960. tags. See manual for details.
  2961. When this variable is nil, Org mode bases tag input on what is
  2962. already in the buffer. The value can be overridden locally by
  2963. using a TAGS keyword, e.g.,
  2964. #+TAGS: tag1 tag2
  2965. See also `org-tag-persistent-alist' to sidestep this behavior."
  2966. :group 'org-tags
  2967. :type '(repeat
  2968. (choice
  2969. (cons :tag "Tag with key"
  2970. (string :tag "Tag name")
  2971. (character :tag "Access char"))
  2972. (list :tag "Tag" (string :tag "Tag name"))
  2973. (const :tag "Start radio group" (:startgroup))
  2974. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2975. (const :tag "Group tags delimiter" (:grouptags))
  2976. (const :tag "End radio group" (:endgroup))
  2977. (const :tag "End tag group, non distinct" (:endgrouptag))
  2978. (const :tag "New line" (:newline)))))
  2979. (defcustom org-tag-persistent-alist nil
  2980. "Tags always available in Org files.
  2981. The value of this variable is an alist. Associations either:
  2982. (TAG)
  2983. (TAG . SELECT)
  2984. (SPECIAL)
  2985. where TAG is a tag as a string, SELECT is a character, used to
  2986. select that tag through the fast tag selection interface, and
  2987. SPECIAL is one of the following keywords: `:startgroup',
  2988. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2989. `:newline'. These keywords are used to define a hierarchy of
  2990. tags. See manual for details.
  2991. Unlike to `org-tag-alist', tags defined in this variable do not
  2992. depend on a local TAGS keyword. Instead, to disable these tags
  2993. on a per-file basis, insert anywhere in the file:
  2994. #+STARTUP: noptag"
  2995. :group 'org-tags
  2996. :type '(repeat
  2997. (choice
  2998. (cons :tag "Tag with key"
  2999. (string :tag "Tag name")
  3000. (character :tag "Access char"))
  3001. (list :tag "Tag" (string :tag "Tag name"))
  3002. (const :tag "Start radio group" (:startgroup))
  3003. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3004. (const :tag "Group tags delimiter" (:grouptags))
  3005. (const :tag "End radio group" (:endgroup))
  3006. (const :tag "End tag group, non distinct" (:endgrouptag))
  3007. (const :tag "New line" (:newline)))))
  3008. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3009. "If non-nil, always offer completion for all tags of all agenda files.
  3010. Setting this variable locally allows for dynamic generation of tag
  3011. completions in capture buffers.
  3012. (add-hook \\='org-capture-mode-hook
  3013. (lambda ()
  3014. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3015. :group 'org-tags
  3016. :version "24.1"
  3017. :type 'boolean)
  3018. (defvar org-file-tags nil
  3019. "List of tags that can be inherited by all entries in the file.
  3020. The tags will be inherited if the variable `org-use-tag-inheritance'
  3021. says they should be.
  3022. This variable is populated from #+FILETAGS lines.")
  3023. (defcustom org-use-fast-tag-selection 'auto
  3024. "Non-nil means use fast tag selection scheme.
  3025. This is a special interface to select and deselect tags with single keys.
  3026. When nil, fast selection is never used.
  3027. When the symbol `auto', fast selection is used if and only if selection
  3028. characters for tags have been configured, either through the variable
  3029. `org-tag-alist' or through a #+TAGS line in the buffer.
  3030. When t, fast selection is always used and selection keys are assigned
  3031. automatically if necessary."
  3032. :group 'org-tags
  3033. :type '(choice
  3034. (const :tag "Always" t)
  3035. (const :tag "Never" nil)
  3036. (const :tag "When selection characters are configured" auto)))
  3037. (defcustom org-fast-tag-selection-single-key nil
  3038. "Non-nil means fast tag selection exits after first change.
  3039. When nil, you have to press RET to exit it.
  3040. During fast tag selection, you can toggle this flag with `C-c'.
  3041. This variable can also have the value `expert'. In this case, the window
  3042. displaying the tags menu is not even shown, until you press C-c again."
  3043. :group 'org-tags
  3044. :type '(choice
  3045. (const :tag "No" nil)
  3046. (const :tag "Yes" t)
  3047. (const :tag "Expert" expert)))
  3048. (defvar org-fast-tag-selection-include-todo nil
  3049. "Non-nil means fast tags selection interface will also offer TODO states.
  3050. This is an undocumented feature, you should not rely on it.")
  3051. (defcustom org-tags-column -77
  3052. "The column to which tags should be indented in a headline.
  3053. If this number is positive, it specifies the column. If it is negative,
  3054. it means that the tags should be flushright to that column. For example,
  3055. -80 works well for a normal 80 character screen.
  3056. When 0, place tags directly after headline text, with only one space in
  3057. between."
  3058. :group 'org-tags
  3059. :type 'integer)
  3060. (defcustom org-auto-align-tags t
  3061. "Non-nil keeps tags aligned when modifying headlines.
  3062. Some operations (i.e. demoting) change the length of a headline and
  3063. therefore shift the tags around. With this option turned on, after
  3064. each such operation the tags are again aligned to `org-tags-column'."
  3065. :group 'org-tags
  3066. :type 'boolean)
  3067. (defcustom org-use-tag-inheritance t
  3068. "Non-nil means tags in levels apply also for sublevels.
  3069. When nil, only the tags directly given in a specific line apply there.
  3070. This may also be a list of tags that should be inherited, or a regexp that
  3071. matches tags that should be inherited. Additional control is possible
  3072. with the variable `org-tags-exclude-from-inheritance' which gives an
  3073. explicit list of tags to be excluded from inheritance, even if the value of
  3074. `org-use-tag-inheritance' would select it for inheritance.
  3075. If this option is t, a match early-on in a tree can lead to a large
  3076. number of matches in the subtree when constructing the agenda or creating
  3077. a sparse tree. If you only want to see the first match in a tree during
  3078. a search, check out the variable `org-tags-match-list-sublevels'."
  3079. :group 'org-tags
  3080. :type '(choice
  3081. (const :tag "Not" nil)
  3082. (const :tag "Always" t)
  3083. (repeat :tag "Specific tags" (string :tag "Tag"))
  3084. (regexp :tag "Tags matched by regexp")))
  3085. (defcustom org-tags-exclude-from-inheritance nil
  3086. "List of tags that should never be inherited.
  3087. This is a way to exclude a few tags from inheritance. For way to do
  3088. the opposite, to actively allow inheritance for selected tags,
  3089. see the variable `org-use-tag-inheritance'."
  3090. :group 'org-tags
  3091. :type '(repeat (string :tag "Tag")))
  3092. (defun org-tag-inherit-p (tag)
  3093. "Check if TAG is one that should be inherited."
  3094. (cond
  3095. ((member tag org-tags-exclude-from-inheritance) nil)
  3096. ((eq org-use-tag-inheritance t) t)
  3097. ((not org-use-tag-inheritance) nil)
  3098. ((stringp org-use-tag-inheritance)
  3099. (string-match org-use-tag-inheritance tag))
  3100. ((listp org-use-tag-inheritance)
  3101. (member tag org-use-tag-inheritance))
  3102. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3103. (defcustom org-tags-match-list-sublevels t
  3104. "Non-nil means list also sublevels of headlines matching a search.
  3105. This variable applies to tags/property searches, and also to stuck
  3106. projects because this search is based on a tags match as well.
  3107. When set to the symbol `indented', sublevels are indented with
  3108. leading dots.
  3109. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3110. the sublevels of a headline matching a tag search often also match
  3111. the same search. Listing all of them can create very long lists.
  3112. Setting this variable to nil causes subtrees of a match to be skipped.
  3113. This variable is semi-obsolete and probably should always be true. It
  3114. is better to limit inheritance to certain tags using the variables
  3115. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3116. :group 'org-tags
  3117. :type '(choice
  3118. (const :tag "No, don't list them" nil)
  3119. (const :tag "Yes, do list them" t)
  3120. (const :tag "List them, indented with leading dots" indented)))
  3121. (defcustom org-tags-sort-function nil
  3122. "When set, tags are sorted using this function as a comparator."
  3123. :group 'org-tags
  3124. :type '(choice
  3125. (const :tag "No sorting" nil)
  3126. (const :tag "Alphabetical" org-string-collate-lessp)
  3127. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3128. (function :tag "Custom function" nil)))
  3129. (defvar org-tags-history nil
  3130. "History of minibuffer reads for tags.")
  3131. (defvar org-last-tags-completion-table nil
  3132. "The last used completion table for tags.")
  3133. (defvar org-after-tags-change-hook nil
  3134. "Hook that is run after the tags in a line have changed.")
  3135. (defgroup org-properties nil
  3136. "Options concerning properties in Org mode."
  3137. :tag "Org Properties"
  3138. :group 'org)
  3139. (defcustom org-property-format "%-10s %s"
  3140. "How property key/value pairs should be formatted by `indent-line'.
  3141. When `indent-line' hits a property definition, it will format the line
  3142. according to this format, mainly to make sure that the values are
  3143. lined-up with respect to each other."
  3144. :group 'org-properties
  3145. :type 'string)
  3146. (defcustom org-properties-postprocess-alist nil
  3147. "Alist of properties and functions to adjust inserted values.
  3148. Elements of this alist must be of the form
  3149. ([string] [function])
  3150. where [string] must be a property name and [function] must be a
  3151. lambda expression: this lambda expression must take one argument,
  3152. the value to adjust, and return the new value as a string.
  3153. For example, this element will allow the property \"Remaining\"
  3154. to be updated wrt the relation between the \"Effort\" property
  3155. and the clock summary:
  3156. ((\"Remaining\" (lambda(value)
  3157. (let ((clocksum (org-clock-sum-current-item))
  3158. (effort (org-duration-to-minutes
  3159. (org-entry-get (point) \"Effort\"))))
  3160. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3161. :group 'org-properties
  3162. :version "24.1"
  3163. :type '(alist :key-type (string :tag "Property")
  3164. :value-type (function :tag "Function")))
  3165. (defcustom org-use-property-inheritance nil
  3166. "Non-nil means properties apply also for sublevels.
  3167. This setting is chiefly used during property searches. Turning it on can
  3168. cause significant overhead when doing a search, which is why it is not
  3169. on by default.
  3170. When nil, only the properties directly given in the current entry count.
  3171. When t, every property is inherited. The value may also be a list of
  3172. properties that should have inheritance, or a regular expression matching
  3173. properties that should be inherited.
  3174. However, note that some special properties use inheritance under special
  3175. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3176. and the properties ending in \"_ALL\" when they are used as descriptor
  3177. for valid values of a property.
  3178. Note for programmers:
  3179. When querying an entry with `org-entry-get', you can control if inheritance
  3180. should be used. By default, `org-entry-get' looks only at the local
  3181. properties. You can request inheritance by setting the inherit argument
  3182. to t (to force inheritance) or to `selective' (to respect the setting
  3183. in this variable)."
  3184. :group 'org-properties
  3185. :type '(choice
  3186. (const :tag "Not" nil)
  3187. (const :tag "Always" t)
  3188. (repeat :tag "Specific properties" (string :tag "Property"))
  3189. (regexp :tag "Properties matched by regexp")))
  3190. (defun org-property-inherit-p (property)
  3191. "Return a non-nil value if PROPERTY should be inherited."
  3192. (cond
  3193. ((eq org-use-property-inheritance t) t)
  3194. ((not org-use-property-inheritance) nil)
  3195. ((stringp org-use-property-inheritance)
  3196. (string-match org-use-property-inheritance property))
  3197. ((listp org-use-property-inheritance)
  3198. (member-ignore-case property org-use-property-inheritance))
  3199. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3200. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3201. "The default column format, if no other format has been defined.
  3202. This variable can be set on the per-file basis by inserting a line
  3203. #+COLUMNS: %25ITEM ....."
  3204. :group 'org-properties
  3205. :type 'string)
  3206. (defcustom org-columns-ellipses ".."
  3207. "The ellipses to be used when a field in column view is truncated.
  3208. When this is the empty string, as many characters as possible are shown,
  3209. but then there will be no visual indication that the field has been truncated.
  3210. When this is a string of length N, the last N characters of a truncated
  3211. field are replaced by this string. If the column is narrower than the
  3212. ellipses string, only part of the ellipses string will be shown."
  3213. :group 'org-properties
  3214. :type 'string)
  3215. (defconst org-global-properties-fixed
  3216. '(("VISIBILITY_ALL" . "folded children content all")
  3217. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3218. "List of property/value pairs that can be inherited by any entry.
  3219. These are fixed values, for the preset properties. The user variable
  3220. that can be used to add to this list is `org-global-properties'.
  3221. The entries in this list are cons cells where the car is a property
  3222. name and cdr is a string with the value. If the value represents
  3223. multiple items like an \"_ALL\" property, separate the items by
  3224. spaces.")
  3225. (defcustom org-global-properties nil
  3226. "List of property/value pairs that can be inherited by any entry.
  3227. This list will be combined with the constant `org-global-properties-fixed'.
  3228. The entries in this list are cons cells where the car is a property
  3229. name and cdr is a string with the value.
  3230. You can set buffer-local values for the same purpose in the variable
  3231. `org-file-properties' this by adding lines like
  3232. #+PROPERTY: NAME VALUE"
  3233. :group 'org-properties
  3234. :type '(repeat
  3235. (cons (string :tag "Property")
  3236. (string :tag "Value"))))
  3237. (defvar-local org-file-properties nil
  3238. "List of property/value pairs that can be inherited by any entry.
  3239. Valid for the current buffer.
  3240. This variable is populated from #+PROPERTY lines.")
  3241. (defgroup org-agenda nil
  3242. "Options concerning agenda views in Org mode."
  3243. :tag "Org Agenda"
  3244. :group 'org)
  3245. (defvar-local org-category nil
  3246. "Variable used by Org files to set a category for agenda display.
  3247. Such files should use a file variable to set it, for example
  3248. # -*- mode: org; org-category: \"ELisp\"
  3249. or contain a special line
  3250. #+CATEGORY: ELisp
  3251. If the file does not specify a category, then file's base name
  3252. is used instead.")
  3253. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3254. (defcustom org-agenda-files nil
  3255. "The files to be used for agenda display.
  3256. If an entry is a directory, all files in that directory that are matched
  3257. by `org-agenda-file-regexp' will be part of the file list.
  3258. If the value of the variable is not a list but a single file name, then
  3259. the list of agenda files is actually stored and maintained in that file,
  3260. one agenda file per line. In this file paths can be given relative to
  3261. `org-directory'. Tilde expansion and environment variable substitution
  3262. are also made.
  3263. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3264. and removed with `\\[org-remove-file]'."
  3265. :group 'org-agenda
  3266. :type '(choice
  3267. (repeat :tag "List of files and directories" file)
  3268. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3269. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3270. "Regular expression to match files for `org-agenda-files'.
  3271. If any element in the list in that variable contains a directory instead
  3272. of a normal file, all files in that directory that are matched by this
  3273. regular expression will be included."
  3274. :group 'org-agenda
  3275. :type 'regexp)
  3276. (defvaralias 'org-agenda-multi-occur-extra-files
  3277. 'org-agenda-text-search-extra-files)
  3278. (defcustom org-agenda-text-search-extra-files nil
  3279. "List of extra files to be searched by text search commands.
  3280. These files will be searched in addition to the agenda files by the
  3281. commands `org-search-view' (`\\[org-agenda] s') \
  3282. and `org-occur-in-agenda-files'.
  3283. Note that these files will only be searched for text search commands,
  3284. not for the other agenda views like todo lists, tag searches or the weekly
  3285. agenda. This variable is intended to list notes and possibly archive files
  3286. that should also be searched by these two commands.
  3287. In fact, if the first element in the list is the symbol `agenda-archives',
  3288. then all archive files of all agenda files will be added to the search
  3289. scope."
  3290. :group 'org-agenda
  3291. :type '(set :greedy t
  3292. (const :tag "Agenda Archives" agenda-archives)
  3293. (repeat :inline t (file))))
  3294. (defcustom org-agenda-skip-unavailable-files nil
  3295. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3296. A nil value means to remove them, after a query, from the list."
  3297. :group 'org-agenda
  3298. :type 'boolean)
  3299. (defcustom org-agenda-diary-file 'diary-file
  3300. "File to which to add new entries with the `i' key in agenda and calendar.
  3301. When this is the symbol `diary-file', the functionality in the Emacs
  3302. calendar will be used to add entries to the `diary-file'. But when this
  3303. points to a file, `org-agenda-diary-entry' will be used instead."
  3304. :group 'org-agenda
  3305. :type '(choice
  3306. (const :tag "The standard Emacs diary file" diary-file)
  3307. (file :tag "Special Org file diary entries")))
  3308. (defgroup org-latex nil
  3309. "Options for embedding LaTeX code into Org mode."
  3310. :tag "Org LaTeX"
  3311. :group 'org)
  3312. (defcustom org-format-latex-options
  3313. '(:foreground default :background default :scale 1.0
  3314. :html-foreground "Black" :html-background "Transparent"
  3315. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3316. "Options for creating images from LaTeX fragments.
  3317. This is a property list with the following properties:
  3318. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3319. `default' means use the foreground of the default face.
  3320. `auto' means use the foreground from the text face.
  3321. :background the background color, or \"Transparent\".
  3322. `default' means use the background of the default face.
  3323. `auto' means use the background from the text face.
  3324. :scale a scaling factor for the size of the images, to get more pixels
  3325. :html-foreground, :html-background, :html-scale
  3326. the same numbers for HTML export.
  3327. :matchers a list indicating which matchers should be used to
  3328. find LaTeX fragments. Valid members of this list are:
  3329. \"begin\" find environments
  3330. \"$1\" find single characters surrounded by $.$
  3331. \"$\" find math expressions surrounded by $...$
  3332. \"$$\" find math expressions surrounded by $$....$$
  3333. \"\\(\" find math expressions surrounded by \\(...\\)
  3334. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3335. :group 'org-latex
  3336. :type 'plist)
  3337. (defcustom org-format-latex-signal-error t
  3338. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3339. When nil, just push out a message."
  3340. :group 'org-latex
  3341. :version "24.1"
  3342. :type 'boolean)
  3343. (defcustom org-latex-to-mathml-jar-file nil
  3344. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3345. Use this to specify additional executable file say a jar file.
  3346. When using MathToWeb as the converter, specify the full-path to
  3347. your mathtoweb.jar file."
  3348. :group 'org-latex
  3349. :version "24.1"
  3350. :type '(choice
  3351. (const :tag "None" nil)
  3352. (file :tag "JAR file" :must-match t)))
  3353. (defcustom org-latex-to-mathml-convert-command nil
  3354. "Command to convert LaTeX fragments to MathML.
  3355. Replace format-specifiers in the command as noted below and use
  3356. `shell-command' to convert LaTeX to MathML.
  3357. %j: Executable file in fully expanded form as specified by
  3358. `org-latex-to-mathml-jar-file'.
  3359. %I: Input LaTeX file in fully expanded form.
  3360. %i: The latex fragment to be converted.
  3361. %o: Output MathML file.
  3362. This command is used by `org-create-math-formula'.
  3363. When using MathToWeb as the converter, set this option to
  3364. \"java -jar %j -unicode -force -df %o %I\".
  3365. When using LaTeXML set this option to
  3366. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3367. :group 'org-latex
  3368. :version "24.1"
  3369. :type '(choice
  3370. (const :tag "None" nil)
  3371. (string :tag "\nShell command")))
  3372. (defcustom org-preview-latex-default-process 'dvipng
  3373. "The default process to convert LaTeX fragments to image files.
  3374. All available processes and theirs documents can be found in
  3375. `org-preview-latex-process-alist', which see."
  3376. :group 'org-latex
  3377. :version "26.1"
  3378. :package-version '(Org . "9.0")
  3379. :type 'symbol)
  3380. (defcustom org-preview-latex-process-alist
  3381. '((dvipng
  3382. :programs ("latex" "dvipng")
  3383. :description "dvi > png"
  3384. :message "you need to install the programs: latex and dvipng."
  3385. :image-input-type "dvi"
  3386. :image-output-type "png"
  3387. :image-size-adjust (1.0 . 1.0)
  3388. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3389. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3390. (dvisvgm
  3391. :programs ("latex" "dvisvgm")
  3392. :description "dvi > svg"
  3393. :message "you need to install the programs: latex and dvisvgm."
  3394. :use-xcolor t
  3395. :image-input-type "dvi"
  3396. :image-output-type "svg"
  3397. :image-size-adjust (1.7 . 1.5)
  3398. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3399. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3400. (imagemagick
  3401. :programs ("latex" "convert")
  3402. :description "pdf > png"
  3403. :message "you need to install the programs: latex and imagemagick."
  3404. :use-xcolor t
  3405. :image-input-type "pdf"
  3406. :image-output-type "png"
  3407. :image-size-adjust (1.0 . 1.0)
  3408. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3409. :image-converter
  3410. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3411. "Definitions of external processes for LaTeX previewing.
  3412. Org mode can use some external commands to generate TeX snippet's images for
  3413. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3414. `org-create-formula-image' how to call them.
  3415. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3416. PROPERTIES accepts the following attributes:
  3417. :programs list of strings, required programs.
  3418. :description string, describe the process.
  3419. :message string, message it when required programs cannot be found.
  3420. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3421. :image-output-type string, output file type of image converter (e.g., \"png\").
  3422. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3423. deal with background and foreground color of image.
  3424. Otherwise, dvipng style background and foreground color
  3425. format are generated. You may then refer to them in
  3426. command options with \"%F\" and \"%B\".
  3427. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3428. image size showed in buffer and the cdr element is for
  3429. HTML file. This option is only useful for process
  3430. developers, users should use variable
  3431. `org-format-latex-options' instead.
  3432. :post-clean list of strings, files matched are to be cleaned up once
  3433. the image is generated. When nil, the files with \".dvi\",
  3434. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3435. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3436. be cleaned up.
  3437. :latex-header list of strings, the LaTeX header of the snippet file.
  3438. When nil, the fallback value is used instead, which is
  3439. controlled by `org-format-latex-header',
  3440. `org-latex-default-packages-alist' and
  3441. `org-latex-packages-alist', which see.
  3442. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3443. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3444. replaced with values defined below.
  3445. :image-converter list of image converter commands strings. Each of them is
  3446. given to the shell and supports any of the following
  3447. place-holders defined below.
  3448. Place-holders used by `:image-converter' and `:latex-compiler':
  3449. %f input file name
  3450. %b base name of input file
  3451. %o base directory of input file
  3452. %O absolute output file name
  3453. Place-holders only used by `:image-converter':
  3454. %F foreground of image
  3455. %B background of image
  3456. %D dpi, which is used to adjust image size by some processing commands.
  3457. %S the image size scale ratio, which is used to adjust image size by some
  3458. processing commands."
  3459. :group 'org-latex
  3460. :version "26.1"
  3461. :package-version '(Org . "9.0")
  3462. :type '(alist :tag "LaTeX to image backends"
  3463. :value-type (plist)))
  3464. (defcustom org-preview-latex-image-directory "ltximg/"
  3465. "Path to store latex preview images.
  3466. A relative path here creates many directories relative to the
  3467. processed Org files paths. An absolute path puts all preview
  3468. images at the same place."
  3469. :group 'org-latex
  3470. :version "26.1"
  3471. :package-version '(Org . "9.0")
  3472. :type 'string)
  3473. (defun org-format-latex-mathml-available-p ()
  3474. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3475. (save-match-data
  3476. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3477. org-latex-to-mathml-convert-command)
  3478. (let ((executable (car (split-string
  3479. org-latex-to-mathml-convert-command))))
  3480. (when (executable-find executable)
  3481. (if (string-match
  3482. "%j" org-latex-to-mathml-convert-command)
  3483. (file-readable-p org-latex-to-mathml-jar-file)
  3484. t))))))
  3485. (defcustom org-format-latex-header "\\documentclass{article}
  3486. \\usepackage[usenames]{color}
  3487. \[PACKAGES]
  3488. \[DEFAULT-PACKAGES]
  3489. \\pagestyle{empty} % do not remove
  3490. % The settings below are copied from fullpage.sty
  3491. \\setlength{\\textwidth}{\\paperwidth}
  3492. \\addtolength{\\textwidth}{-3cm}
  3493. \\setlength{\\oddsidemargin}{1.5cm}
  3494. \\addtolength{\\oddsidemargin}{-2.54cm}
  3495. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3496. \\setlength{\\textheight}{\\paperheight}
  3497. \\addtolength{\\textheight}{-\\headheight}
  3498. \\addtolength{\\textheight}{-\\headsep}
  3499. \\addtolength{\\textheight}{-\\footskip}
  3500. \\addtolength{\\textheight}{-3cm}
  3501. \\setlength{\\topmargin}{1.5cm}
  3502. \\addtolength{\\topmargin}{-2.54cm}"
  3503. "The document header used for processing LaTeX fragments.
  3504. It is imperative that this header make sure that no page number
  3505. appears on the page. The package defined in the variables
  3506. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3507. will either replace the placeholder \"[PACKAGES]\" in this
  3508. header, or they will be appended."
  3509. :group 'org-latex
  3510. :type 'string)
  3511. (defun org-set-packages-alist (var val)
  3512. "Set the packages alist and make sure it has 3 elements per entry."
  3513. (set var (mapcar (lambda (x)
  3514. (if (and (consp x) (= (length x) 2))
  3515. (list (car x) (nth 1 x) t)
  3516. x))
  3517. val)))
  3518. (defun org-get-packages-alist (var)
  3519. "Get the packages alist and make sure it has 3 elements per entry."
  3520. (mapcar (lambda (x)
  3521. (if (and (consp x) (= (length x) 2))
  3522. (list (car x) (nth 1 x) t)
  3523. x))
  3524. (default-value var)))
  3525. (defcustom org-latex-default-packages-alist
  3526. '(("AUTO" "inputenc" t ("pdflatex"))
  3527. ("T1" "fontenc" t ("pdflatex"))
  3528. ("" "graphicx" t)
  3529. ("" "grffile" t)
  3530. ("" "longtable" nil)
  3531. ("" "wrapfig" nil)
  3532. ("" "rotating" nil)
  3533. ("normalem" "ulem" t)
  3534. ("" "amsmath" t)
  3535. ("" "textcomp" t)
  3536. ("" "amssymb" t)
  3537. ("" "capt-of" nil)
  3538. ("" "hyperref" nil))
  3539. "Alist of default packages to be inserted in the header.
  3540. Change this only if one of the packages here causes an
  3541. incompatibility with another package you are using.
  3542. The packages in this list are needed by one part or another of
  3543. Org mode to function properly:
  3544. - inputenc, fontenc: for basic font and character selection
  3545. - graphicx: for including images
  3546. - grffile: allow periods and spaces in graphics file names
  3547. - longtable: For multipage tables
  3548. - wrapfig: for figure placement
  3549. - rotating: for sideways figures and tables
  3550. - ulem: for underline and strike-through
  3551. - amsmath: for subscript and superscript and math environments
  3552. - textcomp, amssymb: for various symbols used
  3553. for interpreting the entities in `org-entities'. You can skip
  3554. some of these packages if you don't use any of their symbols.
  3555. - capt-of: for captions outside of floats
  3556. - hyperref: for cross references
  3557. Therefore you should not modify this variable unless you know
  3558. what you are doing. The one reason to change it anyway is that
  3559. you might be loading some other package that conflicts with one
  3560. of the default packages. Each element is either a cell or
  3561. a string.
  3562. A cell is of the format
  3563. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3564. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3565. when compiling LaTeX snippets into images for inclusion into
  3566. non-LaTeX output.
  3567. COMPILERS is a list of compilers that should include the package,
  3568. see `org-latex-compiler'. If the document compiler is not in the
  3569. list, and the list is non-nil, the package will not be inserted
  3570. in the final document.
  3571. A string will be inserted as-is in the header of the document."
  3572. :group 'org-latex
  3573. :group 'org-export-latex
  3574. :set 'org-set-packages-alist
  3575. :get 'org-get-packages-alist
  3576. :version "26.1"
  3577. :package-version '(Org . "8.3")
  3578. :type '(repeat
  3579. (choice
  3580. (list :tag "options/package pair"
  3581. (string :tag "options")
  3582. (string :tag "package")
  3583. (boolean :tag "Snippet")
  3584. (choice
  3585. (const :tag "For all compilers" nil)
  3586. (repeat :tag "Allowed compiler" string)))
  3587. (string :tag "A line of LaTeX"))))
  3588. (defcustom org-latex-packages-alist nil
  3589. "Alist of packages to be inserted in every LaTeX header.
  3590. These will be inserted after `org-latex-default-packages-alist'.
  3591. Each element is either a cell or a string.
  3592. A cell is of the format:
  3593. (\"options\" \"package\" SNIPPET-FLAG)
  3594. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3595. needed when turning LaTeX snippets into images for inclusion into
  3596. non-LaTeX output.
  3597. COMPILERS is a list of compilers that should include the package,
  3598. see `org-latex-compiler'. If the document compiler is not in the
  3599. list, and the list is non-nil, the package will not be inserted
  3600. in the final document.
  3601. A string will be inserted as-is in the header of the document.
  3602. Make sure that you only list packages here which:
  3603. - you want in every file;
  3604. - do not conflict with the setup in `org-format-latex-header';
  3605. - do not conflict with the default packages in
  3606. `org-latex-default-packages-alist'."
  3607. :group 'org-latex
  3608. :group 'org-export-latex
  3609. :set 'org-set-packages-alist
  3610. :get 'org-get-packages-alist
  3611. :type '(repeat
  3612. (choice
  3613. (list :tag "options/package pair"
  3614. (string :tag "options")
  3615. (string :tag "package")
  3616. (boolean :tag "Snippet"))
  3617. (string :tag "A line of LaTeX"))))
  3618. (defgroup org-appearance nil
  3619. "Settings for Org mode appearance."
  3620. :tag "Org Appearance"
  3621. :group 'org)
  3622. (defcustom org-level-color-stars-only nil
  3623. "Non-nil means fontify only the stars in each headline.
  3624. When nil, the entire headline is fontified.
  3625. Changing it requires restart of `font-lock-mode' to become effective
  3626. also in regions already fontified."
  3627. :group 'org-appearance
  3628. :type 'boolean)
  3629. (defcustom org-hide-leading-stars nil
  3630. "Non-nil means hide the first N-1 stars in a headline.
  3631. This works by using the face `org-hide' for these stars. This
  3632. face is white for a light background, and black for a dark
  3633. background. You may have to customize the face `org-hide' to
  3634. make this work.
  3635. Changing it requires restart of `font-lock-mode' to become effective
  3636. also in regions already fontified.
  3637. You may also set this on a per-file basis by adding one of the following
  3638. lines to the buffer:
  3639. #+STARTUP: hidestars
  3640. #+STARTUP: showstars"
  3641. :group 'org-appearance
  3642. :type 'boolean)
  3643. (defcustom org-hidden-keywords nil
  3644. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3645. For example, a value \\='(title) for this list makes the document's title
  3646. appear in the buffer without the initial \"#+TITLE:\" part."
  3647. :group 'org-appearance
  3648. :version "24.1"
  3649. :type '(set (const :tag "#+AUTHOR" author)
  3650. (const :tag "#+DATE" date)
  3651. (const :tag "#+EMAIL" email)
  3652. (const :tag "#+TITLE" title)))
  3653. (defcustom org-custom-properties nil
  3654. "List of properties (as strings) with a special meaning.
  3655. The default use of these custom properties is to let the user
  3656. hide them with `org-toggle-custom-properties-visibility'."
  3657. :group 'org-properties
  3658. :group 'org-appearance
  3659. :version "24.3"
  3660. :type '(repeat (string :tag "Property Name")))
  3661. (defcustom org-fontify-done-headline nil
  3662. "Non-nil means change the face of a headline if it is marked DONE.
  3663. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3664. When this is non-nil, the headline after the keyword is set to the
  3665. `org-headline-done' as an additional indication."
  3666. :group 'org-appearance
  3667. :type 'boolean)
  3668. (defcustom org-fontify-emphasized-text t
  3669. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3670. Changing this variable requires a restart of Emacs to take effect."
  3671. :group 'org-appearance
  3672. :type 'boolean)
  3673. (defcustom org-fontify-whole-heading-line nil
  3674. "Non-nil means fontify the whole line for headings.
  3675. This is useful when setting a background color for the
  3676. org-level-* faces."
  3677. :group 'org-appearance
  3678. :type 'boolean)
  3679. (defcustom org-highlight-latex-and-related nil
  3680. "Non-nil means highlight LaTeX related syntax in the buffer.
  3681. When non nil, the value should be a list containing any of the
  3682. following symbols:
  3683. `latex' Highlight LaTeX snippets and environments.
  3684. `script' Highlight subscript and superscript.
  3685. `entities' Highlight entities."
  3686. :group 'org-appearance
  3687. :version "24.4"
  3688. :package-version '(Org . "8.0")
  3689. :type '(choice
  3690. (const :tag "No highlighting" nil)
  3691. (set :greedy t :tag "Highlight"
  3692. (const :tag "LaTeX snippets and environments" latex)
  3693. (const :tag "Subscript and superscript" script)
  3694. (const :tag "Entities" entities))))
  3695. (defcustom org-hide-emphasis-markers nil
  3696. "Non-nil mean font-lock should hide the emphasis marker characters."
  3697. :group 'org-appearance
  3698. :type 'boolean
  3699. :safe #'booleanp)
  3700. (defcustom org-hide-macro-markers nil
  3701. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3702. :group 'org-appearance
  3703. :type 'boolean)
  3704. (defcustom org-pretty-entities nil
  3705. "Non-nil means show entities as UTF8 characters.
  3706. When nil, the \\name form remains in the buffer."
  3707. :group 'org-appearance
  3708. :version "24.1"
  3709. :type 'boolean)
  3710. (defcustom org-pretty-entities-include-sub-superscripts t
  3711. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3712. :group 'org-appearance
  3713. :version "24.1"
  3714. :type 'boolean)
  3715. (defvar org-emph-re nil
  3716. "Regular expression for matching emphasis.
  3717. After a match, the match groups contain these elements:
  3718. 0 The match of the full regular expression, including the characters
  3719. before and after the proper match
  3720. 1 The character before the proper match, or empty at beginning of line
  3721. 2 The proper match, including the leading and trailing markers
  3722. 3 The leading marker like * or /, indicating the type of highlighting
  3723. 4 The text between the emphasis markers, not including the markers
  3724. 5 The character after the match, empty at the end of a line")
  3725. (defvar org-verbatim-re nil
  3726. "Regular expression for matching verbatim text.")
  3727. (defvar org-emphasis-regexp-components) ; defined just below
  3728. (defvar org-emphasis-alist) ; defined just below
  3729. (defun org-set-emph-re (var val)
  3730. "Set variable and compute the emphasis regular expression."
  3731. (set var val)
  3732. (when (and (boundp 'org-emphasis-alist)
  3733. (boundp 'org-emphasis-regexp-components)
  3734. org-emphasis-alist org-emphasis-regexp-components)
  3735. (pcase-let*
  3736. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3737. (body (if (<= nl 0) body
  3738. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3739. (template
  3740. (format (concat "\\([%s]\\|^\\)" ;before markers
  3741. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3742. "\\([%s]\\|$\\)") ;after markers
  3743. pre border border body border post)))
  3744. (setq org-emph-re (format template "*/_+"))
  3745. (setq org-verbatim-re (format template "=~")))))
  3746. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3747. ;; set this option proved cumbersome. See this message/thread:
  3748. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3749. (defvar org-emphasis-regexp-components
  3750. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3751. "Components used to build the regular expression for emphasis.
  3752. This is a list with five entries. Terminology: In an emphasis string
  3753. like \" *strong word* \", we call the initial space PREMATCH, the final
  3754. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3755. and \"trong wor\" is the body. The different components in this variable
  3756. specify what is allowed/forbidden in each part:
  3757. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3758. post Chars allowed as postmatch. End of line will be allowed too.
  3759. border The chars *forbidden* as border characters.
  3760. body-regexp A regexp like \".\" to match a body character. Don't use
  3761. non-shy groups here, and don't allow newline here.
  3762. newline The maximum number of newlines allowed in an emphasis exp.
  3763. You need to reload Org or to restart Emacs after setting this.")
  3764. (defcustom org-emphasis-alist
  3765. '(("*" bold)
  3766. ("/" italic)
  3767. ("_" underline)
  3768. ("=" org-verbatim verbatim)
  3769. ("~" org-code verbatim)
  3770. ("+" (:strike-through t)))
  3771. "Alist of characters and faces to emphasize text.
  3772. Text starting and ending with a special character will be emphasized,
  3773. for example *bold*, _underlined_ and /italic/. This variable sets the
  3774. marker characters and the face to be used by font-lock for highlighting
  3775. in Org buffers.
  3776. You need to reload Org or to restart Emacs after customizing this."
  3777. :group 'org-appearance
  3778. :set 'org-set-emph-re
  3779. :version "24.4"
  3780. :package-version '(Org . "8.0")
  3781. :type '(repeat
  3782. (list
  3783. (string :tag "Marker character")
  3784. (choice
  3785. (face :tag "Font-lock-face")
  3786. (plist :tag "Face property list"))
  3787. (option (const verbatim)))))
  3788. (defvar org-protecting-blocks '("src" "example" "export")
  3789. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3790. This is needed for font-lock setup.")
  3791. ;;; Functions and variables from their packages
  3792. ;; Declared here to avoid compiler warnings
  3793. (defvar mark-active)
  3794. ;; Various packages
  3795. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3796. (declare-function calendar-forward-day "cal-move" (arg))
  3797. (declare-function calendar-goto-date "cal-move" (date))
  3798. (declare-function calendar-goto-today "cal-move" ())
  3799. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3800. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3801. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3802. (declare-function cdlatex-tab "ext:cdlatex" ())
  3803. (declare-function dired-get-filename
  3804. "dired"
  3805. (&optional localp no-error-if-not-filep))
  3806. (declare-function iswitchb-read-buffer
  3807. "iswitchb"
  3808. (prompt &optional
  3809. default require-match _predicate start matches-set))
  3810. (declare-function org-agenda-change-all-lines
  3811. "org-agenda"
  3812. (newhead hdmarker &optional fixface just-this))
  3813. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3814. "org-agenda"
  3815. (&optional end))
  3816. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3817. (declare-function org-agenda-format-item
  3818. "org-agenda"
  3819. (extra txt &optional level category tags dotime
  3820. remove-re habitp))
  3821. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3822. (declare-function org-agenda-save-markers-for-cut-and-paste
  3823. "org-agenda"
  3824. (beg end))
  3825. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3826. (declare-function org-agenda-skip "org-agenda" ())
  3827. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3828. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3829. (declare-function org-indent-mode "org-indent" (&optional arg))
  3830. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3831. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3832. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3833. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3834. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3835. (declare-function parse-time-string "parse-time" (string))
  3836. (defvar align-mode-rules-list)
  3837. (defvar calc-embedded-close-formula)
  3838. (defvar calc-embedded-open-formula)
  3839. (defvar calc-embedded-open-mode)
  3840. (defvar font-lock-unfontify-region-function)
  3841. (defvar iswitchb-temp-buflist)
  3842. (defvar org-agenda-tags-todo-honor-ignore-options)
  3843. (defvar remember-data-file)
  3844. (defvar texmathp-why)
  3845. ;;;###autoload
  3846. (defun turn-on-orgtbl ()
  3847. "Unconditionally turn on `orgtbl-mode'."
  3848. (require 'org-table)
  3849. (orgtbl-mode 1))
  3850. (defun org-at-table-p (&optional table-type)
  3851. "Non-nil if the cursor is inside an Org table.
  3852. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3853. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3854. (or (not (derived-mode-p 'org-mode))
  3855. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3856. (and e (or table-type
  3857. (eq 'org (org-element-property :type e))))))))
  3858. (defun org-at-table.el-p ()
  3859. "Non-nil when point is at a table.el table."
  3860. (and (org-match-line "[ \t]*[|+]")
  3861. (let ((element (org-element-at-point)))
  3862. (and (eq (org-element-type element) 'table)
  3863. (eq (org-element-property :type element) 'table.el)))))
  3864. (defun org-at-table-hline-p ()
  3865. "Non-nil when point is inside a hline in a table.
  3866. Assume point is already in a table."
  3867. (org-match-line org-table-hline-regexp))
  3868. (defun org-table-map-tables (function &optional quietly)
  3869. "Apply FUNCTION to the start of all tables in the buffer."
  3870. (org-with-wide-buffer
  3871. (goto-char (point-min))
  3872. (while (re-search-forward org-table-any-line-regexp nil t)
  3873. (unless quietly
  3874. (message "Mapping tables: %d%%"
  3875. (floor (* 100.0 (point)) (buffer-size))))
  3876. (beginning-of-line 1)
  3877. (when (and (looking-at org-table-line-regexp)
  3878. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3879. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3880. (save-excursion (funcall function))
  3881. (or (looking-at org-table-line-regexp)
  3882. (forward-char 1)))
  3883. (re-search-forward org-table-any-border-regexp nil 1)))
  3884. (unless quietly (message "Mapping tables: done")))
  3885. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3886. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3887. (declare-function org-resolve-clocks "org-clock"
  3888. (&optional also-non-dangling-p prompt last-valid))
  3889. (defun org-at-TBLFM-p (&optional pos)
  3890. "Non-nil when point (or POS) is in #+TBLFM line."
  3891. (save-excursion
  3892. (goto-char (or pos (point)))
  3893. (beginning-of-line)
  3894. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3895. (eq (org-element-type (org-element-at-point)) 'table))))
  3896. (defvar org-clock-start-time)
  3897. (defvar org-clock-marker (make-marker)
  3898. "Marker recording the last clock-in.")
  3899. (defvar org-clock-hd-marker (make-marker)
  3900. "Marker recording the last clock-in, but the headline position.")
  3901. (defvar org-clock-heading ""
  3902. "The heading of the current clock entry.")
  3903. (defun org-clock-is-active ()
  3904. "Return the buffer where the clock is currently running.
  3905. Return nil if no clock is running."
  3906. (marker-buffer org-clock-marker))
  3907. (defun org-check-running-clock ()
  3908. "Check if the current buffer contains the running clock.
  3909. If yes, offer to stop it and to save the buffer with the changes."
  3910. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3911. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3912. (buffer-name))))
  3913. (org-clock-out)
  3914. (when (y-or-n-p "Save changed buffer?")
  3915. (save-buffer))))
  3916. (defun org-clocktable-try-shift (dir n)
  3917. "Check if this line starts a clock table, if yes, shift the time block."
  3918. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3919. (org-clocktable-shift dir n)))
  3920. ;;;###autoload
  3921. (defun org-clock-persistence-insinuate ()
  3922. "Set up hooks for clock persistence."
  3923. (require 'org-clock)
  3924. (add-hook 'org-mode-hook 'org-clock-load)
  3925. (add-hook 'kill-emacs-hook 'org-clock-save))
  3926. (defgroup org-archive nil
  3927. "Options concerning archiving in Org mode."
  3928. :tag "Org Archive"
  3929. :group 'org-structure)
  3930. (defcustom org-archive-location "%s_archive::"
  3931. "The location where subtrees should be archived.
  3932. The value of this variable is a string, consisting of two parts,
  3933. separated by a double-colon. The first part is a filename and
  3934. the second part is a headline.
  3935. When the filename is omitted, archiving happens in the same file.
  3936. %s in the filename will be replaced by the current file
  3937. name (without the directory part). Archiving to a different file
  3938. is useful to keep archived entries from contributing to the
  3939. Org Agenda.
  3940. The archived entries will be filed as subtrees of the specified
  3941. headline. When the headline is omitted, the subtrees are simply
  3942. filed away at the end of the file, as top-level entries. Also in
  3943. the heading you can use %s to represent the file name, this can be
  3944. useful when using the same archive for a number of different files.
  3945. Here are a few examples:
  3946. \"%s_archive::\"
  3947. If the current file is Projects.org, archive in file
  3948. Projects.org_archive, as top-level trees. This is the default.
  3949. \"::* Archived Tasks\"
  3950. Archive in the current file, under the top-level headline
  3951. \"* Archived Tasks\".
  3952. \"~/org/archive.org::\"
  3953. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3954. \"~/org/archive.org::* From %s\"
  3955. Archive in file ~/org/archive.org (absolute path), under headlines
  3956. \"From FILENAME\" where file name is the current file name.
  3957. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3958. The \"datetree/\" string is special, signifying to archive
  3959. items to the datetree. Items are placed in either the CLOSED
  3960. date of the item, or the current date if there is no CLOSED date.
  3961. The heading will be a subentry to the current date. There doesn't
  3962. need to be a heading, but there always needs to be a slash after
  3963. datetree. For example, to store archived items directly in the
  3964. datetree, use \"~/org/datetree.org::datetree/\".
  3965. \"basement::** Finished Tasks\"
  3966. Archive in file ./basement (relative path), as level 3 trees
  3967. below the level 2 heading \"** Finished Tasks\".
  3968. You may set this option on a per-file basis by adding to the buffer a
  3969. line like
  3970. #+ARCHIVE: basement::** Finished Tasks
  3971. You may also define it locally for a subtree by setting an ARCHIVE property
  3972. in the entry. If such a property is found in an entry, or anywhere up
  3973. the hierarchy, it will be used."
  3974. :group 'org-archive
  3975. :type 'string)
  3976. (defcustom org-agenda-skip-archived-trees t
  3977. "Non-nil means the agenda will skip any items located in archived trees.
  3978. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3979. variable is no longer recommended, you should leave it at the value t.
  3980. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3981. :group 'org-archive
  3982. :group 'org-agenda-skip
  3983. :type 'boolean)
  3984. (defcustom org-columns-skip-archived-trees t
  3985. "Non-nil means ignore archived trees when creating column view."
  3986. :group 'org-archive
  3987. :group 'org-properties
  3988. :type 'boolean)
  3989. (defcustom org-cycle-open-archived-trees nil
  3990. "Non-nil means `org-cycle' will open archived trees.
  3991. An archived tree is a tree marked with the tag ARCHIVE.
  3992. When nil, archived trees will stay folded. You can still open them with
  3993. normal outline commands like `show-all', but not with the cycling commands."
  3994. :group 'org-archive
  3995. :group 'org-cycle
  3996. :type 'boolean)
  3997. (defcustom org-sparse-tree-open-archived-trees nil
  3998. "Non-nil means sparse tree construction shows matches in archived trees.
  3999. When nil, matches in these trees are highlighted, but the trees are kept in
  4000. collapsed state."
  4001. :group 'org-archive
  4002. :group 'org-sparse-trees
  4003. :type 'boolean)
  4004. (defcustom org-sparse-tree-default-date-type nil
  4005. "The default date type when building a sparse tree.
  4006. When this is nil, a date is a scheduled or a deadline timestamp.
  4007. Otherwise, these types are allowed:
  4008. all: all timestamps
  4009. active: only active timestamps (<...>)
  4010. inactive: only inactive timestamps ([...])
  4011. scheduled: only scheduled timestamps
  4012. deadline: only deadline timestamps"
  4013. :type '(choice (const :tag "Scheduled or deadline" nil)
  4014. (const :tag "All timestamps" all)
  4015. (const :tag "Only active timestamps" active)
  4016. (const :tag "Only inactive timestamps" inactive)
  4017. (const :tag "Only scheduled timestamps" scheduled)
  4018. (const :tag "Only deadline timestamps" deadline)
  4019. (const :tag "Only closed timestamps" closed))
  4020. :version "26.1"
  4021. :package-version '(Org . "8.3")
  4022. :group 'org-sparse-trees)
  4023. (defun org-cycle-hide-archived-subtrees (state)
  4024. "Re-hide all archived subtrees after a visibility state change.
  4025. STATE should be one of the symbols listed in the docstring of
  4026. `org-cycle-hook'."
  4027. (when (and (not org-cycle-open-archived-trees)
  4028. (not (memq state '(overview folded))))
  4029. (save-excursion
  4030. (let* ((globalp (memq state '(contents all)))
  4031. (beg (if globalp (point-min) (point)))
  4032. (end (if globalp (point-max) (org-end-of-subtree t))))
  4033. (org-hide-archived-subtrees beg end)
  4034. (goto-char beg)
  4035. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4036. (message "%s" (substitute-command-keys
  4037. "Subtree is archived and stays closed. Use \
  4038. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4039. (defun org-force-cycle-archived ()
  4040. "Cycle subtree even if it is archived."
  4041. (interactive)
  4042. (setq this-command 'org-cycle)
  4043. (let ((org-cycle-open-archived-trees t))
  4044. (call-interactively 'org-cycle)))
  4045. (defun org-hide-archived-subtrees (beg end)
  4046. "Re-hide all archived subtrees after a visibility state change."
  4047. (org-with-wide-buffer
  4048. (let ((case-fold-search nil)
  4049. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4050. (goto-char beg)
  4051. ;; Include headline point is currently on.
  4052. (beginning-of-line)
  4053. (while (and (< (point) end) (re-search-forward re end t))
  4054. (when (member org-archive-tag (org-get-tags nil t))
  4055. (org-flag-subtree t)
  4056. (org-end-of-subtree t))))))
  4057. (defun org-flag-subtree (flag)
  4058. (save-excursion
  4059. (org-back-to-heading t)
  4060. (org-flag-region (line-end-position)
  4061. (progn (org-end-of-subtree t) (point))
  4062. flag
  4063. 'outline)))
  4064. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4065. ;; Declare Column View Code
  4066. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4067. (declare-function org-columns-compute "org-colview" (property))
  4068. ;; Declare ID code
  4069. (declare-function org-id-store-link "org-id")
  4070. (declare-function org-id-locations-load "org-id")
  4071. (declare-function org-id-locations-save "org-id")
  4072. (defvar org-id-track-globally)
  4073. ;;; Variables for pre-computed regular expressions, all buffer local
  4074. (defvar-local org-todo-regexp nil
  4075. "Matches any of the TODO state keywords.
  4076. Since TODO keywords are case-sensitive, `case-fold-search' is
  4077. expected to be bound to nil when matching against this regexp.")
  4078. (defvar-local org-not-done-regexp nil
  4079. "Matches any of the TODO state keywords except the last one.
  4080. Since TODO keywords are case-sensitive, `case-fold-search' is
  4081. expected to be bound to nil when matching against this regexp.")
  4082. (defvar-local org-not-done-heading-regexp nil
  4083. "Matches a TODO headline that is not done.
  4084. Since TODO keywords are case-sensitive, `case-fold-search' is
  4085. expected to be bound to nil when matching against this regexp.")
  4086. (defvar-local org-todo-line-regexp nil
  4087. "Matches a headline and puts TODO state into group 2 if present.
  4088. Since TODO keywords are case-sensitive, `case-fold-search' is
  4089. expected to be bound to nil when matching against this regexp.")
  4090. (defvar-local org-complex-heading-regexp nil
  4091. "Matches a headline and puts everything into groups:
  4092. group 1: Stars
  4093. group 2: The TODO keyword, maybe
  4094. group 3: Priority cookie
  4095. group 4: True headline
  4096. group 5: Tags
  4097. Since TODO keywords are case-sensitive, `case-fold-search' is
  4098. expected to be bound to nil when matching against this regexp.")
  4099. (defvar-local org-complex-heading-regexp-format nil
  4100. "Printf format to make regexp to match an exact headline.
  4101. This regexp will match the headline of any node which has the
  4102. exact headline text that is put into the format, but may have any
  4103. TODO state, priority and tags.")
  4104. (defvar-local org-todo-line-tags-regexp nil
  4105. "Matches a headline and puts TODO state into group 2 if present.
  4106. Also put tags into group 4 if tags are present.")
  4107. (defconst org-plain-time-of-day-regexp
  4108. (concat
  4109. "\\(\\<[012]?[0-9]"
  4110. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4111. "\\(--?"
  4112. "\\(\\<[012]?[0-9]"
  4113. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4114. "\\)?")
  4115. "Regular expression to match a plain time or time range.
  4116. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4117. groups carry important information:
  4118. 0 the full match
  4119. 1 the first time, range or not
  4120. 8 the second time, if it is a range.")
  4121. (defconst org-plain-time-extension-regexp
  4122. (concat
  4123. "\\(\\<[012]?[0-9]"
  4124. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4125. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4126. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4127. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4128. groups carry important information:
  4129. 0 the full match
  4130. 7 hours of duration
  4131. 9 minutes of duration")
  4132. (defconst org-stamp-time-of-day-regexp
  4133. (concat
  4134. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4135. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4136. "\\(--?"
  4137. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4138. "Regular expression to match a timestamp time or time range.
  4139. After a match, the following groups carry important information:
  4140. 0 the full match
  4141. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4142. 2 the first time, range or not
  4143. 4 the second time, if it is a range.")
  4144. (defconst org-startup-options
  4145. '(("fold" org-startup-folded t)
  4146. ("overview" org-startup-folded t)
  4147. ("nofold" org-startup-folded nil)
  4148. ("showall" org-startup-folded nil)
  4149. ("showeverything" org-startup-folded showeverything)
  4150. ("content" org-startup-folded content)
  4151. ("indent" org-startup-indented t)
  4152. ("noindent" org-startup-indented nil)
  4153. ("hidestars" org-hide-leading-stars t)
  4154. ("showstars" org-hide-leading-stars nil)
  4155. ("odd" org-odd-levels-only t)
  4156. ("oddeven" org-odd-levels-only nil)
  4157. ("align" org-startup-align-all-tables t)
  4158. ("noalign" org-startup-align-all-tables nil)
  4159. ("shrink" org-startup-shrink-all-tables t)
  4160. ("inlineimages" org-startup-with-inline-images t)
  4161. ("noinlineimages" org-startup-with-inline-images nil)
  4162. ("latexpreview" org-startup-with-latex-preview t)
  4163. ("nolatexpreview" org-startup-with-latex-preview nil)
  4164. ("customtime" org-display-custom-times t)
  4165. ("logdone" org-log-done time)
  4166. ("lognotedone" org-log-done note)
  4167. ("nologdone" org-log-done nil)
  4168. ("lognoteclock-out" org-log-note-clock-out t)
  4169. ("nolognoteclock-out" org-log-note-clock-out nil)
  4170. ("logrepeat" org-log-repeat state)
  4171. ("lognoterepeat" org-log-repeat note)
  4172. ("logdrawer" org-log-into-drawer t)
  4173. ("nologdrawer" org-log-into-drawer nil)
  4174. ("logstatesreversed" org-log-states-order-reversed t)
  4175. ("nologstatesreversed" org-log-states-order-reversed nil)
  4176. ("nologrepeat" org-log-repeat nil)
  4177. ("logreschedule" org-log-reschedule time)
  4178. ("lognotereschedule" org-log-reschedule note)
  4179. ("nologreschedule" org-log-reschedule nil)
  4180. ("logredeadline" org-log-redeadline time)
  4181. ("lognoteredeadline" org-log-redeadline note)
  4182. ("nologredeadline" org-log-redeadline nil)
  4183. ("logrefile" org-log-refile time)
  4184. ("lognoterefile" org-log-refile note)
  4185. ("nologrefile" org-log-refile nil)
  4186. ("fninline" org-footnote-define-inline t)
  4187. ("nofninline" org-footnote-define-inline nil)
  4188. ("fnlocal" org-footnote-section nil)
  4189. ("fnauto" org-footnote-auto-label t)
  4190. ("fnprompt" org-footnote-auto-label nil)
  4191. ("fnconfirm" org-footnote-auto-label confirm)
  4192. ("fnplain" org-footnote-auto-label plain)
  4193. ("fnadjust" org-footnote-auto-adjust t)
  4194. ("nofnadjust" org-footnote-auto-adjust nil)
  4195. ("constcgs" constants-unit-system cgs)
  4196. ("constSI" constants-unit-system SI)
  4197. ("noptag" org-tag-persistent-alist nil)
  4198. ("hideblocks" org-hide-block-startup t)
  4199. ("nohideblocks" org-hide-block-startup nil)
  4200. ("beamer" org-startup-with-beamer-mode t)
  4201. ("entitiespretty" org-pretty-entities t)
  4202. ("entitiesplain" org-pretty-entities nil))
  4203. "Variable associated with STARTUP options for Org.
  4204. Each element is a list of three items: the startup options (as written
  4205. in the #+STARTUP line), the corresponding variable, and the value to set
  4206. this variable to if the option is found. An optional forth element PUSH
  4207. means to push this value onto the list in the variable.")
  4208. (defcustom org-group-tags t
  4209. "When non-nil (the default), use group tags.
  4210. This can be turned on/off through `org-toggle-tags-groups'."
  4211. :group 'org-tags
  4212. :group 'org-startup
  4213. :type 'boolean)
  4214. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4215. (defun org-toggle-tags-groups ()
  4216. "Toggle support for group tags.
  4217. Support for group tags is controlled by the option
  4218. `org-group-tags', which is non-nil by default."
  4219. (interactive)
  4220. (setq org-group-tags (not org-group-tags))
  4221. (cond ((and (derived-mode-p 'org-agenda-mode)
  4222. org-group-tags)
  4223. (org-agenda-redo))
  4224. ((derived-mode-p 'org-mode)
  4225. (let ((org-inhibit-startup t)) (org-mode))))
  4226. (message "Groups tags support has been turned %s"
  4227. (if org-group-tags "on" "off")))
  4228. (defun org--tag-add-to-alist (alist1 alist2)
  4229. "Merge tags from ALIST1 into ALIST2.
  4230. Duplicates tags outside a group are removed. Keywords and order
  4231. are preserved.
  4232. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4233. See `org-tag-alist' for their structure."
  4234. (cond
  4235. ((null alist2) alist1)
  4236. ((null alist1) alist2)
  4237. (t
  4238. (let ((to-add nil)
  4239. (group-flag nil))
  4240. (dolist (tag-pair alist1)
  4241. (pcase tag-pair
  4242. (`(,(or :startgrouptag :startgroup))
  4243. (setq group-flag t)
  4244. (push tag-pair to-add))
  4245. (`(,(or :endgrouptag :endgroup))
  4246. (setq group-flag nil)
  4247. (push tag-pair to-add))
  4248. (`(,(or :grouptags :newline))
  4249. (push tag-pair to-add))
  4250. (`(,tag . ,_)
  4251. ;; Remove duplicates from ALIST1, unless they are in
  4252. ;; a group. Indeed, it makes sense to have a tag appear in
  4253. ;; multiple groups.
  4254. (when (or group-flag (not (assoc tag alist2)))
  4255. (push tag-pair to-add)))
  4256. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4257. ;; Preserve order of ALIST1.
  4258. (append (nreverse to-add) alist2)))))
  4259. (defun org-set-regexps-and-options (&optional tags-only)
  4260. "Precompute regular expressions used in the current buffer.
  4261. When optional argument TAGS-ONLY is non-nil, only compute tags
  4262. related expressions."
  4263. (when (derived-mode-p 'org-mode)
  4264. (let ((alist (org--setup-collect-keywords
  4265. (org-make-options-regexp
  4266. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4267. (and (not tags-only)
  4268. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4269. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4270. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4271. ;; Startup options. Get this early since it does change
  4272. ;; behavior for other options (e.g., tags).
  4273. (let ((startup (cdr (assq 'startup alist))))
  4274. (dolist (option startup)
  4275. (let ((entry (assoc-string option org-startup-options t)))
  4276. (when entry
  4277. (let ((var (nth 1 entry))
  4278. (val (nth 2 entry)))
  4279. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4280. (unless (listp (symbol-value var))
  4281. (set (make-local-variable var) nil))
  4282. (add-to-list var val)))))))
  4283. (setq-local org-file-tags
  4284. (mapcar #'org-add-prop-inherited
  4285. (cdr (assq 'filetags alist))))
  4286. (setq org-current-tag-alist
  4287. (org--tag-add-to-alist
  4288. org-tag-persistent-alist
  4289. (let ((tags (cdr (assq 'tags alist))))
  4290. (if tags (org-tag-string-to-alist tags)
  4291. org-tag-alist))))
  4292. (setq org-tag-groups-alist
  4293. (org-tag-alist-to-groups org-current-tag-alist))
  4294. (unless tags-only
  4295. ;; File properties.
  4296. (setq-local org-file-properties (cdr (assq 'property alist)))
  4297. ;; Archive location.
  4298. (let ((archive (cdr (assq 'archive alist))))
  4299. (when archive (setq-local org-archive-location archive)))
  4300. ;; Category.
  4301. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4302. (when cat
  4303. (setq-local org-category (intern cat))
  4304. (setq-local org-file-properties
  4305. (org--update-property-plist
  4306. "CATEGORY" cat org-file-properties))))
  4307. ;; Columns.
  4308. (let ((column (cdr (assq 'columns alist))))
  4309. (when column (setq-local org-columns-default-format column)))
  4310. ;; Constants.
  4311. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4312. ;; Link abbreviations.
  4313. (let ((links (cdr (assq 'link alist))))
  4314. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4315. ;; Priorities.
  4316. (let ((priorities (cdr (assq 'priorities alist))))
  4317. (when priorities
  4318. (setq-local org-highest-priority (nth 0 priorities))
  4319. (setq-local org-lowest-priority (nth 1 priorities))
  4320. (setq-local org-default-priority (nth 2 priorities))))
  4321. ;; Scripts.
  4322. (let ((scripts (assq 'scripts alist)))
  4323. (when scripts
  4324. (setq-local org-use-sub-superscripts (cdr scripts))))
  4325. ;; TODO keywords.
  4326. (setq-local org-todo-kwd-alist nil)
  4327. (setq-local org-todo-key-alist nil)
  4328. (setq-local org-todo-key-trigger nil)
  4329. (setq-local org-todo-keywords-1 nil)
  4330. (setq-local org-done-keywords nil)
  4331. (setq-local org-todo-heads nil)
  4332. (setq-local org-todo-sets nil)
  4333. (setq-local org-todo-log-states nil)
  4334. (let ((todo-sequences
  4335. (or (nreverse (cdr (assq 'todo alist)))
  4336. (let ((d (default-value 'org-todo-keywords)))
  4337. (if (not (stringp (car d))) d
  4338. ;; XXX: Backward compatibility code.
  4339. (list (cons org-todo-interpretation d)))))))
  4340. (dolist (sequence todo-sequences)
  4341. (let* ((sequence (or (run-hook-with-args-until-success
  4342. 'org-todo-setup-filter-hook sequence)
  4343. sequence))
  4344. (sequence-type (car sequence))
  4345. (keywords (cdr sequence))
  4346. (sep (member "|" keywords))
  4347. names alist)
  4348. (dolist (k (remove "|" keywords))
  4349. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4350. k)
  4351. (error "Invalid TODO keyword %s" k))
  4352. (let ((name (match-string 1 k))
  4353. (key (match-string 2 k))
  4354. (log (org-extract-log-state-settings k)))
  4355. (push name names)
  4356. (push (cons name (and key (string-to-char key))) alist)
  4357. (when log (push log org-todo-log-states))))
  4358. (let* ((names (nreverse names))
  4359. (done (if sep (org-remove-keyword-keys (cdr sep))
  4360. (last names)))
  4361. (head (car names))
  4362. (tail (list sequence-type head (car done) (org-last done))))
  4363. (add-to-list 'org-todo-heads head 'append)
  4364. (push names org-todo-sets)
  4365. (setq org-done-keywords (append org-done-keywords done nil))
  4366. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4367. (setq org-todo-key-alist
  4368. (append org-todo-key-alist
  4369. (and alist
  4370. (append '((:startgroup))
  4371. (nreverse alist)
  4372. '((:endgroup))))))
  4373. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4374. (setq org-todo-sets (nreverse org-todo-sets)
  4375. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4376. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4377. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4378. ;; Compute the regular expressions and other local variables.
  4379. ;; Using `org-outline-regexp-bol' would complicate them much,
  4380. ;; because of the fixed white space at the end of that string.
  4381. (unless org-done-keywords
  4382. (setq org-done-keywords
  4383. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4384. (setq org-not-done-keywords
  4385. (org-delete-all org-done-keywords
  4386. (copy-sequence org-todo-keywords-1))
  4387. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4388. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4389. org-not-done-heading-regexp
  4390. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4391. org-todo-line-regexp
  4392. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4393. org-complex-heading-regexp
  4394. (concat "^\\(\\*+\\)"
  4395. "\\(?: +" org-todo-regexp "\\)?"
  4396. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4397. "\\(?: +\\(.*?\\)\\)??"
  4398. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4399. "[ \t]*$")
  4400. org-complex-heading-regexp-format
  4401. (concat "^\\(\\*+\\)"
  4402. "\\(?: +" org-todo-regexp "\\)?"
  4403. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4404. "\\(?: +"
  4405. ;; Stats cookies can be stuck to body.
  4406. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4407. "\\(%s\\)"
  4408. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4409. "\\)"
  4410. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4411. "[ \t]*$")
  4412. org-todo-line-tags-regexp
  4413. (concat "^\\(\\*+\\)"
  4414. "\\(?: +" org-todo-regexp "\\)?"
  4415. "\\(?: +\\(.*?\\)\\)??"
  4416. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4417. "[ \t]*$"))
  4418. (org-compute-latex-and-related-regexp)))))
  4419. (defun org--setup-collect-keywords (regexp &optional files alist)
  4420. "Return setup keywords values as an alist.
  4421. REGEXP matches a subset of setup keywords. FILES is a list of
  4422. file names already visited. It is used to avoid circular setup
  4423. files. ALIST, when non-nil, is the alist computed so far.
  4424. Return value contains the following keys: `archive', `category',
  4425. `columns', `constants', `filetags', `link', `priorities',
  4426. `property', `scripts', `startup', `tags' and `todo'."
  4427. (org-with-wide-buffer
  4428. (goto-char (point-min))
  4429. (let ((case-fold-search t))
  4430. (while (re-search-forward regexp nil t)
  4431. (let ((element (org-element-at-point)))
  4432. (when (eq (org-element-type element) 'keyword)
  4433. (let ((key (org-element-property :key element))
  4434. (value (org-element-property :value element)))
  4435. (cond
  4436. ((equal key "ARCHIVE")
  4437. (when (org-string-nw-p value)
  4438. (push (cons 'archive value) alist)))
  4439. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4440. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4441. ((equal key "CONSTANTS")
  4442. (let* ((constants (assq 'constants alist))
  4443. (store (cdr constants)))
  4444. (dolist (pair (split-string value))
  4445. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4446. pair)
  4447. (let* ((name (match-string 1 pair))
  4448. (value (match-string 2 pair))
  4449. (old (assoc name store)))
  4450. (if old (setcdr old value)
  4451. (push (cons name value) store)))))
  4452. (if constants (setcdr constants store)
  4453. (push (cons 'constants store) alist))))
  4454. ((equal key "FILETAGS")
  4455. (when (org-string-nw-p value)
  4456. (let ((old (assq 'filetags alist))
  4457. (new (apply #'nconc
  4458. (mapcar (lambda (x) (org-split-string x ":"))
  4459. (split-string value)))))
  4460. (if old (setcdr old (append new (cdr old)))
  4461. (push (cons 'filetags new) alist)))))
  4462. ((equal key "LINK")
  4463. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4464. (let ((links (assq 'link alist))
  4465. (pair (cons (match-string-no-properties 1 value)
  4466. (match-string-no-properties 2 value))))
  4467. (if links (push pair (cdr links))
  4468. (push (list 'link pair) alist)))))
  4469. ((equal key "OPTIONS")
  4470. (when (and (org-string-nw-p value)
  4471. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4472. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4473. ((equal key "PRIORITIES")
  4474. (push (cons 'priorities
  4475. (let ((prio (split-string value)))
  4476. (if (< (length prio) 3) '(?A ?C ?B)
  4477. (mapcar #'string-to-char prio))))
  4478. alist))
  4479. ((equal key "PROPERTY")
  4480. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4481. (let* ((property (assq 'property alist))
  4482. (value (org--update-property-plist
  4483. (match-string-no-properties 1 value)
  4484. (match-string-no-properties 2 value)
  4485. (cdr property))))
  4486. (if property (setcdr property value)
  4487. (push (cons 'property value) alist)))))
  4488. ((equal key "STARTUP")
  4489. (let ((startup (assq 'startup alist)))
  4490. (if startup
  4491. (setcdr startup
  4492. (append (cdr startup) (split-string value)))
  4493. (push (cons 'startup (split-string value)) alist))))
  4494. ((equal key "TAGS")
  4495. (let ((tag-cell (assq 'tags alist)))
  4496. (if tag-cell
  4497. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4498. (push (cons 'tags value) alist))))
  4499. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4500. (let ((todo (assq 'todo alist))
  4501. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4502. (split-string value))))
  4503. (if todo (push value (cdr todo))
  4504. (push (list 'todo value) alist))))
  4505. ((equal key "SETUPFILE")
  4506. (unless buffer-read-only ; Do not check in Gnus messages.
  4507. (let ((f (and (org-string-nw-p value)
  4508. (expand-file-name (org-strip-quotes value)))))
  4509. (when (and f (file-readable-p f) (not (member f files)))
  4510. (with-temp-buffer
  4511. (setq default-directory (file-name-directory f))
  4512. (insert-file-contents f)
  4513. (setq alist
  4514. ;; Fake Org mode to benefit from cache
  4515. ;; without recurring needlessly.
  4516. (let ((major-mode 'org-mode))
  4517. (org--setup-collect-keywords
  4518. regexp (cons f files) alist)))))))))))))))
  4519. alist)
  4520. (defun org-tag-string-to-alist (s)
  4521. "Return tag alist associated to string S.
  4522. S is a value for TAGS keyword or produced with
  4523. `org-tag-alist-to-string'. Return value is an alist suitable for
  4524. `org-tag-alist' or `org-tag-persistent-alist'."
  4525. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4526. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4527. "\\(?:(\\(.\\))\\)?\\'"))
  4528. alist group-flag)
  4529. (dolist (tokens lines (cdr (nreverse alist)))
  4530. (push '(:newline) alist)
  4531. (while tokens
  4532. (let ((token (pop tokens)))
  4533. (pcase token
  4534. ("{"
  4535. (push '(:startgroup) alist)
  4536. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4537. ("}"
  4538. (push '(:endgroup) alist)
  4539. (setq group-flag nil))
  4540. ("["
  4541. (push '(:startgrouptag) alist)
  4542. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4543. ("]"
  4544. (push '(:endgrouptag) alist)
  4545. (setq group-flag nil))
  4546. (":"
  4547. (push '(:grouptags) alist))
  4548. ((guard (string-match tag-re token))
  4549. (let ((tag (match-string 1 token))
  4550. (key (and (match-beginning 2)
  4551. (string-to-char (match-string 2 token)))))
  4552. ;; Push all tags in groups, no matter if they already
  4553. ;; appear somewhere else in the list.
  4554. (when (or group-flag (not (assoc tag alist)))
  4555. (push (cons tag key) alist))))))))))
  4556. (defun org-tag-alist-to-string (alist &optional skip-key)
  4557. "Return tag string associated to ALIST.
  4558. ALIST is an alist, as defined in `org-tag-alist' or
  4559. `org-tag-persistent-alist', or produced with
  4560. `org-tag-string-to-alist'.
  4561. Return value is a string suitable as a value for \"TAGS\"
  4562. keyword.
  4563. When optional argument SKIP-KEY is non-nil, skip selection keys
  4564. next to tags."
  4565. (mapconcat (lambda (token)
  4566. (pcase token
  4567. (`(:startgroup) "{")
  4568. (`(:endgroup) "}")
  4569. (`(:startgrouptag) "[")
  4570. (`(:endgrouptag) "]")
  4571. (`(:grouptags) ":")
  4572. (`(:newline) "\\n")
  4573. ((and
  4574. (guard (not skip-key))
  4575. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4576. (format "%s(%c)" tag key))
  4577. (`(,(and tag (pred stringp)) . ,_) tag)
  4578. (_ (user-error "Invalid tag token: %S" token))))
  4579. alist
  4580. " "))
  4581. (defun org-tag-alist-to-groups (alist)
  4582. "Return group alist from tag ALIST.
  4583. ALIST is an alist, as defined in `org-tag-alist' or
  4584. `org-tag-persistent-alist', or produced with
  4585. `org-tag-string-to-alist'. Return value is an alist following
  4586. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4587. a string, summarizing TAGS, as a list of strings."
  4588. (let (groups group-status current-group)
  4589. (dolist (token alist (nreverse groups))
  4590. (pcase token
  4591. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4592. (`(,(or :endgroup :endgrouptag))
  4593. (when (eq group-status 'append)
  4594. (push (nreverse current-group) groups))
  4595. (setq group-status nil current-group nil))
  4596. (`(:grouptags) (setq group-status 'append))
  4597. ((and `(,tag . ,_) (guard group-status))
  4598. (if (eq group-status 'append) (push tag current-group)
  4599. (setq current-group (list tag))))
  4600. (_ nil)))))
  4601. (defvar org--file-cache (make-hash-table :test #'equal)
  4602. "Hash table to store contents of files referenced via a URL.
  4603. This is the cache of file URLs read using `org-file-contents'.")
  4604. (defun org-reset-file-cache ()
  4605. "Reset the cache of files downloaded by `org-file-contents'."
  4606. (clrhash org--file-cache))
  4607. (defun org-file-url-p (file)
  4608. "Non-nil if FILE is a URL."
  4609. (require 'ffap)
  4610. (string-match-p ffap-url-regexp file))
  4611. (defun org-file-contents (file &optional noerror nocache)
  4612. "Return the contents of FILE, as a string.
  4613. FILE can be a file name or URL.
  4614. If FILE is a URL, download the contents. If the URL contents are
  4615. already cached in the `org--file-cache' hash table, the download step
  4616. is skipped.
  4617. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4618. from file or URL.
  4619. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4620. is available. This option applies only if FILE is a URL."
  4621. (let* ((is-url (org-file-url-p file))
  4622. (cache (and is-url
  4623. (not nocache)
  4624. (gethash file org--file-cache))))
  4625. (cond
  4626. (cache)
  4627. (is-url
  4628. (with-current-buffer (url-retrieve-synchronously file)
  4629. (goto-char (point-min))
  4630. ;; Move point to after the url-retrieve header.
  4631. (search-forward "\n\n" nil :move)
  4632. ;; Search for the success code only in the url-retrieve header.
  4633. (if (save-excursion
  4634. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4635. ;; Update the cache `org--file-cache' and return contents.
  4636. (puthash file
  4637. (buffer-substring-no-properties (point) (point-max))
  4638. org--file-cache)
  4639. (funcall (if noerror #'message #'user-error)
  4640. "Unable to fetch file from %S"
  4641. file))))
  4642. (t
  4643. (with-temp-buffer
  4644. (condition-case nil
  4645. (progn
  4646. (insert-file-contents file)
  4647. (buffer-string))
  4648. (file-error
  4649. (funcall (if noerror #'message #'user-error)
  4650. "Unable to read file %S"
  4651. file))))))))
  4652. (defun org-extract-log-state-settings (x)
  4653. "Extract the log state setting from a TODO keyword string.
  4654. This will extract info from a string like \"WAIT(w@/!)\"."
  4655. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4656. (let ((kw (match-string 1 x))
  4657. (log1 (and (match-end 3) (match-string 3 x)))
  4658. (log2 (and (match-end 4) (match-string 4 x))))
  4659. (and (or log1 log2)
  4660. (list kw
  4661. (and log1 (if (equal log1 "!") 'time 'note))
  4662. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4663. (defun org-remove-keyword-keys (list)
  4664. "Remove a pair of parenthesis at the end of each string in LIST."
  4665. (mapcar (lambda (x)
  4666. (if (string-match "(.*)$" x)
  4667. (substring x 0 (match-beginning 0))
  4668. x))
  4669. list))
  4670. (defun org-assign-fast-keys (alist)
  4671. "Assign fast keys to a keyword-key alist.
  4672. Respect keys that are already there."
  4673. (let (new e (alt ?0))
  4674. (while (setq e (pop alist))
  4675. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4676. (cdr e)) ;; Key already assigned.
  4677. (push e new)
  4678. (let ((clist (string-to-list (downcase (car e))))
  4679. (used (append new alist)))
  4680. (when (= (car clist) ?@)
  4681. (pop clist))
  4682. (while (and clist (rassoc (car clist) used))
  4683. (pop clist))
  4684. (unless clist
  4685. (while (rassoc alt used)
  4686. (cl-incf alt)))
  4687. (push (cons (car e) (or (car clist) alt)) new))))
  4688. (nreverse new)))
  4689. ;;; Some variables used in various places
  4690. (defvar org-window-configuration nil
  4691. "Used in various places to store a window configuration.")
  4692. (defvar org-selected-window nil
  4693. "Used in various places to store a window configuration.")
  4694. (defvar org-finish-function nil
  4695. "Function to be called when `C-c C-c' is used.
  4696. This is for getting out of special buffers like capture.")
  4697. (defvar org-last-state)
  4698. ;; Defined somewhere in this file, but used before definition.
  4699. (defvar org-entities) ;; defined in org-entities.el
  4700. (defvar org-struct-menu)
  4701. (defvar org-org-menu)
  4702. (defvar org-tbl-menu)
  4703. ;;;; Define the Org mode
  4704. ;; We use a before-change function to check if a table might need
  4705. ;; an update.
  4706. (defvar org-table-may-need-update t
  4707. "Indicates that a table might need an update.
  4708. This variable is set by `org-before-change-function'.
  4709. `org-table-align' sets it back to nil.")
  4710. (defun org-before-change-function (_beg _end)
  4711. "Every change indicates that a table might need an update."
  4712. (setq org-table-may-need-update t))
  4713. (defvar org-mode-map)
  4714. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4715. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4716. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4717. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4718. (defvar org-table-buffer-is-an nil)
  4719. (defvar bidi-paragraph-direction)
  4720. (defvar buffer-face-mode-face)
  4721. (require 'outline)
  4722. ;; Other stuff we need.
  4723. (require 'time-date)
  4724. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4725. (require 'easymenu)
  4726. (autoload 'easy-menu-add "easymenu")
  4727. (require 'overlay)
  4728. ;; (require 'org-macs) moved higher up in the file before it is first used
  4729. (require 'org-entities)
  4730. ;; (require 'org-compat) moved higher up in the file before it is first used
  4731. (require 'org-faces)
  4732. (require 'org-list)
  4733. (require 'org-pcomplete)
  4734. (require 'org-src)
  4735. (require 'org-footnote)
  4736. (require 'org-macro)
  4737. ;; babel
  4738. (require 'ob)
  4739. ;;;###autoload
  4740. (define-derived-mode org-mode outline-mode "Org"
  4741. "Outline-based notes management and organizer, alias
  4742. \"Carsten's outline-mode for keeping track of everything.\"
  4743. Org mode develops organizational tasks around a NOTES file which
  4744. contains information about projects as plain text. Org mode is
  4745. implemented on top of Outline mode, which is ideal to keep the content
  4746. of large files well structured. It supports ToDo items, deadlines and
  4747. time stamps, which magically appear in the diary listing of the Emacs
  4748. calendar. Tables are easily created with a built-in table editor.
  4749. Plain text URL-like links connect to websites, emails (VM), Usenet
  4750. messages (Gnus), BBDB entries, and any files related to the project.
  4751. For printing and sharing of notes, an Org file (or a part of it)
  4752. can be exported as a structured ASCII or HTML file.
  4753. The following commands are available:
  4754. \\{org-mode-map}"
  4755. ;; Get rid of Outline menus, they are not needed
  4756. ;; Need to do this here because define-derived-mode sets up
  4757. ;; the keymap so late. Still, it is a waste to call this each time
  4758. ;; we switch another buffer into Org mode.
  4759. (define-key org-mode-map [menu-bar headings] 'undefined)
  4760. (define-key org-mode-map [menu-bar hide] 'undefined)
  4761. (define-key org-mode-map [menu-bar show] 'undefined)
  4762. (org-load-modules-maybe)
  4763. (org-install-agenda-files-menu)
  4764. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4765. (add-to-invisibility-spec '(org-hide-block . t))
  4766. (add-to-invisibility-spec '(org-hide-drawer . t))
  4767. (setq-local outline-regexp org-outline-regexp)
  4768. (setq-local outline-level 'org-outline-level)
  4769. (setq bidi-paragraph-direction 'left-to-right)
  4770. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4771. (unless org-display-table
  4772. (setq org-display-table (make-display-table)))
  4773. (set-display-table-slot
  4774. org-display-table 4
  4775. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4776. org-ellipsis)))
  4777. (setq buffer-display-table org-display-table))
  4778. (org-set-regexps-and-options)
  4779. (org-set-font-lock-defaults)
  4780. (when (and org-tag-faces (not org-tags-special-faces-re))
  4781. ;; tag faces set outside customize.... force initialization.
  4782. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4783. ;; Calc embedded
  4784. (setq-local calc-embedded-open-mode "# ")
  4785. ;; Modify a few syntax entries
  4786. (modify-syntax-entry ?\" "\"")
  4787. (modify-syntax-entry ?\\ "_")
  4788. (modify-syntax-entry ?~ "_")
  4789. (modify-syntax-entry ?< "(>")
  4790. (modify-syntax-entry ?> ")<")
  4791. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4792. ;; Activate before-change-function
  4793. (setq-local org-table-may-need-update t)
  4794. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4795. ;; Check for running clock before killing a buffer
  4796. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4797. ;; Initialize macros templates.
  4798. (org-macro-initialize-templates)
  4799. ;; Initialize radio targets.
  4800. (org-update-radio-target-regexp)
  4801. ;; Indentation.
  4802. (setq-local indent-line-function 'org-indent-line)
  4803. (setq-local indent-region-function 'org-indent-region)
  4804. ;; Filling and auto-filling.
  4805. (org-setup-filling)
  4806. ;; Comments.
  4807. (org-setup-comments-handling)
  4808. ;; Initialize cache.
  4809. (org-element-cache-reset)
  4810. ;; Beginning/end of defun
  4811. (setq-local beginning-of-defun-function 'org-backward-element)
  4812. (setq-local end-of-defun-function
  4813. (lambda ()
  4814. (if (not (org-at-heading-p))
  4815. (org-forward-element)
  4816. (org-forward-element)
  4817. (forward-char -1))))
  4818. ;; Next error for sparse trees
  4819. (setq-local next-error-function 'org-occur-next-match)
  4820. ;; Make commit log messages from Org documents easier.
  4821. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4822. ;; Make sure dependence stuff works reliably, even for users who set it
  4823. ;; too late :-(
  4824. (if org-enforce-todo-dependencies
  4825. (add-hook 'org-blocker-hook
  4826. 'org-block-todo-from-children-or-siblings-or-parent)
  4827. (remove-hook 'org-blocker-hook
  4828. 'org-block-todo-from-children-or-siblings-or-parent))
  4829. (if org-enforce-todo-checkbox-dependencies
  4830. (add-hook 'org-blocker-hook
  4831. 'org-block-todo-from-checkboxes)
  4832. (remove-hook 'org-blocker-hook
  4833. 'org-block-todo-from-checkboxes))
  4834. ;; Align options lines
  4835. (setq-local
  4836. align-mode-rules-list
  4837. '((org-in-buffer-settings
  4838. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4839. (modes . '(org-mode)))))
  4840. ;; Make isearch reveal context
  4841. (setq-local outline-isearch-open-invisible-function
  4842. (lambda (&rest _) (org-show-context 'isearch)))
  4843. ;; Setup the pcomplete hooks
  4844. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4845. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4846. (setq-local pcomplete-default-completion-function 'ignore)
  4847. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4848. (setq-local pcomplete-termination-string "")
  4849. (setq-local buffer-face-mode-face 'org-default)
  4850. ;; If empty file that did not turn on Org mode automatically, make
  4851. ;; it to.
  4852. (when (and org-insert-mode-line-in-empty-file
  4853. (called-interactively-p 'any)
  4854. (= (point-min) (point-max)))
  4855. (insert "# -*- mode: org -*-\n\n"))
  4856. (unless org-inhibit-startup
  4857. (org-unmodified
  4858. (when org-startup-with-beamer-mode (org-beamer-mode))
  4859. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4860. (org-table-map-tables
  4861. (cond ((and org-startup-align-all-tables
  4862. org-startup-shrink-all-tables)
  4863. (lambda () (org-table-align) (org-table-shrink)))
  4864. (org-startup-align-all-tables #'org-table-align)
  4865. (t #'org-table-shrink))
  4866. t))
  4867. (when org-startup-with-inline-images (org-display-inline-images))
  4868. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4869. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4870. (when org-startup-truncated (setq truncate-lines t))
  4871. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4872. (org-refresh-effort-properties)))
  4873. ;; Try to set `org-hide' face correctly.
  4874. (let ((foreground (org-find-invisible-foreground)))
  4875. (when foreground
  4876. (set-face-foreground 'org-hide foreground))))
  4877. ;; Update `customize-package-emacs-version-alist'
  4878. (add-to-list 'customize-package-emacs-version-alist
  4879. '(Org ("8.0" . "24.4")
  4880. ("8.1" . "24.4")
  4881. ("8.2" . "24.4")
  4882. ("8.2.7" . "24.4")
  4883. ("8.3" . "26.1")
  4884. ("9.0" . "26.1")
  4885. ("9.1" . "26.1")
  4886. ("9.2" . "27.1")))
  4887. (defvar org-mode-transpose-word-syntax-table
  4888. (let ((st (make-syntax-table text-mode-syntax-table)))
  4889. (dolist (c org-emphasis-alist st)
  4890. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4891. (when (fboundp 'abbrev-table-put)
  4892. (abbrev-table-put org-mode-abbrev-table
  4893. :parents (list text-mode-abbrev-table)))
  4894. (defun org-find-invisible-foreground ()
  4895. (let ((candidates (remove
  4896. "unspecified-bg"
  4897. (nconc
  4898. (list (face-background 'default)
  4899. (face-background 'org-default))
  4900. (mapcar
  4901. (lambda (alist)
  4902. (when (boundp alist)
  4903. (cdr (assq 'background-color (symbol-value alist)))))
  4904. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4905. (list (face-foreground 'org-hide))))))
  4906. (car (remove nil candidates))))
  4907. (defun org-current-time (&optional rounding-minutes past)
  4908. "Current time, possibly rounded to ROUNDING-MINUTES.
  4909. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4910. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4911. the rounding returns a past time."
  4912. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4913. (car org-time-stamp-rounding-minutes)))
  4914. (time (decode-time)) res)
  4915. (if (< r 1)
  4916. (current-time)
  4917. (setq res
  4918. (apply 'encode-time
  4919. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4920. (nthcdr 2 time))))
  4921. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4922. (seconds-to-time (- (float-time res) (* r 60)))
  4923. res))))
  4924. (defun org-today ()
  4925. "Return today date, considering `org-extend-today-until'."
  4926. (time-to-days
  4927. (time-subtract (current-time)
  4928. (list 0 (* 3600 org-extend-today-until) 0))))
  4929. ;;;; Font-Lock stuff, including the activators
  4930. (defvar org-mouse-map (make-sparse-keymap))
  4931. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4932. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4933. (when org-mouse-1-follows-link
  4934. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4935. (when org-tab-follows-link
  4936. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4937. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4938. (require 'font-lock)
  4939. (defconst org-non-link-chars "]\t\n\r<>")
  4940. (defvar org-link-types-re nil
  4941. "Matches a link that has a url-like prefix like \"http:\"")
  4942. (defvar org-link-re-with-space nil
  4943. "Matches a link with spaces, optional angular brackets around it.")
  4944. (defvar org-link-re-with-space2 nil
  4945. "Matches a link with spaces, optional angular brackets around it.")
  4946. (defvar org-link-re-with-space3 nil
  4947. "Matches a link with spaces, only for internal part in bracket links.")
  4948. (defvar org-angle-link-re nil
  4949. "Matches link with angular brackets, spaces are allowed.")
  4950. (defvar org-plain-link-re nil
  4951. "Matches plain link, without spaces.")
  4952. (defvar org-bracket-link-regexp nil
  4953. "Matches a link in double brackets.")
  4954. (defvar org-bracket-link-analytic-regexp nil
  4955. "Regular expression used to analyze links.
  4956. Here is what the match groups contain after a match:
  4957. 1: http:
  4958. 2: http
  4959. 3: path
  4960. 4: [desc]
  4961. 5: desc")
  4962. (defvar org-bracket-link-analytic-regexp++ nil
  4963. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4964. (defvar org-any-link-re nil
  4965. "Regular expression matching any link.")
  4966. (defconst org-match-sexp-depth 3
  4967. "Number of stacked braces for sub/superscript matching.")
  4968. (defun org-create-multibrace-regexp (left right n)
  4969. "Create a regular expression which will match a balanced sexp.
  4970. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4971. as single character strings.
  4972. The regexp returned will match the entire expression including the
  4973. delimiters. It will also define a single group which contains the
  4974. match except for the outermost delimiters. The maximum depth of
  4975. stacked delimiters is N. Escaping delimiters is not possible."
  4976. (let* ((nothing (concat "[^" left right "]*?"))
  4977. (or "\\|")
  4978. (re nothing)
  4979. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4980. (while (> n 1)
  4981. (setq n (1- n)
  4982. re (concat re or next)
  4983. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4984. (concat left "\\(" re "\\)" right)))
  4985. (defconst org-match-substring-regexp
  4986. (concat
  4987. "\\(\\S-\\)\\([_^]\\)\\("
  4988. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4989. "\\|"
  4990. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4991. "\\|"
  4992. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4993. "The regular expression matching a sub- or superscript.")
  4994. (defconst org-match-substring-with-braces-regexp
  4995. (concat
  4996. "\\(\\S-\\)\\([_^]\\)"
  4997. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4998. "The regular expression matching a sub- or superscript, forcing braces.")
  4999. (defun org-make-link-regexps ()
  5000. "Update the link regular expressions.
  5001. This should be called after the variable `org-link-parameters' has changed."
  5002. (let ((types-re (regexp-opt (org-link-types) t)))
  5003. (setq org-link-types-re
  5004. (concat "\\`" types-re ":")
  5005. org-link-re-with-space
  5006. (concat "<?" types-re ":"
  5007. "\\([^" org-non-link-chars " ]"
  5008. "[^" org-non-link-chars "]*"
  5009. "[^" org-non-link-chars " ]\\)>?")
  5010. org-link-re-with-space2
  5011. (concat "<?" types-re ":"
  5012. "\\([^" org-non-link-chars " ]"
  5013. "[^\t\n\r]*"
  5014. "[^" org-non-link-chars " ]\\)>?")
  5015. org-link-re-with-space3
  5016. (concat "<?" types-re ":"
  5017. "\\([^" org-non-link-chars " ]"
  5018. "[^\t\n\r]*\\)")
  5019. org-angle-link-re
  5020. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5021. types-re)
  5022. org-plain-link-re
  5023. (concat
  5024. "\\<" types-re ":"
  5025. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5026. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5027. org-bracket-link-regexp
  5028. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5029. org-bracket-link-analytic-regexp
  5030. (concat
  5031. "\\[\\["
  5032. "\\(" types-re ":\\)?"
  5033. "\\([^]]+\\)"
  5034. "\\]"
  5035. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5036. "\\]")
  5037. org-bracket-link-analytic-regexp++
  5038. (concat
  5039. "\\[\\["
  5040. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5041. "\\([^]]+\\)"
  5042. "\\]"
  5043. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5044. "\\]")
  5045. org-any-link-re
  5046. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5047. org-angle-link-re "\\)\\|\\("
  5048. org-plain-link-re "\\)"))))
  5049. (org-make-link-regexps)
  5050. (defvar org-emph-face nil)
  5051. (defun org-do-emphasis-faces (limit)
  5052. "Run through the buffer and emphasize strings."
  5053. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5054. (car org-emphasis-regexp-components))))
  5055. (catch :exit
  5056. (while (re-search-forward quick-re limit t)
  5057. (let* ((marker (match-string 2))
  5058. (verbatim? (member marker '("~" "="))))
  5059. (when (save-excursion
  5060. (goto-char (match-beginning 0))
  5061. (and
  5062. ;; Do not match table hlines.
  5063. (not (and (equal marker "+")
  5064. (org-match-line
  5065. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5066. ;; Do not match headline stars. Do not consider
  5067. ;; stars of a headline as closing marker for bold
  5068. ;; markup either.
  5069. (not (and (equal marker "*")
  5070. (save-excursion
  5071. (forward-char)
  5072. (skip-chars-backward "*")
  5073. (looking-at-p org-outline-regexp-bol))))
  5074. ;; Match full emphasis markup regexp.
  5075. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5076. ;; Do not span over paragraph boundaries.
  5077. (not (string-match-p org-element-paragraph-separate
  5078. (match-string 2)))
  5079. ;; Do not span over cells in table rows.
  5080. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5081. (string-match-p "|" (match-string 4))))))
  5082. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5083. (font-lock-prepend-text-property
  5084. (match-beginning 2) (match-end 2) 'face face)
  5085. (when verbatim?
  5086. (org-remove-flyspell-overlays-in
  5087. (match-beginning 0) (match-end 0))
  5088. (remove-text-properties (match-beginning 2) (match-end 2)
  5089. '(display t invisible t intangible t)))
  5090. (add-text-properties (match-beginning 2) (match-end 2)
  5091. '(font-lock-multiline t org-emphasis t))
  5092. (when org-hide-emphasis-markers
  5093. (add-text-properties (match-end 4) (match-beginning 5)
  5094. '(invisible org-link))
  5095. (add-text-properties (match-beginning 3) (match-end 3)
  5096. '(invisible org-link)))
  5097. (throw :exit t))))))))
  5098. (defun org-emphasize (&optional char)
  5099. "Insert or change an emphasis, i.e. a font like bold or italic.
  5100. If there is an active region, change that region to a new emphasis.
  5101. If there is no region, just insert the marker characters and position
  5102. the cursor between them.
  5103. CHAR should be the marker character. If it is a space, it means to
  5104. remove the emphasis of the selected region.
  5105. If CHAR is not given (for example in an interactive call) it will be
  5106. prompted for."
  5107. (interactive)
  5108. (let ((erc org-emphasis-regexp-components)
  5109. (string "") beg end move s)
  5110. (if (org-region-active-p)
  5111. (setq beg (region-beginning)
  5112. end (region-end)
  5113. string (buffer-substring beg end))
  5114. (setq move t))
  5115. (unless char
  5116. (message "Emphasis marker or tag: [%s]"
  5117. (mapconcat #'car org-emphasis-alist ""))
  5118. (setq char (read-char-exclusive)))
  5119. (if (equal char ?\s)
  5120. (setq s ""
  5121. move nil)
  5122. (unless (assoc (char-to-string char) org-emphasis-alist)
  5123. (user-error "No such emphasis marker: \"%c\"" char))
  5124. (setq s (char-to-string char)))
  5125. (while (and (> (length string) 1)
  5126. (equal (substring string 0 1) (substring string -1))
  5127. (assoc (substring string 0 1) org-emphasis-alist))
  5128. (setq string (substring string 1 -1)))
  5129. (setq string (concat s string s))
  5130. (when beg (delete-region beg end))
  5131. (unless (or (bolp)
  5132. (string-match (concat "[" (nth 0 erc) "\n]")
  5133. (char-to-string (char-before (point)))))
  5134. (insert " "))
  5135. (unless (or (eobp)
  5136. (string-match (concat "[" (nth 1 erc) "\n]")
  5137. (char-to-string (char-after (point)))))
  5138. (insert " ") (backward-char 1))
  5139. (insert string)
  5140. (and move (backward-char 1))))
  5141. (defconst org-nonsticky-props
  5142. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5143. (defsubst org-rear-nonsticky-at (pos)
  5144. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5145. (defun org-activate-links (limit)
  5146. "Add link properties to links.
  5147. This includes angle, plain, and bracket links."
  5148. (catch :exit
  5149. (while (re-search-forward org-any-link-re limit t)
  5150. (let* ((start (match-beginning 0))
  5151. (end (match-end 0))
  5152. (style (cond ((eq ?< (char-after start)) 'angle)
  5153. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5154. (t 'plain))))
  5155. (when (and (memq style org-highlight-links)
  5156. ;; Do not confuse plain links with tags.
  5157. (not (and (eq style 'plain)
  5158. (let ((face (get-text-property
  5159. (max (1- start) (point-min)) 'face)))
  5160. (if (consp face) (memq 'org-tag face)
  5161. (eq 'org-tag face))))))
  5162. (let* ((link-object (save-excursion
  5163. (goto-char start)
  5164. (save-match-data (org-element-link-parser))))
  5165. (link (org-element-property :raw-link link-object))
  5166. (type (org-element-property :type link-object))
  5167. (path (org-element-property :path link-object))
  5168. (properties ;for link's visible part
  5169. (list
  5170. 'face (pcase (org-link-get-parameter type :face)
  5171. ((and (pred functionp) face) (funcall face path))
  5172. ((and (pred facep) face) face)
  5173. ((and (pred consp) face) face) ;anonymous
  5174. (_ 'org-link))
  5175. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5176. 'highlight)
  5177. 'keymap (or (org-link-get-parameter type :keymap)
  5178. org-mouse-map)
  5179. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5180. ((and (pred stringp) echo) echo)
  5181. ((and (pred functionp) echo) echo)
  5182. (_ (concat "LINK: " link)))
  5183. 'htmlize-link (pcase (org-link-get-parameter type
  5184. :htmlize-link)
  5185. ((and (pred functionp) f) (funcall f))
  5186. (_ `(:uri ,link)))
  5187. 'font-lock-multiline t)))
  5188. (org-remove-flyspell-overlays-in start end)
  5189. (org-rear-nonsticky-at end)
  5190. (if (not (eq 'bracket style))
  5191. (add-text-properties start end properties)
  5192. ;; Handle invisible parts in bracket links.
  5193. (remove-text-properties start end '(invisible nil))
  5194. (let ((hidden
  5195. (append `(invisible
  5196. ,(or (org-link-get-parameter type :display)
  5197. 'org-link))
  5198. properties))
  5199. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5200. (visible-end (or (match-end 4) (match-end 2))))
  5201. (add-text-properties start visible-start hidden)
  5202. (add-text-properties visible-start visible-end properties)
  5203. (add-text-properties visible-end end hidden)
  5204. (org-rear-nonsticky-at visible-start)
  5205. (org-rear-nonsticky-at visible-end)))
  5206. (let ((f (org-link-get-parameter type :activate-func)))
  5207. (when (functionp f)
  5208. (funcall f start end path (eq style 'bracket))))
  5209. (throw :exit t))))) ;signal success
  5210. nil))
  5211. (defun org-activate-code (limit)
  5212. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5213. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5214. (remove-text-properties (match-beginning 0) (match-end 0)
  5215. '(display t invisible t intangible t))
  5216. t))
  5217. (defcustom org-src-fontify-natively t
  5218. "When non-nil, fontify code in code blocks.
  5219. See also the `org-block' face."
  5220. :type 'boolean
  5221. :version "26.1"
  5222. :package-version '(Org . "8.3")
  5223. :group 'org-appearance
  5224. :group 'org-babel)
  5225. (defcustom org-allow-promoting-top-level-subtree nil
  5226. "When non-nil, allow promoting a top level subtree.
  5227. The leading star of the top level headline will be replaced
  5228. by a #."
  5229. :type 'boolean
  5230. :version "24.1"
  5231. :group 'org-appearance)
  5232. (defun org-fontify-meta-lines-and-blocks (limit)
  5233. (condition-case nil
  5234. (org-fontify-meta-lines-and-blocks-1 limit)
  5235. (error (message "Org mode fontification error in %S at %d"
  5236. (current-buffer)
  5237. (line-number-at-pos)))))
  5238. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5239. "Fontify #+ lines and blocks."
  5240. (let ((case-fold-search t))
  5241. (when (re-search-forward
  5242. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5243. limit t)
  5244. (let ((beg (match-beginning 0))
  5245. (block-start (match-end 0))
  5246. (block-end nil)
  5247. (lang (match-string 7))
  5248. (beg1 (line-beginning-position 2))
  5249. (dc1 (downcase (match-string 2)))
  5250. (dc3 (downcase (match-string 3)))
  5251. end end1 quoting block-type)
  5252. (cond
  5253. ((and (match-end 4) (equal dc3 "+begin"))
  5254. ;; Truly a block
  5255. (setq block-type (downcase (match-string 5))
  5256. quoting (member block-type org-protecting-blocks))
  5257. (when (re-search-forward
  5258. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5259. nil t) ;; on purpose, we look further than LIMIT
  5260. (setq end (min (point-max) (match-end 0))
  5261. end1 (min (point-max) (1- (match-beginning 0))))
  5262. (setq block-end (match-beginning 0))
  5263. (when quoting
  5264. (org-remove-flyspell-overlays-in beg1 end1)
  5265. (remove-text-properties beg end
  5266. '(display t invisible t intangible t)))
  5267. (add-text-properties
  5268. beg end '(font-lock-fontified t font-lock-multiline t))
  5269. (add-text-properties beg beg1 '(face org-meta-line))
  5270. (org-remove-flyspell-overlays-in beg beg1)
  5271. (add-text-properties ; For end_src
  5272. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5273. (org-remove-flyspell-overlays-in end1 end)
  5274. (cond
  5275. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5276. (org-src-font-lock-fontify-block lang block-start block-end)
  5277. (add-text-properties beg1 block-end '(src-block t)))
  5278. (quoting
  5279. (add-text-properties beg1 (min (point-max) (1+ end1))
  5280. (list 'face
  5281. (list :inherit
  5282. (let ((face-name
  5283. (intern (format "org-block-%s" lang))))
  5284. (append (and (facep face-name) (list face-name))
  5285. '(org-block))))))) ; end of source block
  5286. ((not org-fontify-quote-and-verse-blocks))
  5287. ((string= block-type "quote")
  5288. (add-face-text-property
  5289. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5290. ((string= block-type "verse")
  5291. (add-face-text-property
  5292. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5293. (add-text-properties beg beg1 '(face org-block-begin-line))
  5294. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5295. '(face org-block-end-line))
  5296. t))
  5297. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5298. (org-remove-flyspell-overlays-in
  5299. (match-beginning 0)
  5300. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5301. (add-text-properties
  5302. beg (match-end 3)
  5303. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5304. '(font-lock-fontified t invisible t)
  5305. '(font-lock-fontified t face org-document-info-keyword)))
  5306. (add-text-properties
  5307. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5308. (if (string-equal dc1 "+title:")
  5309. '(font-lock-fontified t face org-document-title)
  5310. '(font-lock-fontified t face org-document-info))))
  5311. ((string-prefix-p "+caption" dc1)
  5312. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5313. (remove-text-properties (match-beginning 0) (match-end 0)
  5314. '(display t invisible t intangible t))
  5315. ;; Handle short captions.
  5316. (save-excursion
  5317. (beginning-of-line)
  5318. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5319. (add-text-properties (line-beginning-position) (match-end 1)
  5320. '(font-lock-fontified t face org-meta-line))
  5321. (add-text-properties (match-end 0) (line-end-position)
  5322. '(font-lock-fontified t face org-block))
  5323. t)
  5324. ((member dc3 '(" " ""))
  5325. (org-remove-flyspell-overlays-in beg (match-end 0))
  5326. (add-text-properties
  5327. beg (match-end 0)
  5328. '(font-lock-fontified t face font-lock-comment-face)))
  5329. (t ;; just any other in-buffer setting, but not indented
  5330. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5331. (remove-text-properties (match-beginning 0) (match-end 0)
  5332. '(display t invisible t intangible t))
  5333. (add-text-properties beg (match-end 0)
  5334. '(font-lock-fontified t face org-meta-line))
  5335. t))))))
  5336. (defun org-fontify-drawers (limit)
  5337. "Fontify drawers."
  5338. (when (re-search-forward org-drawer-regexp limit t)
  5339. (add-text-properties
  5340. (match-beginning 0) (match-end 0)
  5341. '(font-lock-fontified t face org-special-keyword))
  5342. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5343. t))
  5344. (defun org-fontify-macros (limit)
  5345. "Fontify macros."
  5346. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5347. (let ((begin (match-beginning 0))
  5348. (opening-end (match-beginning 1)))
  5349. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5350. (match-string 1))
  5351. (let ((end (match-end 1))
  5352. (closing-start (match-beginning 1)))
  5353. (add-text-properties
  5354. begin end
  5355. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5356. (org-remove-flyspell-overlays-in begin end)
  5357. (when org-hide-macro-markers
  5358. (add-text-properties begin opening-end '(invisible t))
  5359. (add-text-properties closing-start end '(invisible t)))
  5360. t)))))
  5361. (defun org-activate-footnote-links (limit)
  5362. "Add text properties for footnotes."
  5363. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5364. (when fn
  5365. (let* ((beg (nth 1 fn))
  5366. (end (nth 2 fn))
  5367. (label (car fn))
  5368. (referencep (/= (line-beginning-position) beg)))
  5369. (when (and referencep (nth 3 fn))
  5370. (save-excursion
  5371. (goto-char beg)
  5372. (search-forward (or label "fn:"))
  5373. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5374. (add-text-properties beg end
  5375. (list 'mouse-face 'highlight
  5376. 'keymap org-mouse-map
  5377. 'help-echo
  5378. (if referencep "Footnote reference"
  5379. "Footnote definition")
  5380. 'font-lock-fontified t
  5381. 'font-lock-multiline t
  5382. 'face 'org-footnote))))))
  5383. (defun org-activate-dates (limit)
  5384. "Add text properties for dates."
  5385. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5386. (not (equal (char-before (match-beginning 0)) 91)))
  5387. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5388. (add-text-properties (match-beginning 0) (match-end 0)
  5389. (list 'mouse-face 'highlight
  5390. 'keymap org-mouse-map))
  5391. (org-rear-nonsticky-at (match-end 0))
  5392. (when org-display-custom-times
  5393. ;; If it's a date range, activate custom time for second date.
  5394. (when (match-end 3)
  5395. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5396. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5397. t))
  5398. (defvar-local org-target-link-regexp nil
  5399. "Regular expression matching radio targets in plain text.")
  5400. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5401. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5402. border border border))
  5403. "Regular expression matching a link target.")
  5404. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5405. "Regular expression matching a radio target.")
  5406. (defconst org-any-target-regexp
  5407. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5408. "Regular expression matching any target.")
  5409. (defun org-activate-target-links (limit)
  5410. "Add text properties for target matches."
  5411. (when org-target-link-regexp
  5412. (let ((case-fold-search t))
  5413. ;; `org-target-link-regexp' matches one character before the
  5414. ;; actual target.
  5415. (unless (bolp) (forward-char -1))
  5416. (when (re-search-forward org-target-link-regexp limit t)
  5417. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5418. (add-text-properties (match-beginning 1) (match-end 1)
  5419. (list 'mouse-face 'highlight
  5420. 'keymap org-mouse-map
  5421. 'help-echo "Radio target link"
  5422. 'org-linked-text t))
  5423. (org-rear-nonsticky-at (match-end 1))
  5424. t))))
  5425. (defun org-update-radio-target-regexp ()
  5426. "Find all radio targets in this file and update the regular expression.
  5427. Also refresh fontification if needed."
  5428. (interactive)
  5429. (let ((old-regexp org-target-link-regexp)
  5430. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5431. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5432. (targets
  5433. (org-with-wide-buffer
  5434. (goto-char (point-min))
  5435. (let (rtn)
  5436. (while (re-search-forward org-radio-target-regexp nil t)
  5437. ;; Make sure point is really within the object.
  5438. (backward-char)
  5439. (let ((obj (org-element-context)))
  5440. (when (eq (org-element-type obj) 'radio-target)
  5441. (cl-pushnew (org-element-property :value obj) rtn
  5442. :test #'equal))))
  5443. rtn))))
  5444. (setq org-target-link-regexp
  5445. (and targets
  5446. (concat before-re
  5447. (mapconcat
  5448. (lambda (x)
  5449. (replace-regexp-in-string
  5450. " +" "\\s-+" (regexp-quote x) t t))
  5451. targets
  5452. "\\|")
  5453. after-re)))
  5454. (unless (equal old-regexp org-target-link-regexp)
  5455. ;; Clean-up cache.
  5456. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5457. ((not org-target-link-regexp) old-regexp)
  5458. (t
  5459. (concat before-re
  5460. (mapconcat
  5461. (lambda (re)
  5462. (substring re (length before-re)
  5463. (- (length after-re))))
  5464. (list old-regexp org-target-link-regexp)
  5465. "\\|")
  5466. after-re)))))
  5467. (org-with-wide-buffer
  5468. (goto-char (point-min))
  5469. (while (re-search-forward regexp nil t)
  5470. (org-element-cache-refresh (match-beginning 1)))))
  5471. ;; Re fontify buffer.
  5472. (when (memq 'radio org-highlight-links)
  5473. (org-restart-font-lock)))))
  5474. (defvar org-latex-and-related-regexp nil
  5475. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5476. (defun org-compute-latex-and-related-regexp ()
  5477. "Compute regular expression for LaTeX, entities and sub/superscript.
  5478. Result depends on variable `org-highlight-latex-and-related'."
  5479. (let ((re-sub
  5480. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5481. ((eq org-use-sub-superscripts '{})
  5482. (list org-match-substring-with-braces-regexp))
  5483. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5484. (re-latex
  5485. (when (memq 'latex org-highlight-latex-and-related)
  5486. (let* ((matchers (plist-get org-format-latex-options :matchers))
  5487. (regexps (and (member "begin" matchers)
  5488. '("\\\\end{[a-zA-Z0-9\\*]+}[ \t]*$"))))
  5489. (dolist (matcher matchers)
  5490. (pcase (assoc matcher org-latex-regexps)
  5491. (`("begin" . ,_) (push "^[ \t]*\\\\begin{[a-zA-Z0-9\\*]+}"
  5492. regexps))
  5493. (`(,_ ,regexp . ,_) (push regexp regexps))
  5494. (_ nil)))
  5495. (nreverse regexps))))
  5496. (re-entities
  5497. (when (memq 'entities org-highlight-latex-and-related)
  5498. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  5499. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  5500. (setq-local org-latex-and-related-regexp
  5501. (mapconcat #'identity
  5502. (append re-latex re-entities re-sub)
  5503. "\\|"))))
  5504. (defun org-do-latex-and-related (limit)
  5505. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5506. LIMIT bounds the search for syntax to highlight. Stop at first
  5507. highlighted object, if any. Return t if some highlighting was
  5508. done, nil otherwise."
  5509. (when (org-string-nw-p org-latex-and-related-regexp)
  5510. (catch 'found
  5511. (while (re-search-forward org-latex-and-related-regexp limit t)
  5512. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  5513. org-special-keyword)))
  5514. (save-excursion
  5515. (goto-char (1+ (match-beginning 0)))
  5516. (face-at-point nil t)))
  5517. (let* ((start (if (memq (char-after (1+ (match-beginning 0)))
  5518. '(?_ ?^))
  5519. (1+ (match-beginning 0))
  5520. (match-beginning 0)))
  5521. (end
  5522. (let* ((b (match-beginning 0))
  5523. (e (match-end 0))
  5524. (m (buffer-substring-no-properties b e)))
  5525. (cond
  5526. ((string-match "\\`[ \t]*\\\\begin{\\([a-zA-Z0-9\\*]+\\)}"
  5527. m)
  5528. (let ((re (format "\\\\end{%s}[ \t]*$"
  5529. (regexp-quote (match-string 1 m)))))
  5530. (or (re-search-forward re nil t) e)))
  5531. ((string-match "\\\\end{\\([a-zA-Z0-9\\*]+\\)}[ \t]*\\'" m)
  5532. (let ((re (format "^[ \t]*\\\\begin{%s}"
  5533. (regexp-quote (match-string 1 m)))))
  5534. (setq start
  5535. (or (save-excursion (re-search-backward re nil t))
  5536. b))
  5537. (line-end-position)))
  5538. ((string-match "\\`\\\\[a-zA-Z]+\\*?{\\'" m)
  5539. (search-forward "}" nil t))
  5540. (t e)))))
  5541. (font-lock-prepend-text-property
  5542. start end 'face 'org-latex-and-related)
  5543. (add-text-properties start end '(font-lock-multiline t)))
  5544. (throw 'found t)))
  5545. nil)))
  5546. (defun org-restart-font-lock ()
  5547. "Restart `font-lock-mode', to force refontification."
  5548. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5549. (font-lock-mode -1)
  5550. (font-lock-mode 1)))
  5551. (defun org-activate-tags (limit)
  5552. (when (re-search-forward org-tag-line-re limit t)
  5553. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5554. (add-text-properties (match-beginning 1) (match-end 1)
  5555. (list 'mouse-face 'highlight
  5556. 'keymap org-mouse-map))
  5557. (org-rear-nonsticky-at (match-end 1))
  5558. t))
  5559. (defun org-outline-level ()
  5560. "Compute the outline level of the heading at point.
  5561. If this is called at a normal headline, the level is the number
  5562. of stars. Use `org-reduced-level' to remove the effect of
  5563. `org-odd-levels'. Unlike to `org-current-level', this function
  5564. takes into consideration inlinetasks."
  5565. (org-with-wide-buffer
  5566. (end-of-line)
  5567. (if (re-search-backward org-outline-regexp-bol nil t)
  5568. (1- (- (match-end 0) (match-beginning 0)))
  5569. 0)))
  5570. (defvar org-font-lock-keywords nil)
  5571. (defsubst org-re-property (property &optional literal allow-null value)
  5572. "Return a regexp matching a PROPERTY line.
  5573. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5574. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5575. non-nil, match properties even without a value.
  5576. Match group 3 is set to the value when it exists. If there is no
  5577. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5578. With optional argument VALUE, match only property lines with
  5579. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5580. unless LITERAL is non-nil."
  5581. (concat
  5582. "^\\(?4:[ \t]*\\)"
  5583. (format "\\(?1::\\(?2:%s\\):\\)"
  5584. (if literal property (regexp-quote property)))
  5585. (cond (value
  5586. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5587. (if literal value (regexp-quote value))))
  5588. (allow-null
  5589. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5590. (t
  5591. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5592. (defconst org-property-re
  5593. (org-re-property "\\S-+" 'literal t)
  5594. "Regular expression matching a property line.
  5595. There are four matching groups:
  5596. 1: :PROPKEY: including the leading and trailing colon,
  5597. 2: PROPKEY without the leading and trailing colon,
  5598. 3: PROPVAL without leading or trailing spaces,
  5599. 4: the indentation of the current line,
  5600. 5: trailing whitespace.")
  5601. (defvar org-font-lock-hook nil
  5602. "Functions to be called for special font lock stuff.")
  5603. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5604. (defvar org-font-lock-set-keywords-hook nil
  5605. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5606. This is called after `org-font-lock-extra-keywords' is defined, but before
  5607. it is installed to be used by font lock. This can be useful if something
  5608. needs to be inserted at a specific position in the font-lock sequence.")
  5609. (defun org-font-lock-hook (limit)
  5610. "Run `org-font-lock-hook' within LIMIT."
  5611. (run-hook-with-args 'org-font-lock-hook limit))
  5612. (defun org-set-font-lock-defaults ()
  5613. "Set font lock defaults for the current buffer."
  5614. (let* ((em org-fontify-emphasized-text)
  5615. (lk org-highlight-links)
  5616. (org-font-lock-extra-keywords
  5617. (list
  5618. ;; Call the hook
  5619. '(org-font-lock-hook)
  5620. ;; Headlines
  5621. `(,(if org-fontify-whole-heading-line
  5622. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5623. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5624. (1 (org-get-level-face 1))
  5625. (2 (org-get-level-face 2))
  5626. (3 (org-get-level-face 3)))
  5627. ;; Table lines
  5628. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5629. (1 'org-table t))
  5630. ;; Table internals
  5631. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5632. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5633. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5634. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5635. ;; Drawers
  5636. '(org-fontify-drawers)
  5637. ;; Properties
  5638. (list org-property-re
  5639. '(1 'org-special-keyword t)
  5640. '(3 'org-property-value t))
  5641. ;; Link related fontification.
  5642. '(org-activate-links)
  5643. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5644. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5645. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5646. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5647. ;; Targets.
  5648. (list org-any-target-regexp '(0 'org-target t))
  5649. ;; Diary sexps.
  5650. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5651. ;; Macro
  5652. '(org-fontify-macros)
  5653. ;; TODO keyword
  5654. (list (format org-heading-keyword-regexp-format
  5655. org-todo-regexp)
  5656. '(2 (org-get-todo-face 2) t))
  5657. ;; DONE
  5658. (if org-fontify-done-headline
  5659. (list (format org-heading-keyword-regexp-format
  5660. (concat
  5661. "\\(?:"
  5662. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5663. "\\)"))
  5664. '(2 'org-headline-done t))
  5665. nil)
  5666. ;; Priorities
  5667. '(org-font-lock-add-priority-faces)
  5668. ;; Tags
  5669. '(org-font-lock-add-tag-faces)
  5670. ;; Tags groups
  5671. (when (and org-group-tags org-tag-groups-alist)
  5672. (list (concat org-outline-regexp-bol ".+\\(:"
  5673. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5674. ":\\).*$")
  5675. '(1 'org-tag-group prepend)))
  5676. ;; Special keywords
  5677. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5678. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5679. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5680. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5681. ;; Emphasis
  5682. (when em '(org-do-emphasis-faces))
  5683. ;; Checkboxes
  5684. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5685. 1 'org-checkbox prepend)
  5686. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5687. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5688. (0 (org-get-checkbox-statistics-face) t)))
  5689. ;; Description list items
  5690. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5691. 1 'org-list-dt prepend)
  5692. ;; ARCHIVEd headings
  5693. (list (concat
  5694. org-outline-regexp-bol
  5695. "\\(.*:" org-archive-tag ":.*\\)")
  5696. '(1 'org-archived prepend))
  5697. ;; Specials
  5698. '(org-do-latex-and-related)
  5699. '(org-fontify-entities)
  5700. '(org-raise-scripts)
  5701. ;; Code
  5702. '(org-activate-code (1 'org-code t))
  5703. ;; COMMENT
  5704. (list (format
  5705. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5706. org-todo-regexp
  5707. org-comment-string)
  5708. '(9 'org-special-keyword t))
  5709. ;; Blocks and meta lines
  5710. '(org-fontify-meta-lines-and-blocks))))
  5711. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5712. (run-hooks 'org-font-lock-set-keywords-hook)
  5713. ;; Now set the full font-lock-keywords
  5714. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5715. (setq-local font-lock-defaults
  5716. '(org-font-lock-keywords t nil nil backward-paragraph))
  5717. (kill-local-variable 'font-lock-keywords)
  5718. nil))
  5719. (defun org-toggle-pretty-entities ()
  5720. "Toggle the composition display of entities as UTF8 characters."
  5721. (interactive)
  5722. (setq-local org-pretty-entities (not org-pretty-entities))
  5723. (org-restart-font-lock)
  5724. (if org-pretty-entities
  5725. (message "Entities are now displayed as UTF8 characters")
  5726. (save-restriction
  5727. (widen)
  5728. (decompose-region (point-min) (point-max))
  5729. (message "Entities are now displayed as plain text"))))
  5730. (defvar-local org-custom-properties-overlays nil
  5731. "List of overlays used for custom properties.")
  5732. (defun org-toggle-custom-properties-visibility ()
  5733. "Display or hide properties in `org-custom-properties'."
  5734. (interactive)
  5735. (if org-custom-properties-overlays
  5736. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5737. (setq org-custom-properties-overlays nil))
  5738. (when org-custom-properties
  5739. (org-with-wide-buffer
  5740. (goto-char (point-min))
  5741. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5742. (while (re-search-forward regexp nil t)
  5743. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5744. (when (and end (< (point) end))
  5745. ;; Hide first custom property in current drawer.
  5746. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5747. (overlay-put o 'invisible t)
  5748. (overlay-put o 'org-custom-property t)
  5749. (push o org-custom-properties-overlays))
  5750. ;; Hide additional custom properties in the same drawer.
  5751. (while (re-search-forward regexp end t)
  5752. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5753. (overlay-put o 'invisible t)
  5754. (overlay-put o 'org-custom-property t)
  5755. (push o org-custom-properties-overlays)))))
  5756. ;; Each entry is limited to a single property drawer.
  5757. (outline-next-heading)))))))
  5758. (defun org-fontify-entities (limit)
  5759. "Find an entity to fontify."
  5760. (let (ee)
  5761. (when org-pretty-entities
  5762. (catch 'match
  5763. ;; "\_ "-family is left out on purpose. Only the first one,
  5764. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5765. ;; confusing when adding a second white space character.
  5766. (while (re-search-forward
  5767. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5768. limit t)
  5769. (when (and (not (org-at-comment-p))
  5770. (setq ee (org-entity-get (match-string 1)))
  5771. (= (length (nth 6 ee)) 1))
  5772. (let* ((end (if (equal (match-string 2) "{}")
  5773. (match-end 2)
  5774. (match-end 1))))
  5775. (add-text-properties
  5776. (match-beginning 0) end
  5777. (list 'font-lock-fontified t))
  5778. (compose-region (match-beginning 0) end
  5779. (nth 6 ee) nil)
  5780. (backward-char 1)
  5781. (throw 'match t))))
  5782. nil))))
  5783. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5784. "Fontify string S like in Org mode."
  5785. (with-temp-buffer
  5786. (insert s)
  5787. (let ((org-odd-levels-only odd-levels))
  5788. (org-mode)
  5789. (org-font-lock-ensure)
  5790. (buffer-string))))
  5791. (defvar org-m nil)
  5792. (defvar org-l nil)
  5793. (defvar org-f nil)
  5794. (defun org-get-level-face (n)
  5795. "Get the right face for match N in font-lock matching of headlines."
  5796. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5797. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5798. (if org-cycle-level-faces
  5799. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5800. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5801. (cond
  5802. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5803. ((eq n 2) org-f)
  5804. (t (unless org-level-color-stars-only org-f))))
  5805. (defun org-face-from-face-or-color (context inherit face-or-color)
  5806. "Create a face list that inherits INHERIT, but sets the foreground color.
  5807. When FACE-OR-COLOR is not a string, just return it."
  5808. (if (stringp face-or-color)
  5809. (list :inherit inherit
  5810. (cdr (assoc context org-faces-easy-properties))
  5811. face-or-color)
  5812. face-or-color))
  5813. (defun org-get-todo-face (kwd)
  5814. "Get the right face for a TODO keyword KWD.
  5815. If KWD is a number, get the corresponding match group."
  5816. (when (numberp kwd) (setq kwd (match-string kwd)))
  5817. (or (org-face-from-face-or-color
  5818. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5819. (and (member kwd org-done-keywords) 'org-done)
  5820. 'org-todo))
  5821. (defun org-get-priority-face (priority)
  5822. "Get the right face for PRIORITY.
  5823. PRIORITY is a character."
  5824. (or (org-face-from-face-or-color
  5825. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5826. 'org-priority))
  5827. (defun org-get-tag-face (tag)
  5828. "Get the right face for TAG.
  5829. If TAG is a number, get the corresponding match group."
  5830. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5831. (or (org-face-from-face-or-color
  5832. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5833. 'org-tag)))
  5834. (defun org-font-lock-add-priority-faces (limit)
  5835. "Add the special priority faces."
  5836. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5837. (add-text-properties
  5838. (match-beginning 1) (match-end 1)
  5839. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5840. 'font-lock-fontified t))))
  5841. (defun org-font-lock-add-tag-faces (limit)
  5842. "Add the special tag faces."
  5843. (when (and org-tag-faces org-tags-special-faces-re)
  5844. (while (re-search-forward org-tags-special-faces-re limit t)
  5845. (add-text-properties (match-beginning 1) (match-end 1)
  5846. (list 'face (org-get-tag-face 1)
  5847. 'font-lock-fontified t))
  5848. (backward-char 1))))
  5849. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5850. "Remove fontification and activation overlays from links."
  5851. (font-lock-default-unfontify-region beg end)
  5852. (let* ((buffer-undo-list t)
  5853. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5854. (inhibit-modification-hooks t)
  5855. deactivate-mark buffer-file-name buffer-file-truename)
  5856. (decompose-region beg end)
  5857. (remove-text-properties beg end
  5858. '(mouse-face t keymap t org-linked-text t
  5859. invisible t intangible t
  5860. org-emphasis t))
  5861. (org-remove-font-lock-display-properties beg end)))
  5862. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5863. ((raise 0.3) (height 0.7))
  5864. ((raise -0.5))
  5865. ((raise 0.5)))
  5866. "Display properties for showing superscripts and subscripts.")
  5867. (defun org-remove-font-lock-display-properties (beg end)
  5868. "Remove specific display properties that have been added by font lock.
  5869. The will remove the raise properties that are used to show superscripts
  5870. and subscripts."
  5871. (let (next prop)
  5872. (while (< beg end)
  5873. (setq next (next-single-property-change beg 'display nil end)
  5874. prop (get-text-property beg 'display))
  5875. (when (member prop org-script-display)
  5876. (put-text-property beg next 'display nil))
  5877. (setq beg next))))
  5878. (defun org-raise-scripts (limit)
  5879. "Add raise properties to sub/superscripts."
  5880. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5881. (re-search-forward
  5882. (if (eq org-use-sub-superscripts t)
  5883. org-match-substring-regexp
  5884. org-match-substring-with-braces-regexp)
  5885. limit t))
  5886. (let* ((pos (point)) table-p comment-p
  5887. (mpos (match-beginning 3))
  5888. (emph-p (get-text-property mpos 'org-emphasis))
  5889. (link-p (get-text-property mpos 'mouse-face))
  5890. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5891. (goto-char (point-at-bol))
  5892. (setq table-p (looking-at-p org-table-dataline-regexp)
  5893. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5894. (goto-char pos)
  5895. ;; Handle a_b^c
  5896. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5897. (unless (or comment-p emph-p link-p keyw-p)
  5898. (put-text-property (match-beginning 3) (match-end 0)
  5899. 'display
  5900. (if (equal (char-after (match-beginning 2)) ?^)
  5901. (nth (if table-p 3 1) org-script-display)
  5902. (nth (if table-p 2 0) org-script-display)))
  5903. (add-text-properties (match-beginning 2) (match-end 2)
  5904. (list 'invisible t))
  5905. (when (and (eq (char-after (match-beginning 3)) ?{)
  5906. (eq (char-before (match-end 3)) ?}))
  5907. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5908. (list 'invisible t))
  5909. (add-text-properties (1- (match-end 3)) (match-end 3)
  5910. (list 'invisible t))))
  5911. t)))
  5912. (defun org-remove-empty-overlays-at (pos)
  5913. "Remove outline overlays that do not contain non-white stuff."
  5914. (dolist (o (overlays-at pos))
  5915. (and (eq 'outline (overlay-get o 'invisible))
  5916. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5917. (overlay-end o))))
  5918. (delete-overlay o))))
  5919. (defun org-show-empty-lines-in-parent ()
  5920. "Move to the parent and re-show empty lines before visible headlines."
  5921. (save-excursion
  5922. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5923. (org-cycle-show-empty-lines context))))
  5924. (defun org-files-list ()
  5925. "Return `org-agenda-files' list, plus all open Org files.
  5926. This is useful for operations that need to scan all of a user's
  5927. open and agenda-wise Org files."
  5928. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5929. (dolist (buf (buffer-list))
  5930. (with-current-buffer buf
  5931. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5932. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5933. :test #'equal))))
  5934. files))
  5935. (defsubst org-entry-beginning-position ()
  5936. "Return the beginning position of the current entry."
  5937. (save-excursion (org-back-to-heading t) (point)))
  5938. (defsubst org-entry-end-position ()
  5939. "Return the end position of the current entry."
  5940. (save-excursion (outline-next-heading) (point)))
  5941. (defun org-subtree-end-visible-p ()
  5942. "Is the end of the current subtree visible?"
  5943. (pos-visible-in-window-p
  5944. (save-excursion (org-end-of-subtree t) (point))))
  5945. (defun org-first-headline-recenter ()
  5946. "Move cursor to the first headline and recenter the headline."
  5947. (let ((window (get-buffer-window)))
  5948. (when window
  5949. (goto-char (point-min))
  5950. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5951. (set-window-start window (line-beginning-position))))))
  5952. ;;; Visibility (headlines, blocks, drawers)
  5953. ;;;; Headlines visibility
  5954. (defun org-show-entry ()
  5955. "Show the body directly following this heading.
  5956. Show the heading too, if it is currently invisible."
  5957. (interactive)
  5958. (save-excursion
  5959. (ignore-errors
  5960. (org-back-to-heading t)
  5961. (org-flag-region
  5962. (line-end-position 0)
  5963. (save-excursion
  5964. (if (re-search-forward
  5965. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5966. (match-beginning 1)
  5967. (point-max)))
  5968. nil
  5969. 'outline))))
  5970. (defun org-show-children (&optional level)
  5971. "Show all direct subheadings of this heading.
  5972. Prefix arg LEVEL is how many levels below the current level
  5973. should be shown. Default is enough to cause the following
  5974. heading to appear."
  5975. (interactive "p")
  5976. (save-excursion
  5977. (org-back-to-heading t)
  5978. (let* ((current-level (funcall outline-level))
  5979. (max-level (org-get-valid-level
  5980. current-level
  5981. (if level (prefix-numeric-value level) 1)))
  5982. (end (save-excursion (org-end-of-subtree t t)))
  5983. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5984. (past-first-child nil)
  5985. ;; Make sure to skip inlinetasks.
  5986. (re (format regexp-fmt
  5987. current-level
  5988. (cond
  5989. ((not (featurep 'org-inlinetask)) "")
  5990. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5991. 3))
  5992. (t (1- org-inlinetask-min-level))))))
  5993. ;; Display parent heading.
  5994. (org-flag-heading nil)
  5995. (forward-line)
  5996. ;; Display children. First child may be deeper than expected
  5997. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5998. ;; MAX-LEVEL accordingly.
  5999. (while (re-search-forward re end t)
  6000. (unless past-first-child
  6001. (setq re (format regexp-fmt
  6002. current-level
  6003. (max (funcall outline-level) max-level)))
  6004. (setq past-first-child t))
  6005. (org-flag-heading nil)))))
  6006. (defun org-show-subtree ()
  6007. "Show everything after this heading at deeper levels."
  6008. (interactive)
  6009. (org-flag-region
  6010. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  6011. ;;;; Blocks visibility
  6012. (defun org-hide-block-toggle-maybe ()
  6013. "Toggle visibility of block at point.
  6014. Unlike to `org-hide-block-toggle', this function does not throw
  6015. an error. Return a non-nil value when toggling is successful."
  6016. (interactive)
  6017. (ignore-errors (org-hide-block-toggle)))
  6018. (defun org-hide-block-toggle (&optional force)
  6019. "Toggle the visibility of the current block.
  6020. When optional argument FORCE is `off', make block visible. If it
  6021. is non-nil, hide it unconditionally. Throw an error when not at
  6022. a block. Return a non-nil value when toggling is successful."
  6023. (interactive)
  6024. (let ((element (org-element-at-point)))
  6025. (unless (memq (org-element-type element)
  6026. '(center-block comment-block dynamic-block example-block
  6027. export-block quote-block special-block
  6028. src-block verse-block))
  6029. (user-error "Not at a block"))
  6030. (let* ((post (org-element-property :post-affiliated element))
  6031. (start (save-excursion
  6032. (goto-char post)
  6033. (line-end-position)))
  6034. (end (save-excursion
  6035. (goto-char (org-element-property :end element))
  6036. (skip-chars-backward " \t\n")
  6037. (line-end-position))))
  6038. ;; Do nothing when not before or at the block opening line or at
  6039. ;; the block closing line.
  6040. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  6041. (cond ((eq force 'off)
  6042. (org-flag-region start end nil 'org-hide-block))
  6043. (force
  6044. (org-flag-region start end t 'org-hide-block))
  6045. ((eq (get-char-property start 'invisible) 'org-hide-block)
  6046. (org-flag-region start end nil 'org-hide-block))
  6047. (t
  6048. (org-flag-region start end t 'org-hide-block)))
  6049. ;; When the block is hidden away, make sure point is left in
  6050. ;; a visible part of the buffer.
  6051. (when (invisible-p (max (1- (point)) (point-min)))
  6052. (goto-char post))
  6053. ;; Signal success.
  6054. t))))
  6055. (defun org-hide-block-toggle-all ()
  6056. "Toggle the visibility of all blocks in the current buffer."
  6057. (org-block-map 'org-hide-block-toggle))
  6058. (defun org-hide-block-all ()
  6059. "Fold all blocks in the current buffer."
  6060. (interactive)
  6061. (org-show-all '(blocks))
  6062. (org-block-map 'org-hide-block-toggle-maybe))
  6063. ;;;; Drawers visibility
  6064. (defun org-cycle-hide-drawers (state &optional exceptions)
  6065. "Re-hide all drawers after a visibility state change.
  6066. STATE should be one of the symbols listed in the docstring of
  6067. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6068. a list of strings specifying which drawers should not be hidden."
  6069. (when (and (derived-mode-p 'org-mode)
  6070. (not (memq state '(overview folded contents))))
  6071. (save-excursion
  6072. (let* ((globalp (eq state 'all))
  6073. (beg (if globalp (point-min) (point)))
  6074. (end (if globalp (point-max)
  6075. (if (eq state 'children)
  6076. (save-excursion (outline-next-heading) (point))
  6077. (org-end-of-subtree t)))))
  6078. (goto-char beg)
  6079. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6080. (unless (member-ignore-case (match-string 1) exceptions)
  6081. (let ((drawer (org-element-at-point)))
  6082. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6083. (org-flag-drawer t drawer)
  6084. ;; Make sure to skip drawer entirely or we might flag
  6085. ;; it another time when matching its ending line with
  6086. ;; `org-drawer-regexp'.
  6087. (goto-char (org-element-property :end drawer))))))))))
  6088. (defun org-flag-drawer (flag &optional element)
  6089. "When FLAG is non-nil, hide the drawer we are at.
  6090. Otherwise make it visible. When optional argument ELEMENT is
  6091. a parsed drawer, as returned by `org-element-at-point', hide or
  6092. show that drawer instead."
  6093. (let ((drawer (or element
  6094. (and (save-excursion
  6095. (beginning-of-line)
  6096. (looking-at-p org-drawer-regexp))
  6097. (org-element-at-point)))))
  6098. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6099. (let ((post (org-element-property :post-affiliated drawer)))
  6100. (org-flag-region
  6101. (save-excursion (goto-char post) (line-end-position))
  6102. (save-excursion (goto-char (org-element-property :end drawer))
  6103. (skip-chars-backward " \t\n")
  6104. (line-end-position))
  6105. flag 'org-hide-drawer)
  6106. ;; When the drawer is hidden away, make sure point lies in
  6107. ;; a visible part of the buffer.
  6108. (when (invisible-p (max (1- (point)) (point-min)))
  6109. (goto-char post))))))
  6110. ;;;; Visibility cycling
  6111. (defvar-local org-cycle-global-status nil)
  6112. (put 'org-cycle-global-status 'org-state t)
  6113. (defvar-local org-cycle-subtree-status nil)
  6114. (put 'org-cycle-subtree-status 'org-state t)
  6115. (defun org-show-all (&optional types)
  6116. "Show all contents in the visible part of the buffer.
  6117. By default, the function expands headings, blocks and drawers.
  6118. When optional argument TYPE is a list of symbols among `blocks',
  6119. `drawers' and `headings', to only expand one specific type."
  6120. (dolist (type (or types '(blocks drawers headings)))
  6121. (org-flag-region (point-min) (point-max) nil
  6122. (pcase type
  6123. (`blocks 'org-hide-block)
  6124. (`drawers 'org-hide-drawer)
  6125. (`headings 'outline)
  6126. (_ (error "Invalid type: %S" type))))))
  6127. ;;;###autoload
  6128. (defun org-cycle (&optional arg)
  6129. "TAB-action and visibility cycling for Org mode.
  6130. This is the command invoked in Org mode by the `TAB' key. Its main
  6131. purpose is outline visibility cycling, but it also invokes other actions
  6132. in special contexts.
  6133. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6134. the entire
  6135. buffer through 3 states (global cycling)
  6136. 1. OVERVIEW: Show only top-level headlines.
  6137. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6138. 3. SHOW ALL: Show everything.
  6139. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6140. switch to the startup visibility,
  6141. determined by the variable `org-startup-folded', and by any VISIBILITY
  6142. properties in the buffer.
  6143. With a `\\[universal-argument] \\[universal-argument] \
  6144. \\[universal-argument]' prefix argument, show the entire buffer, including
  6145. any drawers.
  6146. When inside a table, re-align the table and move to the next field.
  6147. When point is at the beginning of a headline, rotate the subtree started
  6148. by this line through 3 different states (local cycling)
  6149. 1. FOLDED: Only the main headline is shown.
  6150. 2. CHILDREN: The main headline and the direct children are shown.
  6151. From this state, you can move to one of the children
  6152. and zoom in further.
  6153. 3. SUBTREE: Show the entire subtree, including body text.
  6154. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6155. When point is at the beginning of an empty headline and the variable
  6156. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6157. of the headline by demoting and promoting it to likely levels. This
  6158. speeds up creation document structure by pressing `TAB' once or several
  6159. times right after creating a new headline.
  6160. When there is a numeric prefix, go up to a heading with level ARG, do
  6161. a `show-subtree' and return to the previous cursor position. If ARG
  6162. is negative, go up that many levels.
  6163. When point is not at the beginning of a headline, execute the global
  6164. binding for `TAB', which is re-indenting the line. See the option
  6165. `org-cycle-emulate-tab' for details.
  6166. As a special case, if point is at the beginning of the buffer and there is
  6167. no headline in line 1, this function will act as if called with prefix arg
  6168. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6169. prefix arg, but only
  6170. if the variable `org-cycle-global-at-bob' is t."
  6171. (interactive "P")
  6172. (org-load-modules-maybe)
  6173. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6174. (and org-cycle-level-after-item/entry-creation
  6175. (or (org-cycle-level)
  6176. (org-cycle-item-indentation))))
  6177. (let* ((limit-level
  6178. (or org-cycle-max-level
  6179. (and (boundp 'org-inlinetask-min-level)
  6180. org-inlinetask-min-level
  6181. (1- org-inlinetask-min-level))))
  6182. (nstars (and limit-level
  6183. (if org-odd-levels-only
  6184. (and limit-level (1- (* limit-level 2)))
  6185. limit-level)))
  6186. (org-outline-regexp
  6187. (if (not (derived-mode-p 'org-mode))
  6188. outline-regexp
  6189. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6190. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6191. (not (looking-at org-outline-regexp))))
  6192. (org-cycle-hook
  6193. (if bob-special
  6194. (delq 'org-optimize-window-after-visibility-change
  6195. (copy-sequence org-cycle-hook))
  6196. org-cycle-hook))
  6197. (pos (point)))
  6198. (cond
  6199. ((equal arg '(16))
  6200. (setq last-command 'dummy)
  6201. (org-set-startup-visibility)
  6202. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6203. ((equal arg '(64))
  6204. (org-show-all)
  6205. (org-unlogged-message "Entire buffer visible, including drawers"))
  6206. ((equal arg '(4)) (org-cycle-internal-global))
  6207. ;; Try hiding block at point.
  6208. ((org-hide-block-toggle-maybe))
  6209. ;; Try cdlatex TAB completion
  6210. ((org-try-cdlatex-tab))
  6211. ;; Table: enter it or move to the next field.
  6212. ((org-at-table-p 'any)
  6213. (if (org-at-table.el-p)
  6214. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6215. Use `\\[org-edit-special]' to edit table.el tables"))
  6216. (if arg (org-table-edit-field t)
  6217. (org-table-justify-field-maybe)
  6218. (call-interactively 'org-table-next-field))))
  6219. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6220. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6221. (bob-special (org-cycle-internal-global))
  6222. ;; Drawers: delegate to `org-flag-drawer'.
  6223. ((save-excursion
  6224. (beginning-of-line 1)
  6225. (looking-at org-drawer-regexp))
  6226. (org-flag-drawer ; toggle block visibility
  6227. (not (get-char-property (match-end 0) 'invisible))))
  6228. ;; Show-subtree, ARG levels up from here.
  6229. ((integerp arg)
  6230. (save-excursion
  6231. (org-back-to-heading)
  6232. (outline-up-heading (if (< arg 0) (- arg)
  6233. (- (funcall outline-level) arg)))
  6234. (org-show-subtree)))
  6235. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6236. ((and (featurep 'org-inlinetask)
  6237. (org-inlinetask-at-task-p)
  6238. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6239. (org-inlinetask-toggle-visibility))
  6240. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6241. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6242. (save-excursion (move-beginning-of-line 1)
  6243. (looking-at org-outline-regexp)))
  6244. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6245. (org-cycle-internal-local))
  6246. ;; From there: TAB emulation and template completion.
  6247. (buffer-read-only (org-back-to-heading))
  6248. ((run-hook-with-args-until-success
  6249. 'org-tab-after-check-for-cycling-hook))
  6250. ((run-hook-with-args-until-success
  6251. 'org-tab-before-tab-emulation-hook))
  6252. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6253. (or (not (bolp))
  6254. (not (looking-at org-outline-regexp))))
  6255. (call-interactively (global-key-binding "\t")))
  6256. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6257. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6258. (or (and (eq org-cycle-emulate-tab 'white)
  6259. (= (match-end 0) (point-at-eol)))
  6260. (and (eq org-cycle-emulate-tab 'whitestart)
  6261. (>= (match-end 0) pos))))
  6262. t
  6263. (eq org-cycle-emulate-tab t))
  6264. (call-interactively (global-key-binding "\t")))
  6265. (t (save-excursion
  6266. (org-back-to-heading)
  6267. (org-cycle)))))))
  6268. (defun org-cycle-internal-global ()
  6269. "Do the global cycling action."
  6270. ;; Hack to avoid display of messages for .org attachments in Gnus
  6271. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6272. (cond
  6273. ((and (eq last-command this-command)
  6274. (eq org-cycle-global-status 'overview))
  6275. ;; We just created the overview - now do table of contents
  6276. ;; This can be slow in very large buffers, so indicate action
  6277. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6278. (unless ga (org-unlogged-message "CONTENTS..."))
  6279. (org-content)
  6280. (unless ga (org-unlogged-message "CONTENTS...done"))
  6281. (setq org-cycle-global-status 'contents)
  6282. (run-hook-with-args 'org-cycle-hook 'contents))
  6283. ((and (eq last-command this-command)
  6284. (eq org-cycle-global-status 'contents))
  6285. ;; We just showed the table of contents - now show everything
  6286. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6287. (org-show-all '(headings blocks))
  6288. (unless ga (org-unlogged-message "SHOW ALL"))
  6289. (setq org-cycle-global-status 'all)
  6290. (run-hook-with-args 'org-cycle-hook 'all))
  6291. (t
  6292. ;; Default action: go to overview
  6293. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6294. (org-overview)
  6295. (unless ga (org-unlogged-message "OVERVIEW"))
  6296. (setq org-cycle-global-status 'overview)
  6297. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6298. (defvar org-called-with-limited-levels nil
  6299. "Non-nil when `org-with-limited-levels' is currently active.")
  6300. (defun org-cycle-internal-local ()
  6301. "Do the local cycling action."
  6302. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6303. ;; First, determine end of headline (EOH), end of subtree or item
  6304. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6305. (save-excursion
  6306. (if (org-at-item-p)
  6307. (progn
  6308. (beginning-of-line)
  6309. (setq struct (org-list-struct))
  6310. (setq eoh (point-at-eol))
  6311. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6312. (setq has-children (org-list-has-child-p (point) struct)))
  6313. (org-back-to-heading)
  6314. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6315. (setq eos (save-excursion (org-end-of-subtree t t)
  6316. (when (bolp) (backward-char)) (point)))
  6317. (setq has-children
  6318. (or (save-excursion
  6319. (let ((level (funcall outline-level)))
  6320. (outline-next-heading)
  6321. (and (org-at-heading-p t)
  6322. (> (funcall outline-level) level))))
  6323. (save-excursion
  6324. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6325. ;; Determine end invisible part of buffer (EOL)
  6326. (beginning-of-line 2)
  6327. (while (and (not (eobp)) ;This is like `next-line'.
  6328. (get-char-property (1- (point)) 'invisible))
  6329. (goto-char (next-single-char-property-change (point) 'invisible))
  6330. (and (eolp) (beginning-of-line 2)))
  6331. (setq eol (point)))
  6332. ;; Find out what to do next and set `this-command'
  6333. (cond
  6334. ((= eos eoh)
  6335. ;; Nothing is hidden behind this heading
  6336. (unless (org-before-first-heading-p)
  6337. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6338. (org-unlogged-message "EMPTY ENTRY")
  6339. (setq org-cycle-subtree-status nil)
  6340. (save-excursion
  6341. (goto-char eos)
  6342. (outline-next-heading)
  6343. (when (org-invisible-p) (org-flag-heading nil))))
  6344. ((and (or (>= eol eos)
  6345. (not (string-match "\\S-" (buffer-substring eol eos))))
  6346. (or has-children
  6347. (not (setq children-skipped
  6348. org-cycle-skip-children-state-if-no-children))))
  6349. ;; Entire subtree is hidden in one line: children view
  6350. (unless (org-before-first-heading-p)
  6351. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6352. (if (org-at-item-p)
  6353. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6354. (org-show-entry)
  6355. (org-with-limited-levels (org-show-children))
  6356. (org-show-set-visibility 'canonical)
  6357. ;; Fold every list in subtree to top-level items.
  6358. (when (eq org-cycle-include-plain-lists 'integrate)
  6359. (save-excursion
  6360. (org-back-to-heading)
  6361. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6362. (beginning-of-line 1)
  6363. (let* ((struct (org-list-struct))
  6364. (prevs (org-list-prevs-alist struct))
  6365. (end (org-list-get-bottom-point struct)))
  6366. (dolist (e (org-list-get-all-items (point) struct prevs))
  6367. (org-list-set-item-visibility e struct 'folded))
  6368. (goto-char (if (< end eos) end eos)))))))
  6369. (org-unlogged-message "CHILDREN")
  6370. (save-excursion
  6371. (goto-char eos)
  6372. (outline-next-heading)
  6373. (when (org-invisible-p) (org-flag-heading nil)))
  6374. (setq org-cycle-subtree-status 'children)
  6375. (unless (org-before-first-heading-p)
  6376. (run-hook-with-args 'org-cycle-hook 'children)))
  6377. ((or children-skipped
  6378. (and (eq last-command this-command)
  6379. (eq org-cycle-subtree-status 'children)))
  6380. ;; We just showed the children, or no children are there,
  6381. ;; now show everything.
  6382. (unless (org-before-first-heading-p)
  6383. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6384. (org-flag-region eoh eos nil 'outline)
  6385. (org-unlogged-message
  6386. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6387. (setq org-cycle-subtree-status 'subtree)
  6388. (unless (org-before-first-heading-p)
  6389. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6390. (t
  6391. ;; Default action: hide the subtree.
  6392. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6393. (org-flag-region eoh eos t 'outline)
  6394. (org-unlogged-message "FOLDED")
  6395. (setq org-cycle-subtree-status 'folded)
  6396. (unless (org-before-first-heading-p)
  6397. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6398. ;;;###autoload
  6399. (defun org-global-cycle (&optional arg)
  6400. "Cycle the global visibility. For details see `org-cycle'.
  6401. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6402. With a numeric prefix, show all headlines up to that level."
  6403. (interactive "P")
  6404. (let ((org-cycle-include-plain-lists
  6405. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6406. (cond
  6407. ((integerp arg)
  6408. (org-show-all '(headings blocks))
  6409. (outline-hide-sublevels arg)
  6410. (setq org-cycle-global-status 'contents))
  6411. ((equal arg '(4))
  6412. (org-set-startup-visibility)
  6413. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6414. (t
  6415. (org-cycle '(4))))))
  6416. (defun org-set-startup-visibility ()
  6417. "Set the visibility required by startup options and properties."
  6418. (cond
  6419. ((eq org-startup-folded t)
  6420. (org-overview))
  6421. ((eq org-startup-folded 'content)
  6422. (org-content))
  6423. ((or (eq org-startup-folded 'showeverything)
  6424. (eq org-startup-folded nil))
  6425. (org-show-all)))
  6426. (unless (eq org-startup-folded 'showeverything)
  6427. (when org-hide-block-startup (org-hide-block-all))
  6428. (org-set-visibility-according-to-property)
  6429. (org-cycle-hide-archived-subtrees 'all)
  6430. (org-cycle-hide-drawers 'all)
  6431. (org-cycle-show-empty-lines t)))
  6432. (defun org-set-visibility-according-to-property ()
  6433. "Switch subtree visibility according to VISIBILITY property."
  6434. (interactive)
  6435. (let ((regexp (org-re-property "VISIBILITY")))
  6436. (org-with-point-at 1
  6437. (while (re-search-forward regexp nil t)
  6438. (let ((state (match-string 3)))
  6439. (if (not (org-at-property-p)) (outline-next-heading)
  6440. (save-excursion
  6441. (org-back-to-heading t)
  6442. (outline-hide-subtree)
  6443. (org-reveal)
  6444. (pcase state
  6445. ("folded"
  6446. (outline-hide-subtree))
  6447. ("children"
  6448. (org-show-hidden-entry)
  6449. (org-show-children))
  6450. ("content"
  6451. (save-excursion
  6452. (save-restriction
  6453. (org-narrow-to-subtree)
  6454. (org-content))))
  6455. ((or "all" "showall")
  6456. (outline-show-subtree))
  6457. (_ nil)))
  6458. (org-end-of-subtree)))))))
  6459. (defun org-overview ()
  6460. "Switch to overview mode, showing only top-level headlines.
  6461. This shows all headlines with a level equal or greater than the level
  6462. of the first headline in the buffer. This is important, because if the
  6463. first headline is not level one, then (hide-sublevels 1) gives confusing
  6464. results."
  6465. (interactive)
  6466. (save-excursion
  6467. (let ((level
  6468. (save-excursion
  6469. (goto-char (point-min))
  6470. (when (re-search-forward org-outline-regexp-bol nil t)
  6471. (goto-char (match-beginning 0))
  6472. (funcall outline-level)))))
  6473. (and level (outline-hide-sublevels level)))))
  6474. (defun org-content (&optional arg)
  6475. "Show all headlines in the buffer, like a table of contents.
  6476. With numerical argument N, show content up to level N."
  6477. (interactive "P")
  6478. (org-overview)
  6479. (save-excursion
  6480. ;; Visit all headings and show their offspring
  6481. (and (integerp arg) (org-overview))
  6482. (goto-char (point-max))
  6483. (catch 'exit
  6484. (while (and (progn (condition-case nil
  6485. (outline-previous-visible-heading 1)
  6486. (error (goto-char (point-min))))
  6487. t)
  6488. (looking-at org-outline-regexp))
  6489. (if (integerp arg)
  6490. (org-show-children (1- arg))
  6491. (outline-show-branches))
  6492. (when (bobp) (throw 'exit nil))))))
  6493. (defun org-optimize-window-after-visibility-change (state)
  6494. "Adjust the window after a change in outline visibility.
  6495. This function is the default value of the hook `org-cycle-hook'."
  6496. (when (get-buffer-window (current-buffer))
  6497. (cond
  6498. ((eq state 'content) nil)
  6499. ((eq state 'all) nil)
  6500. ((eq state 'folded) nil)
  6501. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6502. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6503. (defun org-clean-visibility-after-subtree-move ()
  6504. "Fix visibility issues after moving a subtree."
  6505. ;; First, find a reasonable region to look at:
  6506. ;; Start two siblings above, end three below
  6507. (let* ((beg (save-excursion
  6508. (and (org-get-last-sibling)
  6509. (org-get-last-sibling))
  6510. (point)))
  6511. (end (save-excursion
  6512. (and (org-get-next-sibling)
  6513. (org-get-next-sibling)
  6514. (org-get-next-sibling))
  6515. (if (org-at-heading-p)
  6516. (point-at-eol)
  6517. (point))))
  6518. (level (looking-at "\\*+"))
  6519. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6520. (save-excursion
  6521. (save-restriction
  6522. (narrow-to-region beg end)
  6523. (when re
  6524. ;; Properly fold already folded siblings
  6525. (goto-char (point-min))
  6526. (while (re-search-forward re nil t)
  6527. (when (and (not (org-invisible-p))
  6528. (org-invisible-p (line-end-position)))
  6529. (outline-hide-entry))))
  6530. (org-cycle-hide-drawers 'all)
  6531. (org-cycle-show-empty-lines 'overview)))))
  6532. (defun org-cycle-show-empty-lines (state)
  6533. "Show empty lines above all visible headlines.
  6534. The region to be covered depends on STATE when called through
  6535. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6536. entire buffer covered. Note that an empty line is only shown if there
  6537. are at least `org-cycle-separator-lines' empty lines before the headline."
  6538. (when (/= org-cycle-separator-lines 0)
  6539. (save-excursion
  6540. (let* ((n (abs org-cycle-separator-lines))
  6541. (re (cond
  6542. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6543. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6544. (t (let ((ns (number-to-string (- n 2))))
  6545. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6546. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6547. beg end)
  6548. (cond
  6549. ((memq state '(overview contents t))
  6550. (setq beg (point-min) end (point-max)))
  6551. ((memq state '(children folded))
  6552. (setq beg (point)
  6553. end (progn (org-end-of-subtree t t)
  6554. (line-beginning-position 2)))))
  6555. (when beg
  6556. (goto-char beg)
  6557. (while (re-search-forward re end t)
  6558. (unless (get-char-property (match-end 1) 'invisible)
  6559. (let ((e (match-end 1))
  6560. (b (if (>= org-cycle-separator-lines 0)
  6561. (match-beginning 1)
  6562. (save-excursion
  6563. (goto-char (match-beginning 0))
  6564. (skip-chars-backward " \t\n")
  6565. (line-end-position)))))
  6566. (org-flag-region b e nil 'outline))))))))
  6567. ;; Never hide empty lines at the end of the file.
  6568. (save-excursion
  6569. (goto-char (point-max))
  6570. (outline-previous-heading)
  6571. (outline-end-of-heading)
  6572. (when (and (looking-at "[ \t\n]+")
  6573. (= (match-end 0) (point-max)))
  6574. (org-flag-region (point) (match-end 0) nil 'outline))))
  6575. ;;;; Reveal point location
  6576. (defun org-show-context (&optional key)
  6577. "Make sure point and context are visible.
  6578. Optional argument KEY, when non-nil, is a symbol. See
  6579. `org-show-context-detail' for allowed values and how much is to
  6580. be shown."
  6581. (org-show-set-visibility
  6582. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6583. ((cdr (assq key org-show-context-detail)))
  6584. (t (cdr (assq 'default org-show-context-detail))))))
  6585. (defun org-show-set-visibility (detail)
  6586. "Set visibility around point according to DETAIL.
  6587. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6588. `tree', `canonical' or t. See `org-show-context-detail' for more
  6589. information."
  6590. ;; Show current heading and possibly its entry, following headline
  6591. ;; or all children.
  6592. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6593. (org-flag-heading nil)
  6594. (org-show-entry)
  6595. ;; If point is hidden within a drawer or a block, make sure to
  6596. ;; expose it.
  6597. (dolist (o (overlays-at (point)))
  6598. (when (memq (overlay-get o 'invisible)
  6599. '(org-hide-block org-hide-drawer outline))
  6600. (delete-overlay o)))
  6601. (unless (org-before-first-heading-p)
  6602. (org-with-limited-levels
  6603. (cl-case detail
  6604. ((tree canonical t) (org-show-children))
  6605. ((nil minimal ancestors))
  6606. (t (save-excursion
  6607. (outline-next-heading)
  6608. (org-flag-heading nil)))))))
  6609. ;; Show all siblings.
  6610. (when (eq detail 'lineage) (org-show-siblings))
  6611. ;; Show ancestors, possibly with their children.
  6612. (when (memq detail '(ancestors lineage tree canonical t))
  6613. (save-excursion
  6614. (while (org-up-heading-safe)
  6615. (org-flag-heading nil)
  6616. (when (memq detail '(canonical t)) (org-show-entry))
  6617. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6618. (defvar org-reveal-start-hook nil
  6619. "Hook run before revealing a location.")
  6620. (defun org-reveal (&optional siblings)
  6621. "Show current entry, hierarchy above it, and the following headline.
  6622. This can be used to show a consistent set of context around
  6623. locations exposed with `org-show-context'.
  6624. With optional argument SIBLINGS, on each level of the hierarchy all
  6625. siblings are shown. This repairs the tree structure to what it would
  6626. look like when opened with hierarchical calls to `org-cycle'.
  6627. With a \\[universal-argument] \\[universal-argument] prefix, \
  6628. go to the parent and show the entire tree."
  6629. (interactive "P")
  6630. (run-hooks 'org-reveal-start-hook)
  6631. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6632. ((equal siblings '(16))
  6633. (save-excursion
  6634. (when (org-up-heading-safe)
  6635. (org-show-subtree)
  6636. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6637. (t (org-show-set-visibility 'lineage))))
  6638. ;;; Indirect buffer display of subtrees
  6639. (defvar org-indirect-dedicated-frame nil
  6640. "This is the frame being used for indirect tree display.")
  6641. (defvar org-last-indirect-buffer nil)
  6642. (defun org-tree-to-indirect-buffer (&optional arg)
  6643. "Create indirect buffer and narrow it to current subtree.
  6644. With a numerical prefix ARG, go up to this level and then take that tree.
  6645. If ARG is negative, go up that many levels.
  6646. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6647. indirect buffer previously made with this command, to avoid proliferation of
  6648. indirect buffers. However, when you call the command with a \
  6649. `\\[universal-argument]' prefix, or
  6650. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6651. so that you can work with several indirect buffers at the same time. If
  6652. `org-indirect-buffer-display' is `dedicated-frame', the \
  6653. `\\[universal-argument]' prefix also
  6654. requests that a new frame be made for the new buffer, so that the dedicated
  6655. frame is not changed."
  6656. (interactive "P")
  6657. (let ((cbuf (current-buffer))
  6658. (cwin (selected-window))
  6659. (pos (point))
  6660. beg end level heading ibuf)
  6661. (save-excursion
  6662. (org-back-to-heading t)
  6663. (when (numberp arg)
  6664. (setq level (org-outline-level))
  6665. (when (< arg 0) (setq arg (+ level arg)))
  6666. (while (> (setq level (org-outline-level)) arg)
  6667. (org-up-heading-safe)))
  6668. (setq beg (point)
  6669. heading (org-get-heading 'no-tags))
  6670. (org-end-of-subtree t t)
  6671. (when (org-at-heading-p) (backward-char 1))
  6672. (setq end (point)))
  6673. (when (and (buffer-live-p org-last-indirect-buffer)
  6674. (not (eq org-indirect-buffer-display 'new-frame))
  6675. (not arg))
  6676. (kill-buffer org-last-indirect-buffer))
  6677. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6678. org-last-indirect-buffer ibuf)
  6679. (cond
  6680. ((or (eq org-indirect-buffer-display 'new-frame)
  6681. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6682. (select-frame (make-frame))
  6683. (delete-other-windows)
  6684. (pop-to-buffer-same-window ibuf)
  6685. (org-set-frame-title heading))
  6686. ((eq org-indirect-buffer-display 'dedicated-frame)
  6687. (raise-frame
  6688. (select-frame (or (and org-indirect-dedicated-frame
  6689. (frame-live-p org-indirect-dedicated-frame)
  6690. org-indirect-dedicated-frame)
  6691. (setq org-indirect-dedicated-frame (make-frame)))))
  6692. (delete-other-windows)
  6693. (pop-to-buffer-same-window ibuf)
  6694. (org-set-frame-title (concat "Indirect: " heading)))
  6695. ((eq org-indirect-buffer-display 'current-window)
  6696. (pop-to-buffer-same-window ibuf))
  6697. ((eq org-indirect-buffer-display 'other-window)
  6698. (pop-to-buffer ibuf))
  6699. (t (error "Invalid value")))
  6700. (narrow-to-region beg end)
  6701. (org-show-all '(headings blocks))
  6702. (goto-char pos)
  6703. (run-hook-with-args 'org-cycle-hook 'all)
  6704. (and (window-live-p cwin) (select-window cwin))))
  6705. (defun org-get-indirect-buffer (&optional buffer heading)
  6706. (setq buffer (or buffer (current-buffer)))
  6707. (let ((n 1) (base (buffer-name buffer)) bname)
  6708. (while (buffer-live-p
  6709. (get-buffer
  6710. (setq bname
  6711. (concat base "-"
  6712. (if heading (concat heading "-" (number-to-string n))
  6713. (number-to-string n))))))
  6714. (setq n (1+ n)))
  6715. (condition-case nil
  6716. (make-indirect-buffer buffer bname 'clone)
  6717. (error (make-indirect-buffer buffer bname)))))
  6718. (defun org-set-frame-title (title)
  6719. "Set the title of the current frame to the string TITLE."
  6720. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6721. ;;;; Structure editing
  6722. ;;; Inserting headlines
  6723. (defun org--line-empty-p (n)
  6724. "Is the Nth next line empty?
  6725. Counts the current line as N = 1 and the previous line as N = 0;
  6726. see `beginning-of-line'."
  6727. (save-excursion
  6728. (and (not (bobp))
  6729. (or (beginning-of-line n) t)
  6730. (save-match-data
  6731. (looking-at "[ \t]*$")))))
  6732. (defun org-previous-line-empty-p ()
  6733. "Is the previous line a blank line?
  6734. When NEXT is non-nil, check the next line instead."
  6735. (org--line-empty-p 0))
  6736. (defun org-next-line-empty-p ()
  6737. "Is the previous line a blank line?
  6738. When NEXT is non-nil, check the next line instead."
  6739. (org--line-empty-p 2))
  6740. (defun org--blank-before-heading-p (&optional parent)
  6741. "Non-nil when an empty line should precede a new heading here.
  6742. When optional argument PARENT is non-nil, consider parent
  6743. headline instead of current one."
  6744. (pcase (assq 'heading org-blank-before-new-entry)
  6745. (`(heading . auto)
  6746. (save-excursion
  6747. (org-with-limited-levels
  6748. (unless (and (org-before-first-heading-p)
  6749. (not (outline-next-heading)))
  6750. (org-back-to-heading t)
  6751. (when parent (org-up-heading-safe))
  6752. (cond ((not (bobp))
  6753. (org-previous-line-empty-p))
  6754. ((outline-next-heading)
  6755. (org-previous-line-empty-p))
  6756. ;; Ignore trailing spaces on last buffer line.
  6757. ((progn (skip-chars-backward " \t") (bolp))
  6758. (org-previous-line-empty-p))
  6759. (t nil))))))
  6760. (`(heading . ,value) value)
  6761. (_ nil)))
  6762. (defun org-insert-heading (&optional arg invisible-ok top)
  6763. "Insert a new heading or an item with the same depth at point.
  6764. If point is at the beginning of a heading, insert a new heading
  6765. or a new headline above the current one. When at the beginning
  6766. of a regular line of text, turn it into a heading.
  6767. If point is in the middle of a line, split it and create a new
  6768. headline with the text in the current line after point (see
  6769. `org-M-RET-may-split-line' on how to modify this behavior). As
  6770. a special case, on a headline, splitting can only happen on the
  6771. title itself. E.g., this excludes breaking stars or tags.
  6772. With a `\\[universal-argument]' prefix, set \
  6773. `org-insert-heading-respect-content' to
  6774. a non-nil value for the duration of the command. This forces the
  6775. insertion of a heading after the current subtree, independently
  6776. on the location of point.
  6777. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6778. insert the heading at the end of the tree
  6779. above the current heading. For example, if point is within a
  6780. 2nd-level heading, then it will insert a 2nd-level heading at
  6781. the end of the 1st-level parent subtree.
  6782. When INVISIBLE-OK is set, stop at invisible headlines when going
  6783. back. This is important for non-interactive uses of the
  6784. command.
  6785. When optional argument TOP is non-nil, insert a level 1 heading,
  6786. unconditionally."
  6787. (interactive "P")
  6788. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6789. (level (org-current-level))
  6790. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6791. (cond
  6792. ((or org-insert-heading-respect-content
  6793. (member arg '((4) (16)))
  6794. (and (not invisible-ok)
  6795. (invisible-p (max (1- (point)) (point-min)))))
  6796. ;; Position point at the location of insertion. Make sure we
  6797. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6798. (org-with-limited-levels
  6799. (if (not level) (outline-next-heading) ;before first headline
  6800. (org-back-to-heading invisible-ok)
  6801. (when (equal arg '(16)) (org-up-heading-safe))
  6802. (org-end-of-subtree)))
  6803. (unless (bolp) (insert "\n"))
  6804. (unless (and blank? (org-previous-line-empty-p))
  6805. (org-N-empty-lines-before-current (if blank? 1 0)))
  6806. (insert stars " ")
  6807. (when (eobp) (save-excursion (insert "\n")))
  6808. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6809. ;; is visible.
  6810. (unless invisible-ok
  6811. (pcase (get-char-property-and-overlay (point) 'invisible)
  6812. (`(outline . ,o)
  6813. (move-overlay o (overlay-start o) (line-end-position 0)))
  6814. (_ nil))))
  6815. ;; At a headline...
  6816. ((org-at-heading-p)
  6817. (cond ((bolp)
  6818. (when blank? (save-excursion (insert "\n")))
  6819. (save-excursion (insert stars " \n"))
  6820. (unless (and blank? (org-previous-line-empty-p))
  6821. (org-N-empty-lines-before-current (if blank? 1 0)))
  6822. (end-of-line))
  6823. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6824. (org-match-line org-complex-heading-regexp)
  6825. (org-pos-in-match-range (point) 4))
  6826. ;; Grab the text that should moved to the new headline.
  6827. ;; Preserve tags.
  6828. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6829. (if (looking-at "[ \t]*$") (replace-match "")
  6830. (org-align-tags))
  6831. (end-of-line)
  6832. (when blank? (insert "\n"))
  6833. (insert "\n" stars " ")
  6834. (when (org-string-nw-p split) (insert split))
  6835. (when (eobp) (save-excursion (insert "\n")))))
  6836. (t
  6837. (end-of-line)
  6838. (when blank? (insert "\n"))
  6839. (insert "\n" stars " ")
  6840. (when (eobp) (save-excursion (insert "\n"))))))
  6841. ;; On regular text, turn line into a headline or split, if
  6842. ;; appropriate.
  6843. ((bolp)
  6844. (insert stars " ")
  6845. (unless (and blank? (org-previous-line-empty-p))
  6846. (org-N-empty-lines-before-current (if blank? 1 0))))
  6847. (t
  6848. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6849. (end-of-line))
  6850. (insert "\n" stars " ")
  6851. (unless (and blank? (org-previous-line-empty-p))
  6852. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6853. (run-hooks 'org-insert-heading-hook))
  6854. (defun org-N-empty-lines-before-current (n)
  6855. "Make the number of empty lines before current exactly N.
  6856. So this will delete or add empty lines."
  6857. (let ((column (current-column)))
  6858. (beginning-of-line)
  6859. (unless (bobp)
  6860. (let ((start (save-excursion
  6861. (skip-chars-backward " \r\t\n")
  6862. (line-end-position))))
  6863. (delete-region start (line-end-position 0))))
  6864. (insert (make-string n ?\n))
  6865. (move-to-column column)))
  6866. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6867. "Return the heading of the current entry, without the stars.
  6868. When NO-TAGS is non-nil, don't include tags.
  6869. When NO-TODO is non-nil, don't include TODO keywords.
  6870. When NO-PRIORITY is non-nil, don't include priority cookie.
  6871. When NO-COMMENT is non-nil, don't include COMMENT string.
  6872. Return nil before first heading."
  6873. (unless (org-before-first-heading-p)
  6874. (save-excursion
  6875. (org-back-to-heading t)
  6876. (let ((case-fold-search nil))
  6877. (looking-at org-complex-heading-regexp)
  6878. (let ((todo (and (not no-todo) (match-string 2)))
  6879. (priority (and (not no-priority) (match-string 3)))
  6880. (headline (pcase (match-string 4)
  6881. (`nil "")
  6882. ((and (guard no-comment) h)
  6883. (replace-regexp-in-string
  6884. (eval-when-compile
  6885. (format "\\`%s[ \t]+" org-comment-string))
  6886. "" h))
  6887. (h h)))
  6888. (tags (and (not no-tags) (match-string 5))))
  6889. (mapconcat #'identity
  6890. (delq nil (list todo priority headline tags))
  6891. " "))))))
  6892. (defun org-heading-components ()
  6893. "Return the components of the current heading.
  6894. This is a list with the following elements:
  6895. - the level as an integer
  6896. - the reduced level, different if `org-odd-levels-only' is set.
  6897. - the TODO keyword, or nil
  6898. - the priority character, like ?A, or nil if no priority is given
  6899. - the headline text itself, or the tags string if no headline text
  6900. - the tags string, or nil."
  6901. (save-excursion
  6902. (org-back-to-heading t)
  6903. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6904. (list (length (match-string 1))
  6905. (org-reduced-level (length (match-string 1)))
  6906. (match-string-no-properties 2)
  6907. (and (match-end 3) (aref (match-string 3) 2))
  6908. (match-string-no-properties 4)
  6909. (match-string-no-properties 5)))))
  6910. (defun org-get-entry ()
  6911. "Get the entry text, after heading, entire subtree."
  6912. (save-excursion
  6913. (org-back-to-heading t)
  6914. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6915. (defun org-edit-headline (&optional heading)
  6916. "Edit the current headline.
  6917. Set it to HEADING when provided."
  6918. (interactive)
  6919. (org-with-wide-buffer
  6920. (org-back-to-heading t)
  6921. (let ((case-fold-search nil))
  6922. (when (looking-at org-complex-heading-regexp)
  6923. (let* ((old (match-string-no-properties 4))
  6924. (new (save-match-data
  6925. (org-trim (or heading (read-string "Edit: " old))))))
  6926. (unless (equal old new)
  6927. (if old (replace-match new t t nil 4)
  6928. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6929. (insert " " new))
  6930. (org-align-tags)
  6931. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6932. (defun org-insert-heading-after-current ()
  6933. "Insert a new heading with same level as current, after current subtree."
  6934. (interactive)
  6935. (org-back-to-heading)
  6936. (org-insert-heading)
  6937. (org-move-subtree-down)
  6938. (end-of-line 1))
  6939. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6940. "Insert heading with `org-insert-heading-respect-content' set to t."
  6941. (interactive)
  6942. (org-insert-heading '(4) invisible-ok))
  6943. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6944. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6945. (interactive)
  6946. (org-insert-todo-heading force-state '(4)))
  6947. (defun org-insert-todo-heading (arg &optional force-heading)
  6948. "Insert a new heading with the same level and TODO state as current heading.
  6949. If the heading has no TODO state, or if the state is DONE, use
  6950. the first state (TODO by default). Also with one prefix arg,
  6951. force first state. With two prefix args, force inserting at the
  6952. end of the parent subtree.
  6953. When called at a plain list item, insert a new item with an
  6954. unchecked check box."
  6955. (interactive "P")
  6956. (when (or force-heading (not (org-insert-item 'checkbox)))
  6957. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6958. force-heading))
  6959. (save-excursion
  6960. (org-forward-heading-same-level -1)
  6961. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6962. (let* ((new-mark-x
  6963. (if (or (equal arg '(4))
  6964. (not (match-beginning 2))
  6965. (member (match-string 2) org-done-keywords))
  6966. (car org-todo-keywords-1)
  6967. (match-string 2)))
  6968. (new-mark
  6969. (or
  6970. (run-hook-with-args-until-success
  6971. 'org-todo-get-default-hook new-mark-x nil)
  6972. new-mark-x)))
  6973. (beginning-of-line 1)
  6974. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6975. (if org-treat-insert-todo-heading-as-state-change
  6976. (org-todo new-mark)
  6977. (insert new-mark " "))))
  6978. (when org-provide-todo-statistics
  6979. (org-update-parent-todo-statistics))))
  6980. (defun org-insert-subheading (arg)
  6981. "Insert a new subheading and demote it.
  6982. Works for outline headings and for plain lists alike."
  6983. (interactive "P")
  6984. (org-insert-heading arg)
  6985. (cond
  6986. ((org-at-heading-p) (org-do-demote))
  6987. ((org-at-item-p) (org-indent-item))))
  6988. (defun org-insert-todo-subheading (arg)
  6989. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6990. Works for outline headings and for plain lists alike."
  6991. (interactive "P")
  6992. (org-insert-todo-heading arg)
  6993. (cond
  6994. ((org-at-heading-p) (org-do-demote))
  6995. ((org-at-item-p) (org-indent-item))))
  6996. ;;; Promotion and Demotion
  6997. (defvar org-after-demote-entry-hook nil
  6998. "Hook run after an entry has been demoted.
  6999. The cursor will be at the beginning of the entry.
  7000. When a subtree is being demoted, the hook will be called for each node.")
  7001. (defvar org-after-promote-entry-hook nil
  7002. "Hook run after an entry has been promoted.
  7003. The cursor will be at the beginning of the entry.
  7004. When a subtree is being promoted, the hook will be called for each node.")
  7005. (defun org-promote-subtree ()
  7006. "Promote the entire subtree.
  7007. See also `org-promote'."
  7008. (interactive)
  7009. (save-excursion
  7010. (org-with-limited-levels (org-map-tree 'org-promote)))
  7011. (org-fix-position-after-promote))
  7012. (defun org-demote-subtree ()
  7013. "Demote the entire subtree.
  7014. See `org-demote' and `org-promote'."
  7015. (interactive)
  7016. (save-excursion
  7017. (org-with-limited-levels (org-map-tree 'org-demote)))
  7018. (org-fix-position-after-promote))
  7019. (defun org-do-promote ()
  7020. "Promote the current heading higher up the tree.
  7021. If the region is active in `transient-mark-mode', promote all
  7022. headings in the region."
  7023. (interactive)
  7024. (save-excursion
  7025. (if (org-region-active-p)
  7026. (org-map-region 'org-promote (region-beginning) (region-end))
  7027. (org-promote)))
  7028. (org-fix-position-after-promote))
  7029. (defun org-do-demote ()
  7030. "Demote the current heading lower down the tree.
  7031. If the region is active in `transient-mark-mode', demote all
  7032. headings in the region."
  7033. (interactive)
  7034. (save-excursion
  7035. (if (org-region-active-p)
  7036. (org-map-region 'org-demote (region-beginning) (region-end))
  7037. (org-demote)))
  7038. (org-fix-position-after-promote))
  7039. (defun org-fix-position-after-promote ()
  7040. "Fix cursor position and indentation after demoting/promoting."
  7041. (let ((pos (point)))
  7042. (when (save-excursion
  7043. (beginning-of-line)
  7044. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7045. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7046. (cond ((eobp) (insert " "))
  7047. ((eolp) (insert " "))
  7048. ((equal (char-after) ?\s) (forward-char 1))))))
  7049. (defun org-current-level ()
  7050. "Return the level of the current entry, or nil if before the first headline.
  7051. The level is the number of stars at the beginning of the
  7052. headline. Use `org-reduced-level' to remove the effect of
  7053. `org-odd-levels'. Unlike to `org-outline-level', this function
  7054. ignores inlinetasks."
  7055. (let ((level (org-with-limited-levels (org-outline-level))))
  7056. (and (> level 0) level)))
  7057. (defun org-get-previous-line-level ()
  7058. "Return the outline depth of the last headline before the current line.
  7059. Returns 0 for the first headline in the buffer, and nil if before the
  7060. first headline."
  7061. (and (org-current-level)
  7062. (or (and (/= (line-beginning-position) (point-min))
  7063. (save-excursion (beginning-of-line 0) (org-current-level)))
  7064. 0)))
  7065. (defun org-reduced-level (l)
  7066. "Compute the effective level of a heading.
  7067. This takes into account the setting of `org-odd-levels-only'."
  7068. (cond
  7069. ((zerop l) 0)
  7070. (org-odd-levels-only (1+ (floor (/ l 2))))
  7071. (t l)))
  7072. (defun org-level-increment ()
  7073. "Return the number of stars that will be added or removed at a
  7074. time to headlines when structure editing, based on the value of
  7075. `org-odd-levels-only'."
  7076. (if org-odd-levels-only 2 1))
  7077. (defun org-get-valid-level (level &optional change)
  7078. "Rectify a level change under the influence of `org-odd-levels-only'.
  7079. LEVEL is a current level, CHANGE is by how much the level should
  7080. be modified. Even if CHANGE is nil, LEVEL may be returned
  7081. modified because even level numbers will become the next higher
  7082. odd number. Returns values greater than 0."
  7083. (if org-odd-levels-only
  7084. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7085. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7086. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7087. (max 1 (+ level (or change 0)))))
  7088. (defun org-promote ()
  7089. "Promote the current heading higher up the tree."
  7090. (org-with-wide-buffer
  7091. (org-back-to-heading t)
  7092. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7093. after-change-functions))
  7094. (level (save-match-data (funcall outline-level)))
  7095. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7096. (diff (abs (- level (length up-head) -1))))
  7097. (cond
  7098. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7099. (replace-match "# " nil t))
  7100. ((= level 1)
  7101. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7102. (t (replace-match up-head nil t)))
  7103. (unless (= level 1)
  7104. (when org-auto-align-tags (org-align-tags))
  7105. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7106. (run-hooks 'org-after-promote-entry-hook))))
  7107. (defun org-demote ()
  7108. "Demote the current heading lower down the tree."
  7109. (org-with-wide-buffer
  7110. (org-back-to-heading t)
  7111. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7112. after-change-functions))
  7113. (level (save-match-data (funcall outline-level)))
  7114. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7115. (diff (abs (- level (length down-head) -1))))
  7116. (replace-match down-head nil t)
  7117. (when org-auto-align-tags (org-align-tags))
  7118. (when org-adapt-indentation (org-fixup-indentation diff))
  7119. (run-hooks 'org-after-demote-entry-hook))))
  7120. (defun org-cycle-level ()
  7121. "Cycle the level of an empty headline through possible states.
  7122. This goes first to child, then to parent, level, then up the hierarchy.
  7123. After top level, it switches back to sibling level."
  7124. (interactive)
  7125. (let ((org-adapt-indentation nil))
  7126. (when (org-point-at-end-of-empty-headline)
  7127. (setq this-command 'org-cycle-level) ; Only needed for caching
  7128. (let ((cur-level (org-current-level))
  7129. (prev-level (org-get-previous-line-level)))
  7130. (cond
  7131. ;; If first headline in file, promote to top-level.
  7132. ((= prev-level 0)
  7133. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7134. do (org-do-promote)))
  7135. ;; If same level as prev, demote one.
  7136. ((= prev-level cur-level)
  7137. (org-do-demote))
  7138. ;; If parent is top-level, promote to top level if not already.
  7139. ((= prev-level 1)
  7140. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7141. do (org-do-promote)))
  7142. ;; If top-level, return to prev-level.
  7143. ((= cur-level 1)
  7144. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7145. do (org-do-demote)))
  7146. ;; If less than prev-level, promote one.
  7147. ((< cur-level prev-level)
  7148. (org-do-promote))
  7149. ;; If deeper than prev-level, promote until higher than
  7150. ;; prev-level.
  7151. ((> cur-level prev-level)
  7152. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7153. do (org-do-promote))))
  7154. t))))
  7155. (defun org-map-tree (fun)
  7156. "Call FUN for every heading underneath the current one."
  7157. (org-back-to-heading t)
  7158. (let ((level (funcall outline-level)))
  7159. (save-excursion
  7160. (funcall fun)
  7161. (while (and (progn
  7162. (outline-next-heading)
  7163. (> (funcall outline-level) level))
  7164. (not (eobp)))
  7165. (funcall fun)))))
  7166. (defun org-map-region (fun beg end)
  7167. "Call FUN for every heading between BEG and END."
  7168. (let ((org-ignore-region t))
  7169. (save-excursion
  7170. (setq end (copy-marker end))
  7171. (goto-char beg)
  7172. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7173. (< (point) end))
  7174. (funcall fun))
  7175. (while (and (progn
  7176. (outline-next-heading)
  7177. (< (point) end))
  7178. (not (eobp)))
  7179. (funcall fun)))))
  7180. (defun org-fixup-indentation (diff)
  7181. "Change the indentation in the current entry by DIFF.
  7182. DIFF is an integer. Indentation is done according to the
  7183. following rules:
  7184. - Planning information and property drawers are always indented
  7185. according to the new level of the headline;
  7186. - Footnote definitions and their contents are ignored;
  7187. - Inlinetasks' boundaries are not shifted;
  7188. - Empty lines are ignored;
  7189. - Other lines' indentation are shifted by DIFF columns, unless
  7190. it would introduce a structural change in the document, in
  7191. which case no shifting is done at all.
  7192. Assume point is at a heading or an inlinetask beginning."
  7193. (org-with-wide-buffer
  7194. (narrow-to-region (line-beginning-position)
  7195. (save-excursion
  7196. (if (org-with-limited-levels (org-at-heading-p))
  7197. (org-with-limited-levels (outline-next-heading))
  7198. (org-inlinetask-goto-end))
  7199. (point)))
  7200. (forward-line)
  7201. ;; Indent properly planning info and property drawer.
  7202. (when (looking-at-p org-planning-line-re)
  7203. (org-indent-line)
  7204. (forward-line))
  7205. (when (looking-at org-property-drawer-re)
  7206. (goto-char (match-end 0))
  7207. (forward-line)
  7208. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7209. (catch 'no-shift
  7210. (when (zerop diff) (throw 'no-shift nil))
  7211. ;; If DIFF is negative, first check if a shift is possible at all
  7212. ;; (e.g., it doesn't break structure). This can only happen if
  7213. ;; some contents are not properly indented.
  7214. (let ((case-fold-search t))
  7215. (when (< diff 0)
  7216. (let ((diff (- diff))
  7217. (forbidden-re (concat org-outline-regexp
  7218. "\\|"
  7219. (substring org-footnote-definition-re 1))))
  7220. (save-excursion
  7221. (while (not (eobp))
  7222. (cond
  7223. ((looking-at-p "[ \t]*$") (forward-line))
  7224. ((and (looking-at-p org-footnote-definition-re)
  7225. (let ((e (org-element-at-point)))
  7226. (and (eq (org-element-type e) 'footnote-definition)
  7227. (goto-char (org-element-property :end e))))))
  7228. ((looking-at-p org-outline-regexp) (forward-line))
  7229. ;; Give up if shifting would move before column 0 or
  7230. ;; if it would introduce a headline or a footnote
  7231. ;; definition.
  7232. (t
  7233. (skip-chars-forward " \t")
  7234. (let ((ind (current-column)))
  7235. (when (or (< ind diff)
  7236. (and (= ind diff) (looking-at-p forbidden-re)))
  7237. (throw 'no-shift nil)))
  7238. ;; Ignore contents of example blocks and source
  7239. ;; blocks if their indentation is meant to be
  7240. ;; preserved. Jump to block's closing line.
  7241. (beginning-of-line)
  7242. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7243. (let ((e (org-element-at-point)))
  7244. (and (memq (org-element-type e)
  7245. '(example-block src-block))
  7246. (or org-src-preserve-indentation
  7247. (org-element-property :preserve-indent e))
  7248. (goto-char (org-element-property :end e))
  7249. (progn (skip-chars-backward " \r\t\n")
  7250. (beginning-of-line)
  7251. t))))
  7252. (forward-line))))))))
  7253. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7254. ;; by DIFF. Also skip contents of source or example blocks
  7255. ;; when indentation is meant to be preserved.
  7256. (while (not (eobp))
  7257. (cond
  7258. ((and (looking-at-p org-footnote-definition-re)
  7259. (let ((e (org-element-at-point)))
  7260. (and (eq (org-element-type e) 'footnote-definition)
  7261. (goto-char (org-element-property :end e))))))
  7262. ((looking-at-p org-outline-regexp) (forward-line))
  7263. ((looking-at-p "[ \t]*$") (forward-line))
  7264. (t
  7265. (indent-line-to (+ (current-indentation) diff))
  7266. (beginning-of-line)
  7267. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7268. (let ((e (org-element-at-point)))
  7269. (and (memq (org-element-type e)
  7270. '(example-block src-block))
  7271. (or org-src-preserve-indentation
  7272. (org-element-property :preserve-indent e))
  7273. (goto-char (org-element-property :end e))
  7274. (progn (skip-chars-backward " \r\t\n")
  7275. (beginning-of-line)
  7276. t))))
  7277. (forward-line)))))))))
  7278. (defun org-convert-to-odd-levels ()
  7279. "Convert an Org file with all levels allowed to one with odd levels.
  7280. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7281. level 5 etc."
  7282. (interactive)
  7283. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7284. (let ((outline-level 'org-outline-level)
  7285. (org-odd-levels-only nil) n)
  7286. (save-excursion
  7287. (goto-char (point-min))
  7288. (while (re-search-forward "^\\*\\*+ " nil t)
  7289. (setq n (- (length (match-string 0)) 2))
  7290. (while (>= (setq n (1- n)) 0)
  7291. (org-demote))
  7292. (end-of-line 1))))))
  7293. (defun org-convert-to-oddeven-levels ()
  7294. "Convert an Org file with only odd levels to one with odd/even levels.
  7295. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7296. file contains a section with an even level, conversion would
  7297. destroy the structure of the file. An error is signaled in this
  7298. case."
  7299. (interactive)
  7300. (goto-char (point-min))
  7301. ;; First check if there are no even levels
  7302. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7303. (org-show-set-visibility 'canonical)
  7304. (error "Not all levels are odd in this file. Conversion not possible"))
  7305. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7306. (let ((outline-regexp org-outline-regexp)
  7307. (outline-level 'org-outline-level)
  7308. (org-odd-levels-only nil) n)
  7309. (save-excursion
  7310. (goto-char (point-min))
  7311. (while (re-search-forward "^\\*\\*+ " nil t)
  7312. (setq n (/ (1- (length (match-string 0))) 2))
  7313. (while (>= (setq n (1- n)) 0)
  7314. (org-promote))
  7315. (end-of-line 1))))))
  7316. (defun org-tr-level (n)
  7317. "Make N odd if required."
  7318. (if org-odd-levels-only (1+ (/ n 2)) n))
  7319. ;;; Vertical tree motion, cutting and pasting of subtrees
  7320. (defun org-move-subtree-up (&optional arg)
  7321. "Move the current subtree up past ARG headlines of the same level."
  7322. (interactive "p")
  7323. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7324. (defun org-move-subtree-down (&optional arg)
  7325. "Move the current subtree down past ARG headlines of the same level."
  7326. (interactive "p")
  7327. (setq arg (prefix-numeric-value arg))
  7328. (org-preserve-local-variables
  7329. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7330. 'org-get-last-sibling))
  7331. (ins-point (make-marker))
  7332. (cnt (abs arg))
  7333. (col (current-column))
  7334. beg end txt folded)
  7335. ;; Select the tree
  7336. (org-back-to-heading)
  7337. (setq beg (point))
  7338. (save-match-data
  7339. (save-excursion (outline-end-of-heading)
  7340. (setq folded (org-invisible-p)))
  7341. (progn (org-end-of-subtree nil t)
  7342. (unless (eobp) (backward-char))))
  7343. (outline-next-heading)
  7344. (setq end (point))
  7345. (goto-char beg)
  7346. ;; Find insertion point, with error handling
  7347. (while (> cnt 0)
  7348. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7349. (goto-char beg)
  7350. (user-error "Cannot move past superior level or buffer limit"))
  7351. (setq cnt (1- cnt)))
  7352. (when (> arg 0)
  7353. ;; Moving forward - still need to move over subtree
  7354. (org-end-of-subtree t t)
  7355. (save-excursion
  7356. (org-back-over-empty-lines)
  7357. (or (bolp) (newline))))
  7358. (move-marker ins-point (point))
  7359. (setq txt (buffer-substring beg end))
  7360. (org-save-markers-in-region beg end)
  7361. (delete-region beg end)
  7362. (org-remove-empty-overlays-at beg)
  7363. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7364. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7365. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7366. (let ((bbb (point)))
  7367. (insert-before-markers txt)
  7368. (org-reinstall-markers-in-region bbb)
  7369. (move-marker ins-point bbb))
  7370. (or (bolp) (insert "\n"))
  7371. (goto-char ins-point)
  7372. (org-skip-whitespace)
  7373. (move-marker ins-point nil)
  7374. (if folded
  7375. (outline-hide-subtree)
  7376. (org-show-entry)
  7377. (org-show-children))
  7378. (org-clean-visibility-after-subtree-move)
  7379. ;; move back to the initial column we were at
  7380. (move-to-column col))))
  7381. (defvar org-subtree-clip ""
  7382. "Clipboard for cut and paste of subtrees.
  7383. This is actually only a copy of the kill, because we use the normal kill
  7384. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7385. (defvar org-subtree-clip-folded nil
  7386. "Was the last copied subtree folded?
  7387. This is used to fold the tree back after pasting.")
  7388. (defun org-cut-subtree (&optional n)
  7389. "Cut the current subtree into the clipboard.
  7390. With prefix arg N, cut this many sequential subtrees.
  7391. This is a short-hand for marking the subtree and then cutting it."
  7392. (interactive "p")
  7393. (org-copy-subtree n 'cut))
  7394. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7395. "Copy the current subtree into the clipboard.
  7396. With prefix arg N, copy this many sequential subtrees.
  7397. This is a short-hand for marking the subtree and then copying it.
  7398. If CUT is non-nil, actually cut the subtree.
  7399. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7400. of some markers in the region, even if CUT is non-nil. This is
  7401. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7402. (interactive "p")
  7403. (org-preserve-local-variables
  7404. (let (beg end folded (beg0 (point)))
  7405. (if (called-interactively-p 'any)
  7406. (org-back-to-heading nil) ; take what looks like a subtree
  7407. (org-back-to-heading t)) ; take what is really there
  7408. (setq beg (point))
  7409. (skip-chars-forward " \t\r\n")
  7410. (save-match-data
  7411. (if nosubtrees
  7412. (outline-next-heading)
  7413. (save-excursion (outline-end-of-heading)
  7414. (setq folded (org-invisible-p)))
  7415. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7416. (org-end-of-subtree t t)))
  7417. ;; Include the end of an inlinetask
  7418. (when (and (featurep 'org-inlinetask)
  7419. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7420. "END[ \t]*$")))
  7421. (end-of-line))
  7422. (setq end (point))
  7423. (goto-char beg0)
  7424. (when (> end beg)
  7425. (setq org-subtree-clip-folded folded)
  7426. (when (or cut force-store-markers)
  7427. (org-save-markers-in-region beg end))
  7428. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7429. (setq org-subtree-clip (current-kill 0))
  7430. (message "%s: Subtree(s) with %d characters"
  7431. (if cut "Cut" "Copied")
  7432. (length org-subtree-clip))))))
  7433. (defun org-paste-subtree (&optional level tree for-yank remove)
  7434. "Paste the clipboard as a subtree, with modification of headline level.
  7435. The entire subtree is promoted or demoted in order to match a new headline
  7436. level.
  7437. If the cursor is at the beginning of a headline, the same level as
  7438. that headline is used to paste the tree.
  7439. If not, the new level is derived from the *visible* headings
  7440. before and after the insertion point, and taken to be the inferior headline
  7441. level of the two. So if the previous visible heading is level 3 and the
  7442. next is level 4 (or vice versa), level 4 will be used for insertion.
  7443. This makes sure that the subtree remains an independent subtree and does
  7444. not swallow low level entries.
  7445. You can also force a different level, either by using a numeric prefix
  7446. argument, or by inserting the heading marker by hand. For example, if the
  7447. cursor is after \"*****\", then the tree will be shifted to level 5.
  7448. If optional TREE is given, use this text instead of the kill ring.
  7449. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7450. move back over whitespace before inserting, and move point to the end of
  7451. the inserted text when done.
  7452. When REMOVE is non-nil, remove the subtree from the clipboard."
  7453. (interactive "P")
  7454. (setq tree (or tree (and kill-ring (current-kill 0))))
  7455. (unless (org-kill-is-subtree-p tree)
  7456. (user-error
  7457. (substitute-command-keys
  7458. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7459. (org-with-limited-levels
  7460. (let* ((visp (not (org-invisible-p)))
  7461. (txt tree)
  7462. (old-level (if (string-match org-outline-regexp-bol txt)
  7463. (- (match-end 0) (match-beginning 0) 1)
  7464. -1))
  7465. (force-level
  7466. (cond
  7467. (level (prefix-numeric-value level))
  7468. ;; When point is after the stars in an otherwise empty
  7469. ;; headline, use the number of stars as the forced level.
  7470. ((and (org-match-line "^\\*+[ \t]*$")
  7471. (not (eq ?* (char-after))))
  7472. (org-outline-level))
  7473. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7474. (previous-level
  7475. (save-excursion
  7476. (org-previous-visible-heading 1)
  7477. (if (org-at-heading-p) (org-outline-level) 1)))
  7478. (next-level
  7479. (save-excursion
  7480. (if (org-at-heading-p) (org-outline-level)
  7481. (org-next-visible-heading 1)
  7482. (if (org-at-heading-p) (org-outline-level) 1))))
  7483. (new-level (or force-level (max previous-level next-level)))
  7484. (shift (if (or (= old-level -1)
  7485. (= new-level -1)
  7486. (= old-level new-level))
  7487. 0
  7488. (- new-level old-level)))
  7489. (delta (if (> shift 0) -1 1))
  7490. (func (if (> shift 0) #'org-demote #'org-promote))
  7491. (org-odd-levels-only nil)
  7492. beg end newend)
  7493. ;; Remove the forced level indicator.
  7494. (when (and force-level (not level))
  7495. (delete-region (line-beginning-position) (point)))
  7496. ;; Paste before the next visible heading or at end of buffer,
  7497. ;; unless point is at the beginning of a headline.
  7498. (unless (and (bolp) (org-at-heading-p))
  7499. (org-next-visible-heading 1)
  7500. (unless (bolp) (insert "\n")))
  7501. (setq beg (point))
  7502. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7503. (insert-before-markers txt)
  7504. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7505. (setq newend (point))
  7506. (org-reinstall-markers-in-region beg)
  7507. (setq end (point))
  7508. (goto-char beg)
  7509. (skip-chars-forward " \t\n\r")
  7510. (setq beg (point))
  7511. (when (and (org-invisible-p) visp)
  7512. (save-excursion (outline-show-heading)))
  7513. ;; Shift if necessary.
  7514. (unless (= shift 0)
  7515. (save-restriction
  7516. (narrow-to-region beg end)
  7517. (while (not (= shift 0))
  7518. (org-map-region func (point-min) (point-max))
  7519. (setq shift (+ delta shift)))
  7520. (goto-char (point-min))
  7521. (setq newend (point-max))))
  7522. (when (or for-yank (called-interactively-p 'interactive))
  7523. (message "Clipboard pasted as level %d subtree" new-level))
  7524. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7525. kill-ring
  7526. (equal org-subtree-clip (current-kill 0))
  7527. org-subtree-clip-folded)
  7528. ;; The tree was folded before it was killed/copied
  7529. (outline-hide-subtree))
  7530. (when for-yank (goto-char newend))
  7531. (when remove (pop kill-ring)))))
  7532. (defun org-kill-is-subtree-p (&optional txt)
  7533. "Check if the current kill is an outline subtree, or a set of trees.
  7534. Returns nil if kill does not start with a headline, or if the first
  7535. headline level is not the largest headline level in the tree.
  7536. So this will actually accept several entries of equal levels as well,
  7537. which is OK for `org-paste-subtree'.
  7538. If optional TXT is given, check this string instead of the current kill."
  7539. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7540. (re (org-get-limited-outline-regexp))
  7541. (^re (concat "^" re))
  7542. (start-level (and kill
  7543. (string-match
  7544. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7545. kill)
  7546. (- (match-end 2) (match-beginning 2) 1)))
  7547. (start (1+ (or (match-beginning 2) -1))))
  7548. (if (not start-level)
  7549. (progn
  7550. nil) ;; does not even start with a heading
  7551. (catch 'exit
  7552. (while (setq start (string-match ^re kill (1+ start)))
  7553. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7554. (throw 'exit nil)))
  7555. t))))
  7556. (defvar org-markers-to-move nil
  7557. "Markers that should be moved with a cut-and-paste operation.
  7558. Those markers are stored together with their positions relative to
  7559. the start of the region.")
  7560. (defun org-save-markers-in-region (beg end)
  7561. "Check markers in region.
  7562. If these markers are between BEG and END, record their position relative
  7563. to BEG, so that after moving the block of text, we can put the markers back
  7564. into place.
  7565. This function gets called just before an entry or tree gets cut from the
  7566. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7567. called immediately, to move the markers with the entries."
  7568. (setq org-markers-to-move nil)
  7569. (when (featurep 'org-clock)
  7570. (org-clock-save-markers-for-cut-and-paste beg end))
  7571. (when (featurep 'org-agenda)
  7572. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7573. (defun org-check-and-save-marker (marker beg end)
  7574. "Check if MARKER is between BEG and END.
  7575. If yes, remember the marker and the distance to BEG."
  7576. (when (and (marker-buffer marker)
  7577. (equal (marker-buffer marker) (current-buffer))
  7578. (>= marker beg) (< marker end))
  7579. (push (cons marker (- marker beg)) org-markers-to-move)))
  7580. (defun org-reinstall-markers-in-region (beg)
  7581. "Move all remembered markers to their position relative to BEG."
  7582. (dolist (x org-markers-to-move)
  7583. (move-marker (car x) (+ beg (cdr x))))
  7584. (setq org-markers-to-move nil))
  7585. (defun org-narrow-to-subtree ()
  7586. "Narrow buffer to the current subtree."
  7587. (interactive)
  7588. (save-excursion
  7589. (save-match-data
  7590. (org-with-limited-levels
  7591. (narrow-to-region
  7592. (progn (org-back-to-heading t) (point))
  7593. (progn (org-end-of-subtree t t)
  7594. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7595. (point)))))))
  7596. (defun org-toggle-narrow-to-subtree ()
  7597. "Narrow to the subtree at point or widen a narrowed buffer."
  7598. (interactive)
  7599. (if (buffer-narrowed-p)
  7600. (widen)
  7601. (org-narrow-to-subtree)))
  7602. (defun org-narrow-to-block ()
  7603. "Narrow buffer to the current block."
  7604. (interactive)
  7605. (let* ((case-fold-search t)
  7606. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7607. "^[ \t]*#\\+end_.*")))
  7608. (if blockp
  7609. (narrow-to-region (car blockp) (cdr blockp))
  7610. (user-error "Not in a block"))))
  7611. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7612. "Clone the task (subtree) at point N times.
  7613. The clones will be inserted as siblings.
  7614. In interactive use, the user will be prompted for the number of
  7615. clones to be produced. If the entry has a timestamp, the user
  7616. will also be prompted for a time shift, which may be a repeater
  7617. as used in time stamps, for example `+3d'. To disable this,
  7618. you can call the function with a universal prefix argument.
  7619. When a valid repeater is given and the entry contains any time
  7620. stamps, the clones will become a sequence in time, with time
  7621. stamps in the subtree shifted for each clone produced. If SHIFT
  7622. is nil or the empty string, time stamps will be left alone. The
  7623. ID property of the original subtree is removed.
  7624. In each clone, all the CLOCK entries will be removed. This
  7625. prevents Org from considering that the clocked times overlap.
  7626. If the original subtree did contain time stamps with a repeater,
  7627. the following will happen:
  7628. - the repeater will be removed in each clone
  7629. - an additional clone will be produced, with the current, unshifted
  7630. date(s) in the entry.
  7631. - the original entry will be placed *after* all the clones, with
  7632. repeater intact.
  7633. - the start days in the repeater in the original entry will be shifted
  7634. to past the last clone.
  7635. In this way you can spell out a number of instances of a repeating task,
  7636. and still retain the repeater to cover future instances of the task.
  7637. As described above, N+1 clones are produced when the original
  7638. subtree has a repeater. Setting N to 0, then, can be used to
  7639. remove the repeater from a subtree and create a shifted clone
  7640. with the original repeater."
  7641. (interactive "nNumber of clones to produce: ")
  7642. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7643. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7644. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7645. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7646. (shift
  7647. (or shift
  7648. (if (and (not (equal current-prefix-arg '(4)))
  7649. (save-excursion
  7650. (goto-char beg)
  7651. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7652. (read-from-minibuffer
  7653. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7654. ""))) ;No time shift
  7655. (doshift
  7656. (and (org-string-nw-p shift)
  7657. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7658. shift)
  7659. (user-error "Invalid shift specification %s" shift)))))
  7660. (goto-char end-of-tree)
  7661. (unless (bolp) (insert "\n"))
  7662. (let* ((end (point))
  7663. (template (buffer-substring beg end))
  7664. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7665. (shift-what (pcase (and doshift (match-string 2 shift))
  7666. (`nil nil)
  7667. ("d" 'day)
  7668. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7669. ("m" 'month)
  7670. ("y" 'year)
  7671. (_ (error "Unsupported time unit"))))
  7672. (nmin 1)
  7673. (nmax n)
  7674. (n-no-remove -1)
  7675. (idprop (org-entry-get nil "ID")))
  7676. (when (and doshift
  7677. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7678. template))
  7679. (delete-region beg end)
  7680. (setq end beg)
  7681. (setq nmin 0)
  7682. (setq nmax (1+ nmax))
  7683. (setq n-no-remove nmax))
  7684. (goto-char end)
  7685. (cl-loop for n from nmin to nmax do
  7686. (insert
  7687. ;; Prepare clone.
  7688. (with-temp-buffer
  7689. (insert template)
  7690. (org-mode)
  7691. (goto-char (point-min))
  7692. (org-show-subtree)
  7693. (and idprop (if org-clone-delete-id
  7694. (org-entry-delete nil "ID")
  7695. (org-id-get-create t)))
  7696. (unless (= n 0)
  7697. (while (re-search-forward org-clock-line-re nil t)
  7698. (delete-region (line-beginning-position)
  7699. (line-beginning-position 2)))
  7700. (goto-char (point-min))
  7701. (while (re-search-forward org-drawer-regexp nil t)
  7702. (org-remove-empty-drawer-at (point))))
  7703. (goto-char (point-min))
  7704. (when doshift
  7705. (while (re-search-forward org-ts-regexp-both nil t)
  7706. (org-timestamp-change (* n shift-n) shift-what))
  7707. (unless (= n n-no-remove)
  7708. (goto-char (point-min))
  7709. (while (re-search-forward org-ts-regexp nil t)
  7710. (save-excursion
  7711. (goto-char (match-beginning 0))
  7712. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7713. (delete-region (match-beginning 1) (match-end 1)))))))
  7714. (buffer-string)))))
  7715. (goto-char beg)))
  7716. ;;; Outline Sorting
  7717. (defun org-sort (&optional with-case)
  7718. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7719. Optional argument WITH-CASE means sort case-sensitively."
  7720. (interactive "P")
  7721. (org-call-with-arg
  7722. (cond ((org-at-table-p) #'org-table-sort-lines)
  7723. ((org-at-item-p) #'org-sort-list)
  7724. (t #'org-sort-entries))
  7725. with-case))
  7726. (defun org-sort-remove-invisible (s)
  7727. "Remove invisible part of links and emphasis markers from string S."
  7728. (remove-text-properties 0 (length s) org-rm-props s)
  7729. (replace-regexp-in-string
  7730. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7731. (replace-regexp-in-string
  7732. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7733. (org-link-display-format s)
  7734. t t) t t))
  7735. (defvar org-priority-regexp) ; defined later in the file
  7736. (defvar org-after-sorting-entries-or-items-hook nil
  7737. "Hook that is run after a bunch of entries or items have been sorted.
  7738. When children are sorted, the cursor is in the parent line when this
  7739. hook gets called. When a region or a plain list is sorted, the cursor
  7740. will be in the first entry of the sorted region/list.")
  7741. (defun org-sort-entries
  7742. (&optional with-case sorting-type getkey-func compare-func property
  7743. interactive?)
  7744. "Sort entries on a certain level of an outline tree.
  7745. If there is an active region, the entries in the region are sorted.
  7746. Else, if the cursor is before the first entry, sort the top-level items.
  7747. Else, the children of the entry at point are sorted.
  7748. Sorting can be alphabetically, numerically, by date/time as given by
  7749. a time stamp, by a property, by priority order, or by a custom function.
  7750. The command prompts for the sorting type unless it has been given to the
  7751. function through the SORTING-TYPE argument, which needs to be a character,
  7752. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7753. the precise meaning of each character:
  7754. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7755. c By creation time, which is assumed to be the first inactive time stamp
  7756. at the beginning of a line.
  7757. d By deadline date/time.
  7758. k By clocking time.
  7759. n Numerically, by converting the beginning of the entry/item to a number.
  7760. o By order of TODO keywords.
  7761. p By priority according to the cookie.
  7762. r By the value of a property.
  7763. s By scheduled date/time.
  7764. t By date/time, either the first active time stamp in the entry, or, if
  7765. none exist, by the first inactive one.
  7766. Capital letters will reverse the sort order.
  7767. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7768. called with point at the beginning of the record. It must return a
  7769. value that is compatible with COMPARE-FUNC, the function used to
  7770. compare entries.
  7771. Comparing entries ignores case by default. However, with an optional argument
  7772. WITH-CASE, the sorting considers case as well.
  7773. Sorting is done against the visible part of the headlines, it ignores hidden
  7774. links.
  7775. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7776. A non-nil value for INTERACTIVE? is used to signal that this
  7777. function is being called interactively."
  7778. (interactive (list current-prefix-arg nil nil nil nil t))
  7779. (let ((case-func (if with-case 'identity 'downcase))
  7780. start beg end stars re re2
  7781. txt what tmp)
  7782. ;; Find beginning and end of region to sort
  7783. (cond
  7784. ((org-region-active-p)
  7785. ;; we will sort the region
  7786. (setq end (region-end)
  7787. what "region")
  7788. (goto-char (region-beginning))
  7789. (unless (org-at-heading-p) (outline-next-heading))
  7790. (setq start (point)))
  7791. ((or (org-at-heading-p)
  7792. (ignore-errors (progn (org-back-to-heading) t)))
  7793. ;; we will sort the children of the current headline
  7794. (org-back-to-heading)
  7795. (setq start (point)
  7796. end (progn (org-end-of-subtree t t)
  7797. (or (bolp) (insert "\n"))
  7798. (when (>= (org-back-over-empty-lines) 1)
  7799. (forward-line 1))
  7800. (point))
  7801. what "children")
  7802. (goto-char start)
  7803. (outline-show-subtree)
  7804. (outline-next-heading))
  7805. (t
  7806. ;; we will sort the top-level entries in this file
  7807. (goto-char (point-min))
  7808. (or (org-at-heading-p) (outline-next-heading))
  7809. (setq start (point))
  7810. (goto-char (point-max))
  7811. (beginning-of-line 1)
  7812. (when (looking-at ".*?\\S-")
  7813. ;; File ends in a non-white line
  7814. (end-of-line 1)
  7815. (insert "\n"))
  7816. (setq end (point-max))
  7817. (setq what "top-level")
  7818. (goto-char start)
  7819. (org-show-all '(headings blocks))))
  7820. (setq beg (point))
  7821. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7822. (looking-at "\\(\\*+\\)")
  7823. (setq stars (match-string 1)
  7824. re (concat "^" (regexp-quote stars) " +")
  7825. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7826. txt (buffer-substring beg end))
  7827. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7828. (when (and (not (equal stars "*")) (string-match re2 txt))
  7829. (user-error "Region to sort contains a level above the first entry"))
  7830. (unless sorting-type
  7831. (message
  7832. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7833. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7834. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7835. what)
  7836. (setq sorting-type (read-char-exclusive)))
  7837. (unless getkey-func
  7838. (and (= (downcase sorting-type) ?f)
  7839. (setq getkey-func
  7840. (or (and interactive?
  7841. (org-read-function
  7842. "Function for extracting keys: "))
  7843. (error "Missing key extractor")))))
  7844. (and (= (downcase sorting-type) ?r)
  7845. (not property)
  7846. (setq property
  7847. (completing-read "Property: "
  7848. (mapcar #'list (org-buffer-property-keys t))
  7849. nil t)))
  7850. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7851. (message "Sorting entries...")
  7852. (save-restriction
  7853. (narrow-to-region start end)
  7854. (let ((restore-clock?
  7855. ;; The clock marker is lost when using `sort-subr'; mark
  7856. ;; the clock with temporary `:org-clock-marker-backup'
  7857. ;; text property.
  7858. (when (and (eq (org-clock-is-active) (current-buffer))
  7859. (<= start (marker-position org-clock-marker))
  7860. (>= end (marker-position org-clock-marker)))
  7861. (with-silent-modifications
  7862. (put-text-property (1- org-clock-marker) org-clock-marker
  7863. :org-clock-marker-backup t))
  7864. t))
  7865. (dcst (downcase sorting-type))
  7866. (case-fold-search nil)
  7867. (now (current-time)))
  7868. (org-preserve-local-variables
  7869. (sort-subr
  7870. (/= dcst sorting-type)
  7871. ;; This function moves to the beginning character of the
  7872. ;; "record" to be sorted.
  7873. (lambda nil
  7874. (if (re-search-forward re nil t)
  7875. (goto-char (match-beginning 0))
  7876. (goto-char (point-max))))
  7877. ;; This function moves to the last character of the "record" being
  7878. ;; sorted.
  7879. (lambda nil
  7880. (save-match-data
  7881. (condition-case nil
  7882. (outline-forward-same-level 1)
  7883. (error
  7884. (goto-char (point-max))))))
  7885. ;; This function returns the value that gets sorted against.
  7886. (lambda ()
  7887. (cond
  7888. ((= dcst ?n)
  7889. (string-to-number
  7890. (org-sort-remove-invisible (org-get-heading t t t t))))
  7891. ((= dcst ?a)
  7892. (funcall case-func
  7893. (org-sort-remove-invisible (org-get-heading t t t t))))
  7894. ((= dcst ?k)
  7895. (or (get-text-property (point) :org-clock-minutes) 0))
  7896. ((= dcst ?t)
  7897. (let ((end (save-excursion (outline-next-heading) (point))))
  7898. (if (or (re-search-forward org-ts-regexp end t)
  7899. (re-search-forward org-ts-regexp-both end t))
  7900. (org-time-string-to-seconds (match-string 0))
  7901. (float-time now))))
  7902. ((= dcst ?c)
  7903. (let ((end (save-excursion (outline-next-heading) (point))))
  7904. (if (re-search-forward
  7905. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7906. end t)
  7907. (org-time-string-to-seconds (match-string 0))
  7908. (float-time now))))
  7909. ((= dcst ?s)
  7910. (let ((end (save-excursion (outline-next-heading) (point))))
  7911. (if (re-search-forward org-scheduled-time-regexp end t)
  7912. (org-time-string-to-seconds (match-string 1))
  7913. (float-time now))))
  7914. ((= dcst ?d)
  7915. (let ((end (save-excursion (outline-next-heading) (point))))
  7916. (if (re-search-forward org-deadline-time-regexp end t)
  7917. (org-time-string-to-seconds (match-string 1))
  7918. (float-time now))))
  7919. ((= dcst ?p)
  7920. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7921. (string-to-char (match-string 2))
  7922. org-default-priority))
  7923. ((= dcst ?r)
  7924. (or (org-entry-get nil property) ""))
  7925. ((= dcst ?o)
  7926. (when (looking-at org-complex-heading-regexp)
  7927. (let* ((m (match-string 2))
  7928. (s (if (member m org-done-keywords) '- '+)))
  7929. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7930. ((= dcst ?f)
  7931. (if getkey-func
  7932. (progn
  7933. (setq tmp (funcall getkey-func))
  7934. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7935. tmp)
  7936. (error "Invalid key function `%s'" getkey-func)))
  7937. (t (error "Invalid sorting type `%c'" sorting-type))))
  7938. nil
  7939. (cond
  7940. ((= dcst ?a) 'org-string-collate-lessp)
  7941. ((= dcst ?f)
  7942. (or compare-func
  7943. (and interactive?
  7944. (org-read-function
  7945. (concat "Function for comparing keys "
  7946. "(empty for default `sort-subr' predicate): ")
  7947. 'allow-empty))))
  7948. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7949. (when restore-clock?
  7950. (move-marker org-clock-marker
  7951. (1+ (next-single-property-change
  7952. start :org-clock-marker-backup)))
  7953. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7954. '(:org-clock-marker-backup t)))))
  7955. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7956. (message "Sorting entries...done")))
  7957. (defun org-contextualize-keys (alist contexts)
  7958. "Return valid elements in ALIST depending on CONTEXTS.
  7959. `org-agenda-custom-commands' or `org-capture-templates' are the
  7960. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7961. or `org-capture-templates-contexts' are the associated contexts
  7962. definitions."
  7963. (let ((contexts
  7964. ;; normalize contexts
  7965. (mapcar
  7966. (lambda(c) (cond ((listp (cadr c))
  7967. (list (car c) (car c) (nth 1 c)))
  7968. ((string= "" (cadr c))
  7969. (list (car c) (car c) (nth 2 c)))
  7970. (t c)))
  7971. contexts))
  7972. (a alist) r s)
  7973. ;; loop over all commands or templates
  7974. (dolist (c a)
  7975. (let (vrules repl)
  7976. (cond
  7977. ((not (assoc (car c) contexts))
  7978. (push c r))
  7979. ((and (assoc (car c) contexts)
  7980. (setq vrules (org-contextualize-validate-key
  7981. (car c) contexts)))
  7982. (mapc (lambda (vr)
  7983. (unless (equal (car vr) (cadr vr))
  7984. (setq repl vr)))
  7985. vrules)
  7986. (if (not repl) (push c r)
  7987. (push (cadr repl) s)
  7988. (push
  7989. (cons (car c)
  7990. (cdr (or (assoc (cadr repl) alist)
  7991. (error "Undefined key `%s' as contextual replacement for `%s'"
  7992. (cadr repl) (car c)))))
  7993. r))))))
  7994. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7995. (delq
  7996. nil
  7997. (delete-dups
  7998. (mapcar (lambda (x)
  7999. (let ((tpl (car x)))
  8000. (unless (delq
  8001. nil
  8002. (mapcar (lambda (y)
  8003. (equal y tpl))
  8004. s))
  8005. x)))
  8006. (reverse r))))))
  8007. (defun org-contextualize-validate-key (key contexts)
  8008. "Check CONTEXTS for agenda or capture KEY."
  8009. (let (res)
  8010. (dolist (r contexts)
  8011. (dolist (rr (car (last r)))
  8012. (when
  8013. (and (equal key (car r))
  8014. (if (functionp rr) (funcall rr)
  8015. (or (and (eq (car rr) 'in-file)
  8016. (buffer-file-name)
  8017. (string-match (cdr rr) (buffer-file-name)))
  8018. (and (eq (car rr) 'in-mode)
  8019. (string-match (cdr rr) (symbol-name major-mode)))
  8020. (and (eq (car rr) 'in-buffer)
  8021. (string-match (cdr rr) (buffer-name)))
  8022. (when (and (eq (car rr) 'not-in-file)
  8023. (buffer-file-name))
  8024. (not (string-match (cdr rr) (buffer-file-name))))
  8025. (when (eq (car rr) 'not-in-mode)
  8026. (not (string-match (cdr rr) (symbol-name major-mode))))
  8027. (when (eq (car rr) 'not-in-buffer)
  8028. (not (string-match (cdr rr) (buffer-name)))))))
  8029. (push r res))))
  8030. (delete-dups (delq nil res))))
  8031. ;; Defined to provide a value for defcustom, since there is no
  8032. ;; string-collate-greaterp in Emacs.
  8033. (defun org-string-collate-greaterp (s1 s2)
  8034. "Return non-nil if S1 is greater than S2 in collation order."
  8035. (not (org-string-collate-lessp s1 s2)))
  8036. ;;;###autoload
  8037. (defun org-run-like-in-org-mode (cmd)
  8038. "Run a command, pretending that the current buffer is in Org mode.
  8039. This will temporarily bind local variables that are typically bound in
  8040. Org mode to the values they have in Org mode, and then interactively
  8041. call CMD."
  8042. (org-load-modules-maybe)
  8043. (let (binds)
  8044. (dolist (var (org-get-local-variables))
  8045. (when (or (not (boundp (car var)))
  8046. (eq (symbol-value (car var))
  8047. (default-value (car var))))
  8048. (push (list (car var) `(quote ,(cadr var))) binds)))
  8049. (eval `(let ,binds
  8050. (call-interactively (quote ,cmd))))))
  8051. (defun org-get-category (&optional pos force-refresh)
  8052. "Get the category applying to position POS."
  8053. (save-match-data
  8054. (when force-refresh (org-refresh-category-properties))
  8055. (let ((pos (or pos (point))))
  8056. (or (get-text-property pos 'org-category)
  8057. (progn (org-refresh-category-properties)
  8058. (get-text-property pos 'org-category))))))
  8059. ;;; Refresh properties
  8060. (defun org-refresh-properties (dprop tprop)
  8061. "Refresh buffer text properties.
  8062. DPROP is the drawer property and TPROP is either the
  8063. corresponding text property to set, or an alist with each element
  8064. being a text property (as a symbol) and a function to apply to
  8065. the value of the drawer property."
  8066. (let* ((case-fold-search t)
  8067. (inhibit-read-only t)
  8068. (inherit? (org-property-inherit-p dprop))
  8069. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8070. (global (and inherit? (org--property-global-value dprop nil))))
  8071. (with-silent-modifications
  8072. (org-with-point-at 1
  8073. ;; Set global values (e.g., values defined through
  8074. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8075. (when global (put-text-property (point-min) (point-max) tprop global))
  8076. ;; Set local values.
  8077. (while (re-search-forward property-re nil t)
  8078. (when (org-at-property-p)
  8079. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8080. (outline-next-heading))))))
  8081. (defun org-refresh-property (tprop p &optional inherit)
  8082. "Refresh the buffer text property TPROP from the drawer property P.
  8083. The refresh happens only for the current headline, or the whole
  8084. sub-tree if optional argument INHERIT is non-nil."
  8085. (unless (org-before-first-heading-p)
  8086. (save-excursion
  8087. (org-back-to-heading t)
  8088. (let ((start (point))
  8089. (end (save-excursion
  8090. (if inherit (org-end-of-subtree t t)
  8091. (or (outline-next-heading) (point-max))))))
  8092. (if (symbolp tprop)
  8093. ;; TPROP is a text property symbol.
  8094. (put-text-property start end tprop p)
  8095. ;; TPROP is an alist with (property . function) elements.
  8096. (pcase-dolist (`(,prop . ,f) tprop)
  8097. (put-text-property start end prop (funcall f p))))))))
  8098. (defun org-refresh-category-properties ()
  8099. "Refresh category text properties in the buffer."
  8100. (let ((case-fold-search t)
  8101. (inhibit-read-only t)
  8102. (default-category
  8103. (cond ((null org-category)
  8104. (if buffer-file-name
  8105. (file-name-sans-extension
  8106. (file-name-nondirectory buffer-file-name))
  8107. "???"))
  8108. ((symbolp org-category) (symbol-name org-category))
  8109. (t org-category))))
  8110. (with-silent-modifications
  8111. (org-with-wide-buffer
  8112. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8113. ;; This is the default category for the buffer. If none is
  8114. ;; found, fall-back to `org-category' or buffer file name.
  8115. (put-text-property
  8116. (point-min) (point-max)
  8117. 'org-category
  8118. (catch 'buffer-category
  8119. (goto-char (point-max))
  8120. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8121. (let ((element (org-element-at-point)))
  8122. (when (eq (org-element-type element) 'keyword)
  8123. (throw 'buffer-category
  8124. (org-element-property :value element)))))
  8125. default-category))
  8126. ;; Set sub-tree specific categories.
  8127. (goto-char (point-min))
  8128. (let ((regexp (org-re-property "CATEGORY")))
  8129. (while (re-search-forward regexp nil t)
  8130. (let ((value (match-string-no-properties 3)))
  8131. (when (org-at-property-p)
  8132. (put-text-property
  8133. (save-excursion (org-back-to-heading t) (point))
  8134. (save-excursion (org-end-of-subtree t t) (point))
  8135. 'org-category
  8136. value)))))))))
  8137. (defun org-refresh-stats-properties ()
  8138. "Refresh stats text properties in the buffer."
  8139. (with-silent-modifications
  8140. (org-with-point-at 1
  8141. (let ((regexp (concat org-outline-regexp-bol
  8142. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8143. (while (re-search-forward regexp nil t)
  8144. (let* ((numerator (string-to-number (match-string 1)))
  8145. (denominator (and (match-end 2)
  8146. (string-to-number (match-string 2))))
  8147. (stats (cond ((not denominator) numerator) ;percent
  8148. ((= denominator 0) 0)
  8149. (t (/ (* numerator 100) denominator)))))
  8150. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8151. 'org-stats stats)))))))
  8152. (defun org-refresh-effort-properties ()
  8153. "Refresh effort properties"
  8154. (org-refresh-properties
  8155. org-effort-property
  8156. '((effort . identity)
  8157. (effort-minutes . org-duration-to-minutes))))
  8158. ;;;; Link Stuff
  8159. ;;; Link abbreviations
  8160. (defun org-link-expand-abbrev (link)
  8161. "Apply replacements as defined in `org-link-abbrev-alist'."
  8162. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8163. (let* ((key (match-string 1 link))
  8164. (as (or (assoc key org-link-abbrev-alist-local)
  8165. (assoc key org-link-abbrev-alist)))
  8166. (tag (and (match-end 2) (match-string 3 link)))
  8167. rpl)
  8168. (if (not as)
  8169. link
  8170. (setq rpl (cdr as))
  8171. (cond
  8172. ((symbolp rpl) (funcall rpl tag))
  8173. ((string-match "%(\\([^)]+\\))" rpl)
  8174. (replace-match
  8175. (save-match-data
  8176. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8177. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8178. ((string-match "%h" rpl)
  8179. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8180. (t (concat rpl tag)))))
  8181. link))
  8182. ;;; Storing and inserting links
  8183. (defvar org-insert-link-history nil
  8184. "Minibuffer history for links inserted with `org-insert-link'.")
  8185. (defvar org-stored-links nil
  8186. "Contains the links stored with `org-store-link'.")
  8187. (defvar org-store-link-plist nil
  8188. "Plist with info about the most recently link created with `org-store-link'.")
  8189. (defun org-store-link-functions ()
  8190. "Return a list of functions that are called to create and store a link.
  8191. The functions are defined in the `:store' property of
  8192. `org-link-parameters'.
  8193. Each function is called in turn until one returns a non-nil
  8194. value. Each function should check if it is responsible for
  8195. creating this link (for example by looking at the major mode).
  8196. If not, it must exit and return nil. If yes, it should return
  8197. a non-nil value after calling `org-store-link-props' with a list
  8198. of properties and values. Special properties are:
  8199. :type The link prefix, like \"http\". This must be given.
  8200. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8201. This is obligatory as well.
  8202. :description Optional default description for the second pair
  8203. of brackets in an Org mode link. The user can still change
  8204. this when inserting this link into an Org mode buffer.
  8205. In addition to these, any additional properties can be specified
  8206. and then used in capture templates."
  8207. (cl-loop for link in org-link-parameters
  8208. with store-func
  8209. do (setq store-func (org-link-get-parameter (car link) :store))
  8210. if store-func
  8211. collect store-func))
  8212. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8213. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8214. ;;;###autoload
  8215. (defun org-store-link (arg &optional interactive?)
  8216. "Store a link to the current location.
  8217. \\<org-mode-map>
  8218. This link is added to `org-stored-links' and can later be inserted
  8219. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8220. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8221. A single
  8222. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8223. `org-gnus-prefer-web-links' for links to Usenet articles.
  8224. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8225. skipping storing functions that are not
  8226. part of Org core.
  8227. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8228. prefix ARG forces storing a link for each line in the
  8229. active region.
  8230. Assume the function is called interactively if INTERACTIVE? is
  8231. non-nil."
  8232. (interactive "P\np")
  8233. (org-load-modules-maybe)
  8234. (if (and (equal arg '(64)) (org-region-active-p))
  8235. (save-excursion
  8236. (let ((end (region-end)))
  8237. (goto-char (region-beginning))
  8238. (set-mark (point))
  8239. (while (< (point-at-eol) end)
  8240. (move-end-of-line 1) (activate-mark)
  8241. (let (current-prefix-arg)
  8242. (call-interactively 'org-store-link))
  8243. (move-beginning-of-line 2)
  8244. (set-mark (point)))))
  8245. (setq org-store-link-plist nil)
  8246. (let (link cpltxt desc description search txt custom-id agenda-link)
  8247. (cond
  8248. ;; Store a link using an external link type, if any function is
  8249. ;; available. If more than one can generate a link from current
  8250. ;; location, ask which one to use.
  8251. ((and (not (equal arg '(16)))
  8252. (let ((results-alist nil))
  8253. (dolist (f (org-store-link-functions))
  8254. (when (funcall f)
  8255. ;; XXX: return value is not link's plist, so we
  8256. ;; store the new value before it is modified. It
  8257. ;; would be cleaner to ask store link functions to
  8258. ;; return the plist instead.
  8259. (push (cons f (copy-sequence org-store-link-plist))
  8260. results-alist)))
  8261. (pcase results-alist
  8262. (`nil nil)
  8263. (`((,_ . ,_)) t) ;single choice: nothing to do
  8264. (`((,name . ,_) . ,_)
  8265. ;; Reinstate link plist associated to the chosen
  8266. ;; function.
  8267. (apply #'org-store-link-props
  8268. (cdr (assoc-string
  8269. (completing-read
  8270. "Which function for creating the link? "
  8271. (mapcar #'car results-alist)
  8272. nil t (symbol-name name))
  8273. results-alist)))
  8274. t))))
  8275. (setq link (plist-get org-store-link-plist :link))
  8276. (setq desc (or (plist-get org-store-link-plist :description)
  8277. link)))
  8278. ;; Store a link from a remote editing buffer.
  8279. ((org-src-edit-buffer-p)
  8280. (let ((coderef-format (org-src-coderef-format))
  8281. (format-link
  8282. (lambda (label)
  8283. (if org-src-source-file-name
  8284. (format "file:%s::(%s)" org-src-source-file-name label)
  8285. (format "(%s)" label)))))
  8286. (cond
  8287. ;; Code references do not exist in this type of buffer.
  8288. ;; Pretend we're linking from the source buffer directly.
  8289. ((not (memq (org-src-source-type) '(example-block src-block)))
  8290. (with-current-buffer (org-src-source-buffer)
  8291. (org-store-link arg interactive?))
  8292. (setq link nil))
  8293. ;; A code reference exists. Use it.
  8294. ((save-excursion
  8295. (beginning-of-line)
  8296. (re-search-forward (org-src-coderef-regexp coderef-format)
  8297. (line-end-position)
  8298. t))
  8299. (setq link (funcall format-link (match-string-no-properties 3))))
  8300. ;; No code reference. Create a new one then store the link
  8301. ;; to it, but only in the function is called interactively.
  8302. (interactive?
  8303. (end-of-line)
  8304. (let* ((label (read-string "Code line label: "))
  8305. (reference (format coderef-format label))
  8306. (gc (- 79 (length reference))))
  8307. (if (< (current-column) gc)
  8308. (org-move-to-column gc t)
  8309. (insert " "))
  8310. (insert reference)
  8311. (setq link (funcall format-link label))))
  8312. ;; No code reference, and non-interactive call. Don't know
  8313. ;; what to do. Give up.
  8314. (t (setq link nil)))))
  8315. ;; We are in the agenda, link to referenced location
  8316. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8317. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8318. (get-text-property (point) 'org-marker))))
  8319. (when m
  8320. (org-with-point-at m
  8321. (setq agenda-link (org-store-link nil interactive?))))))
  8322. ((eq major-mode 'calendar-mode)
  8323. (let ((cd (calendar-cursor-to-date)))
  8324. (setq link
  8325. (format-time-string
  8326. (car org-time-stamp-formats)
  8327. (apply 'encode-time
  8328. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8329. nil nil nil))))
  8330. (org-store-link-props :type "calendar" :date cd)))
  8331. ((eq major-mode 'help-mode)
  8332. (setq link (concat "help:" (save-excursion
  8333. (goto-char (point-min))
  8334. (looking-at "^[^ ]+")
  8335. (match-string 0))))
  8336. (org-store-link-props :type "help"))
  8337. ((eq major-mode 'w3-mode)
  8338. (setq cpltxt (if (and (buffer-name)
  8339. (not (string-match "Untitled" (buffer-name))))
  8340. (buffer-name)
  8341. (url-view-url t))
  8342. link (url-view-url t))
  8343. (org-store-link-props :type "w3" :url (url-view-url t)))
  8344. ((eq major-mode 'image-mode)
  8345. (setq cpltxt (concat "file:"
  8346. (abbreviate-file-name buffer-file-name))
  8347. link cpltxt)
  8348. (org-store-link-props :type "image" :file buffer-file-name))
  8349. ;; In dired, store a link to the file of the current line
  8350. ((derived-mode-p 'dired-mode)
  8351. (let ((file (dired-get-filename nil t)))
  8352. (setq file (if file
  8353. (abbreviate-file-name
  8354. (expand-file-name (dired-get-filename nil t)))
  8355. ;; otherwise, no file so use current directory.
  8356. default-directory))
  8357. (setq cpltxt (concat "file:" file)
  8358. link cpltxt)))
  8359. ((setq search (run-hook-with-args-until-success
  8360. 'org-create-file-search-functions))
  8361. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8362. "::" search))
  8363. (setq cpltxt (or description link)))
  8364. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8365. (org-with-limited-levels
  8366. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8367. (cond
  8368. ;; Store a link using the target at point
  8369. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8370. (setq cpltxt
  8371. (concat "file:"
  8372. (abbreviate-file-name
  8373. (buffer-file-name (buffer-base-buffer)))
  8374. "::" (match-string 1))
  8375. link cpltxt))
  8376. ((and (featurep 'org-id)
  8377. (or (eq org-id-link-to-org-use-id t)
  8378. (and interactive?
  8379. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8380. (and (eq org-id-link-to-org-use-id
  8381. 'create-if-interactive-and-no-custom-id)
  8382. (not custom-id))))
  8383. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8384. ;; Store a link using the ID at point
  8385. (setq link (condition-case nil
  8386. (prog1 (org-id-store-link)
  8387. (setq desc (or (plist-get org-store-link-plist
  8388. :description)
  8389. "")))
  8390. (error
  8391. ;; Probably before first headline, link only to file
  8392. (concat "file:"
  8393. (abbreviate-file-name
  8394. (buffer-file-name (buffer-base-buffer))))))))
  8395. (t
  8396. ;; Just link to current headline
  8397. (setq cpltxt (concat "file:"
  8398. (abbreviate-file-name
  8399. (buffer-file-name (buffer-base-buffer)))))
  8400. ;; Add a context search string
  8401. (when (org-xor org-context-in-file-links
  8402. (equal arg '(4)))
  8403. (let* ((element (org-element-at-point))
  8404. (name (org-element-property :name element)))
  8405. (setq txt (cond
  8406. ((org-at-heading-p) nil)
  8407. (name)
  8408. ((org-region-active-p)
  8409. (buffer-substring (region-beginning) (region-end)))))
  8410. (when (or (null txt) (string-match "\\S-" txt))
  8411. (setq cpltxt
  8412. (concat cpltxt "::"
  8413. (condition-case nil
  8414. (org-make-org-heading-search-string txt)
  8415. (error "")))
  8416. desc (or name
  8417. (nth 4 (ignore-errors (org-heading-components)))
  8418. "NONE")))))
  8419. (when (string-match "::\\'" cpltxt)
  8420. (setq cpltxt (substring cpltxt 0 -2)))
  8421. (setq link cpltxt)))))
  8422. ((buffer-file-name (buffer-base-buffer))
  8423. ;; Just link to this file here.
  8424. (setq cpltxt (concat "file:"
  8425. (abbreviate-file-name
  8426. (buffer-file-name (buffer-base-buffer)))))
  8427. ;; Add a context string.
  8428. (when (org-xor org-context-in-file-links
  8429. (equal arg '(4)))
  8430. (setq txt (if (org-region-active-p)
  8431. (buffer-substring (region-beginning) (region-end))
  8432. (buffer-substring (point-at-bol) (point-at-eol))))
  8433. ;; Only use search option if there is some text.
  8434. (when (string-match "\\S-" txt)
  8435. (setq cpltxt
  8436. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8437. desc "NONE")))
  8438. (setq link cpltxt))
  8439. (interactive?
  8440. (user-error "No method for storing a link from this buffer"))
  8441. (t (setq link nil)))
  8442. ;; We're done setting link and desc, clean up
  8443. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8444. (setq link (or link cpltxt)
  8445. desc (or desc cpltxt))
  8446. (cond ((not desc))
  8447. ((equal desc "NONE") (setq desc nil))
  8448. (t (setq desc
  8449. (replace-regexp-in-string
  8450. org-bracket-link-analytic-regexp
  8451. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8452. desc))))
  8453. ;; Return the link
  8454. (if (not (and interactive? link))
  8455. (or agenda-link (and link (org-make-link-string link desc)))
  8456. (push (list link desc) org-stored-links)
  8457. (message "Stored: %s" (or desc link))
  8458. (when custom-id
  8459. (setq link (concat "file:" (abbreviate-file-name
  8460. (buffer-file-name)) "::#" custom-id))
  8461. (push (list link desc) org-stored-links))
  8462. (car org-stored-links)))))
  8463. (defun org-store-link-props (&rest plist)
  8464. "Store link properties.
  8465. The properties are pre-processed by extracting names, addresses
  8466. and dates."
  8467. (let ((x (plist-get plist :from)))
  8468. (when x
  8469. (let ((adr (mail-extract-address-components x)))
  8470. (setq plist (plist-put plist :fromname (car adr)))
  8471. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8472. (let ((x (plist-get plist :to)))
  8473. (when x
  8474. (let ((adr (mail-extract-address-components x)))
  8475. (setq plist (plist-put plist :toname (car adr)))
  8476. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8477. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8478. (when x
  8479. (setq plist (plist-put plist :date-timestamp
  8480. (format-time-string
  8481. (org-time-stamp-format t) x)))
  8482. (setq plist (plist-put plist :date-timestamp-inactive
  8483. (format-time-string
  8484. (org-time-stamp-format t t) x)))))
  8485. (let ((from (plist-get plist :from))
  8486. (to (plist-get plist :to)))
  8487. (when (and from to org-from-is-user-regexp)
  8488. (setq plist
  8489. (plist-put plist :fromto
  8490. (if (string-match org-from-is-user-regexp from)
  8491. (concat "to %t")
  8492. (concat "from %f"))))))
  8493. (setq org-store-link-plist plist))
  8494. (defun org-add-link-props (&rest plist)
  8495. "Add these properties to the link property list."
  8496. (let (key value)
  8497. (while plist
  8498. (setq key (pop plist) value (pop plist))
  8499. (setq org-store-link-plist
  8500. (plist-put org-store-link-plist key value)))))
  8501. (defun org-email-link-description (&optional fmt)
  8502. "Return the description part of an email link.
  8503. This takes information from `org-store-link-plist' and formats it
  8504. according to FMT (default from `org-email-link-description-format')."
  8505. (setq fmt (or fmt org-email-link-description-format))
  8506. (let* ((p org-store-link-plist)
  8507. (to (plist-get p :toaddress))
  8508. (from (plist-get p :fromaddress))
  8509. (table
  8510. (list
  8511. (cons "%c" (plist-get p :fromto))
  8512. (cons "%F" (plist-get p :from))
  8513. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8514. (cons "%T" (plist-get p :to))
  8515. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8516. (cons "%s" (plist-get p :subject))
  8517. (cons "%d" (plist-get p :date))
  8518. (cons "%m" (plist-get p :message-id)))))
  8519. (when (string-match "%c" fmt)
  8520. ;; Check if the user wrote this message
  8521. (if (and org-from-is-user-regexp from to
  8522. (save-match-data (string-match org-from-is-user-regexp from)))
  8523. (setq fmt (replace-match "to %t" t t fmt))
  8524. (setq fmt (replace-match "from %f" t t fmt))))
  8525. (org-replace-escapes fmt table)))
  8526. (defun org-make-org-heading-search-string (&optional string)
  8527. "Make search string for the current headline or STRING."
  8528. (let ((s (or string
  8529. (and (derived-mode-p 'org-mode)
  8530. (save-excursion
  8531. (org-back-to-heading t)
  8532. (org-element-property :raw-value (org-element-at-point))))))
  8533. (lines org-context-in-file-links))
  8534. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8535. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8536. (when (and string (integerp lines) (> lines 0))
  8537. (let ((slines (org-split-string s "\n")))
  8538. (when (< lines (length slines))
  8539. (setq s (mapconcat
  8540. 'identity
  8541. (reverse (nthcdr (- (length slines) lines)
  8542. (reverse slines))) "\n")))))
  8543. (mapconcat #'identity (split-string s) " ")))
  8544. (defconst org-link-escape-chars
  8545. ;;%20 %5B %5D %25
  8546. '(?\s ?\[ ?\] ?%)
  8547. "List of characters that should be escaped in a link when stored to Org.
  8548. This is the list that is used for internal purposes.")
  8549. (defun org-make-link-string (link &optional description)
  8550. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8551. (unless (org-string-nw-p link) (error "Empty link"))
  8552. (let ((uri (cond ((string-match org-link-types-re link)
  8553. (concat (match-string 1 link)
  8554. (org-link-escape (substring link (match-end 1)))))
  8555. ((or (file-name-absolute-p link)
  8556. (string-match-p "\\`\\.\\.?/" link))
  8557. (org-link-escape link))
  8558. ;; For readability, do not encode space characters
  8559. ;; in fuzzy links.
  8560. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8561. (description
  8562. (and (org-string-nw-p description)
  8563. ;; Remove brackets from description, as they are fatal.
  8564. (replace-regexp-in-string
  8565. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8566. (org-trim description)))))
  8567. (format "[[%s]%s]"
  8568. uri
  8569. (if description (format "[%s]" description) ""))))
  8570. (defun org-link-escape (text &optional table merge)
  8571. "Return percent escaped representation of TEXT.
  8572. TEXT is a string with the text to escape.
  8573. Optional argument TABLE is a list with characters that should be
  8574. escaped. When nil, `org-link-escape-chars' is used.
  8575. If optional argument MERGE is set, merge TABLE into
  8576. `org-link-escape-chars'."
  8577. (let ((characters-to-encode
  8578. (cond ((null table) org-link-escape-chars)
  8579. (merge (append org-link-escape-chars table))
  8580. (t table))))
  8581. (mapconcat
  8582. (lambda (c)
  8583. (if (or (memq c characters-to-encode)
  8584. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8585. (mapconcat (lambda (e) (format "%%%.2X" e))
  8586. (or (encode-coding-char c 'utf-8)
  8587. (error "Unable to percent escape character: %c" c))
  8588. "")
  8589. (char-to-string c)))
  8590. text "")))
  8591. (defun org-link-unescape (str)
  8592. "Unhex hexified Unicode parts in string STR.
  8593. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8594. reciprocal of `org-link-escape', which see."
  8595. (if (org-string-nw-p str)
  8596. (replace-regexp-in-string
  8597. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8598. str))
  8599. (defun org-link-unescape-compound (hex)
  8600. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8601. Note: this function also decodes single byte encodings like
  8602. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8603. (save-match-data
  8604. (let* ((bytes (cdr (split-string hex "%")))
  8605. (ret "")
  8606. (eat 0)
  8607. (sum 0))
  8608. (while bytes
  8609. (let* ((val (string-to-number (pop bytes) 16))
  8610. (shift-xor
  8611. (if (= 0 eat)
  8612. (cond
  8613. ((>= val 252) (cons 6 252))
  8614. ((>= val 248) (cons 5 248))
  8615. ((>= val 240) (cons 4 240))
  8616. ((>= val 224) (cons 3 224))
  8617. ((>= val 192) (cons 2 192))
  8618. (t (cons 0 0)))
  8619. (cons 6 128))))
  8620. (when (>= val 192) (setq eat (car shift-xor)))
  8621. (setq val (logxor val (cdr shift-xor)))
  8622. (setq sum (+ (ash sum (car shift-xor)) val))
  8623. (when (> eat 0) (setq eat (- eat 1)))
  8624. (cond
  8625. ((= 0 eat) ;multi byte
  8626. (setq ret (concat ret (char-to-string sum)))
  8627. (setq sum 0))
  8628. ((not bytes) ; single byte(s)
  8629. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8630. ret)))
  8631. (defun org-link-unescape-single-byte-sequence (hex)
  8632. "Unhexify hex-encoded single byte character sequences."
  8633. (mapconcat (lambda (byte)
  8634. (char-to-string (string-to-number byte 16)))
  8635. (cdr (split-string hex "%")) ""))
  8636. (defun org-fixup-message-id-for-http (s)
  8637. "Replace special characters in a message id, so it can be used in an http query."
  8638. (when (string-match "%" s)
  8639. (setq s (mapconcat (lambda (c)
  8640. (if (eq c ?%)
  8641. "%25"
  8642. (char-to-string c)))
  8643. s "")))
  8644. (while (string-match "<" s)
  8645. (setq s (replace-match "%3C" t t s)))
  8646. (while (string-match ">" s)
  8647. (setq s (replace-match "%3E" t t s)))
  8648. (while (string-match "@" s)
  8649. (setq s (replace-match "%40" t t s)))
  8650. s)
  8651. (defun org-link-prettify (link)
  8652. "Return a human-readable representation of LINK.
  8653. The car of LINK must be a raw link.
  8654. The cdr of LINK must be either a link description or nil."
  8655. (let ((desc (or (cadr link) "<no description>")))
  8656. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8657. "<" (car link) ">")))
  8658. ;;;###autoload
  8659. (defun org-insert-link-global ()
  8660. "Insert a link like Org mode does.
  8661. This command can be called in any mode to insert a link in Org syntax."
  8662. (interactive)
  8663. (org-load-modules-maybe)
  8664. (org-run-like-in-org-mode 'org-insert-link))
  8665. (defun org-insert-all-links (arg &optional pre post)
  8666. "Insert all links in `org-stored-links'.
  8667. When a universal prefix, do not delete the links from `org-stored-links'.
  8668. When `ARG' is a number, insert the last N link(s).
  8669. `PRE' and `POST' are optional arguments to define a string to
  8670. prepend or to append."
  8671. (interactive "P")
  8672. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8673. (links (copy-sequence org-stored-links))
  8674. (pr (or pre "- "))
  8675. (po (or post "\n"))
  8676. (cnt 1) l)
  8677. (if (null org-stored-links)
  8678. (message "No link to insert")
  8679. (while (and (or (listp arg) (>= arg cnt))
  8680. (setq l (if (listp arg)
  8681. (pop links)
  8682. (pop org-stored-links))))
  8683. (setq cnt (1+ cnt))
  8684. (insert pr)
  8685. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8686. (insert po)))))
  8687. (defun org-insert-last-stored-link (arg)
  8688. "Insert the last link stored in `org-stored-links'."
  8689. (interactive "p")
  8690. (org-insert-all-links arg "" "\n"))
  8691. (defun org-link-fontify-links-to-this-file ()
  8692. "Fontify links to the current file in `org-stored-links'."
  8693. (let ((f (buffer-file-name)) a b)
  8694. (setq a (mapcar (lambda(l)
  8695. (let ((ll (car l)))
  8696. (when (and (string-match "^file:\\(.+\\)::" ll)
  8697. (equal f (expand-file-name (match-string 1 ll))))
  8698. ll)))
  8699. org-stored-links))
  8700. (when (featurep 'org-id)
  8701. (setq b (mapcar (lambda(l)
  8702. (let ((ll (car l)))
  8703. (when (and (string-match "^id:\\(.+\\)$" ll)
  8704. (equal f (expand-file-name
  8705. (or (org-id-find-id-file
  8706. (match-string 1 ll)) ""))))
  8707. ll)))
  8708. org-stored-links)))
  8709. (mapcar (lambda(l)
  8710. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8711. (delq nil (append a b)))))
  8712. (defvar org--links-history nil)
  8713. (defun org-insert-link (&optional complete-file link-location default-description)
  8714. "Insert a link. At the prompt, enter the link.
  8715. Completion can be used to insert any of the link protocol prefixes in use.
  8716. The history can be used to select a link previously stored with
  8717. `org-store-link'. When the empty string is entered (i.e. if you just
  8718. press `RET' at the prompt), the link defaults to the most recently
  8719. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8720. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8721. You will also be prompted for a description, and if one is given, it will
  8722. be displayed in the buffer instead of the link.
  8723. If there is already a link at point, this command will allow you to edit
  8724. link and description parts.
  8725. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8726. file name can be
  8727. selected using completion. The path to the file will be relative to the
  8728. current directory if the file is in the current directory or a subdirectory.
  8729. Otherwise, the link will be the absolute path as completed in the minibuffer
  8730. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8731. option `org-link-file-path-type'.
  8732. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8733. absolute path even if the file is in
  8734. the current directory or below.
  8735. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8736. prefix negates `org-keep-stored-link-after-insertion'.
  8737. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8738. the link location instead of reading one interactively.
  8739. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8740. be used as the default description. Otherwise, if
  8741. `org-make-link-description-function' is non-nil, this function
  8742. will be called with the link target, and the result will be the
  8743. default link description. When called non-interactively, don't
  8744. allow to edit the default description."
  8745. (interactive "P")
  8746. (let* ((wcf (current-window-configuration))
  8747. (origbuf (current-buffer))
  8748. (region (when (org-region-active-p)
  8749. (buffer-substring (region-beginning) (region-end))))
  8750. (remove (and region (list (region-beginning) (region-end))))
  8751. (desc region)
  8752. (link link-location)
  8753. (abbrevs org-link-abbrev-alist-local)
  8754. entry all-prefixes auto-desc)
  8755. (cond
  8756. (link-location) ; specified by arg, just use it.
  8757. ((org-in-regexp org-bracket-link-regexp 1)
  8758. ;; We do have a link at point, and we are going to edit it.
  8759. (setq remove (list (match-beginning 0) (match-end 0)))
  8760. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8761. (setq link (read-string "Link: "
  8762. (org-link-unescape
  8763. (match-string-no-properties 1)))))
  8764. ((or (org-in-regexp org-angle-link-re)
  8765. (org-in-regexp org-plain-link-re))
  8766. ;; Convert to bracket link
  8767. (setq remove (list (match-beginning 0) (match-end 0))
  8768. link (read-string "Link: "
  8769. (org-unbracket-string "<" ">" (match-string 0)))))
  8770. ((member complete-file '((4) (16)))
  8771. ;; Completing read for file names.
  8772. (setq link (org-file-complete-link complete-file)))
  8773. (t
  8774. ;; Read link, with completion for stored links.
  8775. (org-link-fontify-links-to-this-file)
  8776. (org-switch-to-buffer-other-window "*Org Links*")
  8777. (with-current-buffer "*Org Links*"
  8778. (erase-buffer)
  8779. (insert "Insert a link.
  8780. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8781. (when org-stored-links
  8782. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8783. (insert (mapconcat 'org-link-prettify
  8784. (reverse org-stored-links) "\n")))
  8785. (goto-char (point-min)))
  8786. (let ((cw (selected-window)))
  8787. (select-window (get-buffer-window "*Org Links*" 'visible))
  8788. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8789. (unless (pos-visible-in-window-p (point-max))
  8790. (org-fit-window-to-buffer))
  8791. (and (window-live-p cw) (select-window cw)))
  8792. (setq all-prefixes (append (mapcar 'car abbrevs)
  8793. (mapcar 'car org-link-abbrev-alist)
  8794. (org-link-types)))
  8795. (unwind-protect
  8796. ;; Fake a link history, containing the stored links.
  8797. (let ((org--links-history
  8798. (append (mapcar #'car org-stored-links)
  8799. org-insert-link-history)))
  8800. (setq link
  8801. (org-completing-read
  8802. "Link: "
  8803. (append
  8804. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8805. (mapcar #'car org-stored-links))
  8806. nil nil nil
  8807. 'org--links-history
  8808. (caar org-stored-links)))
  8809. (unless (org-string-nw-p link) (user-error "No link selected"))
  8810. (dolist (l org-stored-links)
  8811. (when (equal link (cadr l))
  8812. (setq link (car l))
  8813. (setq auto-desc t)))
  8814. (when (or (member link all-prefixes)
  8815. (and (equal ":" (substring link -1))
  8816. (member (substring link 0 -1) all-prefixes)
  8817. (setq link (substring link 0 -1))))
  8818. (setq link (with-current-buffer origbuf
  8819. (org-link-try-special-completion link)))))
  8820. (set-window-configuration wcf)
  8821. (kill-buffer "*Org Links*"))
  8822. (setq entry (assoc link org-stored-links))
  8823. (or entry (push link org-insert-link-history))
  8824. (setq desc (or desc (nth 1 entry)))))
  8825. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8826. (not org-keep-stored-link-after-insertion))
  8827. (setq org-stored-links (delq (assoc link org-stored-links)
  8828. org-stored-links)))
  8829. (when (and (string-match org-plain-link-re link)
  8830. (not (string-match org-ts-regexp link)))
  8831. ;; URL-like link, normalize the use of angular brackets.
  8832. (setq link (org-unbracket-string "<" ">" link)))
  8833. ;; Check if we are linking to the current file with a search
  8834. ;; option If yes, simplify the link by using only the search
  8835. ;; option.
  8836. (when (and buffer-file-name
  8837. (let ((case-fold-search nil))
  8838. (string-match "\\`file:\\(.+?\\)::" link)))
  8839. (let ((path (match-string-no-properties 1 link))
  8840. (search (substring-no-properties link (match-end 0))))
  8841. (save-match-data
  8842. (when (equal (file-truename buffer-file-name) (file-truename path))
  8843. ;; We are linking to this same file, with a search option
  8844. (setq link search)))))
  8845. ;; Check if we can/should use a relative path. If yes, simplify
  8846. ;; the link.
  8847. (let ((case-fold-search nil))
  8848. (when (string-match "\\`\\(file\\|docview\\):" link)
  8849. (let* ((type (match-string-no-properties 0 link))
  8850. (path-start (match-end 0))
  8851. (search (and (string-match "::\\(.*\\)\\'" link)
  8852. (match-string 1 link)))
  8853. (path
  8854. (if search
  8855. (substring-no-properties
  8856. link path-start (match-beginning 0))
  8857. (substring-no-properties link (match-end 0))))
  8858. (origpath path))
  8859. (cond
  8860. ((or (eq org-link-file-path-type 'absolute)
  8861. (equal complete-file '(16)))
  8862. (setq path (abbreviate-file-name (expand-file-name path))))
  8863. ((eq org-link-file-path-type 'noabbrev)
  8864. (setq path (expand-file-name path)))
  8865. ((eq org-link-file-path-type 'relative)
  8866. (setq path (file-relative-name path)))
  8867. (t
  8868. (save-match-data
  8869. (if (string-match (concat "^" (regexp-quote
  8870. (expand-file-name
  8871. (file-name-as-directory
  8872. default-directory))))
  8873. (expand-file-name path))
  8874. ;; We are linking a file with relative path name.
  8875. (setq path (substring (expand-file-name path)
  8876. (match-end 0)))
  8877. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8878. (setq link (concat type path (and search (concat "::" search))))
  8879. (when (equal desc origpath)
  8880. (setq desc path)))))
  8881. (unless auto-desc
  8882. (let ((initial-input
  8883. (cond
  8884. (default-description)
  8885. ((not org-make-link-description-function) desc)
  8886. (t (condition-case nil
  8887. (funcall org-make-link-description-function link desc)
  8888. (error
  8889. (message "Can't get link description from `%s'"
  8890. (symbol-name org-make-link-description-function))
  8891. (sit-for 2)
  8892. nil))))))
  8893. (setq desc (if (called-interactively-p 'any)
  8894. (read-string "Description: " initial-input)
  8895. initial-input))))
  8896. (unless (org-string-nw-p desc) (setq desc nil))
  8897. (when remove (apply 'delete-region remove))
  8898. (insert (org-make-link-string link desc))
  8899. ;; Redisplay so as the new link has proper invisible characters.
  8900. (sit-for 0)))
  8901. (defun org-link-try-special-completion (type)
  8902. "If there is completion support for link type TYPE, offer it."
  8903. (let ((fun (org-link-get-parameter type :complete)))
  8904. (if (functionp fun)
  8905. (funcall fun)
  8906. (read-string "Link (no completion support): " (concat type ":")))))
  8907. (defun org-file-complete-link (&optional arg)
  8908. "Create a file link using completion."
  8909. (let ((file (read-file-name "File: "))
  8910. (pwd (file-name-as-directory (expand-file-name ".")))
  8911. (pwd1 (file-name-as-directory (abbreviate-file-name
  8912. (expand-file-name ".")))))
  8913. (cond ((equal arg '(16))
  8914. (concat "file:"
  8915. (abbreviate-file-name (expand-file-name file))))
  8916. ((string-match
  8917. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8918. (concat "file:" (match-string 1 file)))
  8919. ((string-match
  8920. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8921. (expand-file-name file))
  8922. (concat "file:"
  8923. (match-string 1 (expand-file-name file))))
  8924. (t (concat "file:" file)))))
  8925. ;;; Opening/following a link
  8926. (defvar org-link-search-failed nil)
  8927. (defvar org-open-link-functions nil
  8928. "Hook for functions finding a plain text link.
  8929. These functions must take a single argument, the link content.
  8930. They will be called for links that look like [[link text][description]]
  8931. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8932. like a filename (e.g. \"./blue.png\").
  8933. These functions will be called *before* Org attempts to resolve the
  8934. link by doing text searches in the current buffer - so if you want a
  8935. link \"[[target]]\" to still find \"<<target>>\", your function should
  8936. handle this as a special case.
  8937. When the function does handle the link, it must return a non-nil value.
  8938. If it decides that it is not responsible for this link, it must return
  8939. nil to indicate that that Org can continue with other options like
  8940. exact and fuzzy text search.")
  8941. (defun org-next-link (&optional search-backward)
  8942. "Move forward to the next link.
  8943. If the link is in hidden text, expose it."
  8944. (interactive "P")
  8945. (when (and org-link-search-failed (eq this-command last-command))
  8946. (goto-char (point-min))
  8947. (message "Link search wrapped back to beginning of buffer"))
  8948. (setq org-link-search-failed nil)
  8949. (let* ((pos (point))
  8950. (ct (org-context))
  8951. (a (assq :link ct))
  8952. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8953. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8954. ((looking-at org-any-link-re)
  8955. ;; Don't stay stuck at link without an org-link face
  8956. (forward-char (if search-backward -1 1))))
  8957. (if (funcall srch-fun org-any-link-re nil t)
  8958. (progn
  8959. (goto-char (match-beginning 0))
  8960. (when (org-invisible-p) (org-show-context)))
  8961. (goto-char pos)
  8962. (setq org-link-search-failed t)
  8963. (message "No further link found"))))
  8964. (defun org-previous-link ()
  8965. "Move backward to the previous link.
  8966. If the link is in hidden text, expose it."
  8967. (interactive)
  8968. (org-next-link t))
  8969. (defun org-translate-link (s)
  8970. "Translate a link string if a translation function has been defined."
  8971. (with-temp-buffer
  8972. (insert (org-trim s))
  8973. (org-trim (org-element-interpret-data (org-element-context)))))
  8974. (defun org-translate-link-from-planner (type path)
  8975. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8976. This is still an experimental function, your mileage may vary."
  8977. (cond
  8978. ((member type '("http" "https" "news" "ftp"))
  8979. ;; standard Internet links are the same.
  8980. nil)
  8981. ((and (equal type "irc") (string-match "^//" path))
  8982. ;; Planner has two / at the beginning of an irc link, we have 1.
  8983. ;; We should have zero, actually....
  8984. (setq path (substring path 1)))
  8985. ((and (equal type "lisp") (string-match "^/" path))
  8986. ;; Planner has a slash, we do not.
  8987. (setq type "elisp" path (substring path 1)))
  8988. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8989. ;; A typical message link. Planner has the id after the final slash,
  8990. ;; we separate it with a hash mark
  8991. (setq path (concat (match-string 1 path) "#"
  8992. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8993. (cons type path))
  8994. (defun org-find-file-at-mouse (ev)
  8995. "Open file link or URL at mouse."
  8996. (interactive "e")
  8997. (mouse-set-point ev)
  8998. (org-open-at-point 'in-emacs))
  8999. (defun org-open-at-mouse (ev)
  9000. "Open file link or URL at mouse.
  9001. See the docstring of `org-open-file' for details."
  9002. (interactive "e")
  9003. (mouse-set-point ev)
  9004. (when (eq major-mode 'org-agenda-mode)
  9005. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9006. (org-open-at-point))
  9007. (defvar org-window-config-before-follow-link nil
  9008. "The window configuration before following a link.
  9009. This is saved in case the need arises to restore it.")
  9010. ;;;###autoload
  9011. (defun org-open-at-point-global ()
  9012. "Follow a link or a time-stamp like Org mode does.
  9013. Also follow links and emails as seen by `thing-at-point'.
  9014. This command can be called in any mode to follow an external
  9015. link or a time-stamp that has Org mode syntax. Its behavior
  9016. is undefined when called on internal links like fuzzy links.
  9017. Raise a user error when there is nothing to follow."
  9018. (interactive)
  9019. (let ((tap-url (thing-at-point 'url))
  9020. (tap-email (thing-at-point 'email)))
  9021. (cond ((org-in-regexp org-any-link-re)
  9022. (org-open-link-from-string (match-string-no-properties 0)))
  9023. ((or (org-in-regexp org-ts-regexp-both nil t)
  9024. (org-in-regexp org-tsr-regexp-both nil t))
  9025. (org-follow-timestamp-link))
  9026. (tap-url (org-open-link-from-string tap-url))
  9027. (tap-email (org-open-link-from-string
  9028. (concat "mailto:" tap-email)))
  9029. (t (user-error "No link found")))))
  9030. ;;;###autoload
  9031. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9032. "Open a link in the string S, as if it was in Org mode."
  9033. (interactive "sLink: \nP")
  9034. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9035. (with-temp-buffer
  9036. (let ((org-inhibit-startup (not reference-buffer)))
  9037. (org-mode)
  9038. (insert s)
  9039. (goto-char (point-min))
  9040. (when reference-buffer
  9041. (setq org-link-abbrev-alist-local
  9042. (with-current-buffer reference-buffer
  9043. org-link-abbrev-alist-local)))
  9044. (org-open-at-point arg reference-buffer)))))
  9045. (defvar org-open-at-point-functions nil
  9046. "Hook that is run when following a link at point.
  9047. Functions in this hook must return t if they identify and follow
  9048. a link at point. If they don't find anything interesting at point,
  9049. they must return nil.")
  9050. (defvar org-link-search-inhibit-query nil)
  9051. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9052. (defun org--open-doi-link (path)
  9053. "Open a \"doi\" type link.
  9054. PATH is a the path to search for, as a string."
  9055. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9056. (defun org--open-elisp-link (path)
  9057. "Open a \"elisp\" type link.
  9058. PATH is the sexp to evaluate, as a string."
  9059. (let ((cmd path))
  9060. (if (or (and (org-string-nw-p
  9061. org-confirm-elisp-link-not-regexp)
  9062. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9063. (not org-confirm-elisp-link-function)
  9064. (funcall org-confirm-elisp-link-function
  9065. (format "Execute \"%s\" as elisp? "
  9066. (org-add-props cmd nil 'face 'org-warning))))
  9067. (message "%s => %s" cmd
  9068. (if (eq (string-to-char cmd) ?\()
  9069. (eval (read cmd))
  9070. (call-interactively (read cmd))))
  9071. (user-error "Abort"))))
  9072. (defun org--open-help-link (path)
  9073. "Open a \"help\" type link.
  9074. PATH is a symbol name, as a string."
  9075. (pcase (intern path)
  9076. ((and (pred fboundp) variable) (describe-function variable))
  9077. ((and (pred boundp) function) (describe-variable function))
  9078. (name (user-error "Unknown function or variable: %s" name))))
  9079. (defun org--open-shell-link (path)
  9080. "Open a \"shell\" type link.
  9081. PATH is the command to execute, as a string."
  9082. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9083. (cmd path))
  9084. (if (or (and (org-string-nw-p
  9085. org-confirm-shell-link-not-regexp)
  9086. (string-match
  9087. org-confirm-shell-link-not-regexp cmd))
  9088. (not org-confirm-shell-link-function)
  9089. (funcall org-confirm-shell-link-function
  9090. (format "Execute \"%s\" in shell? "
  9091. (org-add-props cmd nil
  9092. 'face 'org-warning))))
  9093. (progn
  9094. (message "Executing %s" cmd)
  9095. (shell-command cmd buf)
  9096. (when (featurep 'midnight)
  9097. (setq clean-buffer-list-kill-buffer-names
  9098. (cons (buffer-name buf)
  9099. clean-buffer-list-kill-buffer-names))))
  9100. (user-error "Abort"))))
  9101. (defun org-open-at-point (&optional arg reference-buffer)
  9102. "Open link, timestamp, footnote or tags at point.
  9103. When point is on a link, follow it. Normally, files will be
  9104. opened by an appropriate application. If the optional prefix
  9105. argument ARG is non-nil, Emacs will visit the file. With
  9106. a double prefix argument, try to open outside of Emacs, in the
  9107. application the system uses for this file type.
  9108. When point is on a timestamp, open the agenda at the day
  9109. specified.
  9110. When point is a footnote definition, move to the first reference
  9111. found. If it is on a reference, move to the associated
  9112. definition.
  9113. When point is on a headline, display a list of every link in the
  9114. entry, so it is possible to pick one, or all, of them. If point
  9115. is on a tag, call `org-tags-view' instead.
  9116. When optional argument REFERENCE-BUFFER is non-nil, it should
  9117. specify a buffer from where the link search should happen. This
  9118. is used internally by `org-open-link-from-string'.
  9119. On top of syntactically correct links, this function also tries
  9120. to open links and time-stamps in comments, node properties, and
  9121. keywords if point is on something looking like a timestamp or
  9122. a link."
  9123. (interactive "P")
  9124. (org-load-modules-maybe)
  9125. (setq org-window-config-before-follow-link (current-window-configuration))
  9126. (org-remove-occur-highlights nil nil t)
  9127. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9128. (let* ((context
  9129. ;; Only consider supported types, even if they are not the
  9130. ;; closest one.
  9131. (org-element-lineage
  9132. (org-element-context)
  9133. '(clock comment comment-block footnote-definition
  9134. footnote-reference headline inline-src-block inlinetask
  9135. keyword link node-property planning src-block timestamp)
  9136. t))
  9137. (type (org-element-type context))
  9138. (value (org-element-property :value context)))
  9139. (cond
  9140. ((not type) (user-error "No link found"))
  9141. ;; No valid link at point. For convenience, look if something
  9142. ;; looks like a link under point in some specific places.
  9143. ((memq type '(comment comment-block node-property keyword))
  9144. (call-interactively #'org-open-at-point-global))
  9145. ;; On a headline or an inlinetask, but not on a timestamp,
  9146. ;; a link, a footnote reference.
  9147. ((memq type '(headline inlinetask))
  9148. (org-match-line org-complex-heading-regexp)
  9149. (if (and (match-beginning 5)
  9150. (>= (point) (match-beginning 5))
  9151. (< (point) (match-end 5)))
  9152. ;; On tags.
  9153. (org-tags-view arg (substring (match-string 5) 0 -1))
  9154. ;; Not on tags.
  9155. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9156. (`(nil . ,_)
  9157. (require 'org-attach)
  9158. (org-attach-reveal 'if-exists))
  9159. (`(,links . ,links-end)
  9160. (dolist (link (if (stringp links) (list links) links))
  9161. (search-forward link nil links-end)
  9162. (goto-char (match-beginning 0))
  9163. (org-open-at-point))))))
  9164. ;; On a footnote reference or at definition's label.
  9165. ((or (eq type 'footnote-reference)
  9166. (and (eq type 'footnote-definition)
  9167. (save-excursion
  9168. ;; Do not validate action when point is on the
  9169. ;; spaces right after the footnote label, in order
  9170. ;; to be on par with behavior on links.
  9171. (skip-chars-forward " \t")
  9172. (let ((begin
  9173. (org-element-property :contents-begin context)))
  9174. (if begin (< (point) begin)
  9175. (= (org-element-property :post-affiliated context)
  9176. (line-beginning-position)))))))
  9177. (org-footnote-action))
  9178. ;; On a planning line. Check if we are really on a timestamp.
  9179. ((and (eq type 'planning)
  9180. (org-in-regexp org-ts-regexp-both nil t))
  9181. (org-follow-timestamp-link))
  9182. ;; On a clock line, make sure point is on the timestamp
  9183. ;; before opening it.
  9184. ((and (eq type 'clock)
  9185. value
  9186. (>= (point) (org-element-property :begin value))
  9187. (<= (point) (org-element-property :end value)))
  9188. (org-follow-timestamp-link))
  9189. ((eq type 'src-block) (org-babel-open-src-block-result))
  9190. ;; Do nothing on white spaces after an object.
  9191. ((>= (point)
  9192. (save-excursion
  9193. (goto-char (org-element-property :end context))
  9194. (skip-chars-backward " \t")
  9195. (point)))
  9196. (user-error "No link found"))
  9197. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  9198. ((eq type 'timestamp) (org-follow-timestamp-link))
  9199. ((eq type 'link)
  9200. (let ((type (org-element-property :type context))
  9201. (path (org-link-unescape (org-element-property :path context))))
  9202. ;; Switch back to REFERENCE-BUFFER needed when called in
  9203. ;; a temporary buffer through `org-open-link-from-string'.
  9204. (with-current-buffer (or reference-buffer (current-buffer))
  9205. (cond
  9206. ((equal type "file")
  9207. (if (string-match "[*?{]" (file-name-nondirectory path))
  9208. (dired path)
  9209. ;; Look into `org-link-parameters' in order to find
  9210. ;; a DEDICATED-FUNCTION to open file. The function
  9211. ;; will be applied on raw link instead of parsed link
  9212. ;; due to the limitation in `org-add-link-type'
  9213. ;; ("open" function called with a single argument).
  9214. ;; If no such function is found, fallback to
  9215. ;; `org-open-file'.
  9216. (let* ((option (org-element-property :search-option context))
  9217. (app (org-element-property :application context))
  9218. (dedicated-function
  9219. (org-link-get-parameter
  9220. (if app (concat type "+" app) type)
  9221. :follow)))
  9222. (if dedicated-function
  9223. (funcall dedicated-function
  9224. (concat path
  9225. (and option (concat "::" option))))
  9226. (apply #'org-open-file
  9227. path
  9228. (cond (arg)
  9229. ((equal app "emacs") 'emacs)
  9230. ((equal app "sys") 'system))
  9231. (cond ((not option) nil)
  9232. ((string-match-p "\\`[0-9]+\\'" option)
  9233. (list (string-to-number option)))
  9234. (t (list nil
  9235. (org-link-unescape option)))))))))
  9236. ((functionp (org-link-get-parameter type :follow))
  9237. (funcall (org-link-get-parameter type :follow) path))
  9238. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9239. (unless (run-hook-with-args-until-success
  9240. 'org-open-link-functions path)
  9241. (if (not arg) (org-mark-ring-push)
  9242. (switch-to-buffer-other-window
  9243. (org-get-buffer-for-internal-link (current-buffer))))
  9244. (let ((destination
  9245. (org-with-wide-buffer
  9246. (if (equal type "radio")
  9247. (org-search-radio-target
  9248. (org-element-property :path context))
  9249. (org-link-search
  9250. (pcase type
  9251. ("custom-id" (concat "#" path))
  9252. ("coderef" (format "(%s)" path))
  9253. (_ path))
  9254. ;; Prevent fuzzy links from matching
  9255. ;; themselves.
  9256. (and (equal type "fuzzy")
  9257. (+ 2 (org-element-property :begin context)))))
  9258. (point))))
  9259. (unless (and (<= (point-min) destination)
  9260. (>= (point-max) destination))
  9261. (widen))
  9262. (goto-char destination))))
  9263. (t (browse-url-at-point))))))
  9264. (t (user-error "No link found")))))
  9265. (run-hook-with-args 'org-follow-link-hook))
  9266. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9267. "Offer links in the current entry and return the selected link.
  9268. If there is only one link, return it.
  9269. If NTH is an integer, return the NTH link found.
  9270. If ZERO is a string, check also this string for a link, and if
  9271. there is one, return it."
  9272. (with-current-buffer buffer
  9273. (org-with-wide-buffer
  9274. (goto-char marker)
  9275. (let ((cnt ?0)
  9276. have-zero end links link c)
  9277. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9278. (push (match-string 0 zero) links)
  9279. (setq cnt (1- cnt) have-zero t))
  9280. (save-excursion
  9281. (org-back-to-heading t)
  9282. (setq end (save-excursion (outline-next-heading) (point)))
  9283. (while (re-search-forward org-any-link-re end t)
  9284. (push (match-string 0) links))
  9285. (setq links (org-uniquify (reverse links))))
  9286. (cond
  9287. ((null links)
  9288. (message "No links"))
  9289. ((equal (length links) 1)
  9290. (setq link (car links)))
  9291. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9292. (setq link (nth (if have-zero nth (1- nth)) links)))
  9293. (t ; we have to select a link
  9294. (save-excursion
  9295. (save-window-excursion
  9296. (delete-other-windows)
  9297. (with-output-to-temp-buffer "*Select Link*"
  9298. (dolist (l links)
  9299. (cond
  9300. ((not (string-match org-bracket-link-regexp l))
  9301. (princ (format "[%c] %s\n" (cl-incf cnt)
  9302. (org-unbracket-string "<" ">" l))))
  9303. ((match-end 3)
  9304. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9305. (match-string 3 l) (match-string 1 l))))
  9306. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9307. (match-string 1 l)))))))
  9308. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9309. (message "Select link to open, RET to open all:")
  9310. (setq c (read-char-exclusive))
  9311. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9312. (when (equal c ?q) (user-error "Abort"))
  9313. (if (equal c ?\C-m)
  9314. (setq link links)
  9315. (setq nth (- c ?0))
  9316. (when have-zero (setq nth (1+ nth)))
  9317. (unless (and (integerp nth) (>= (length links) nth))
  9318. (user-error "Invalid link selection"))
  9319. (setq link (nth (1- nth) links)))))
  9320. (cons link end)))))
  9321. ;; TODO: These functions are deprecated since `org-open-at-point'
  9322. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9323. (defun org-open-file-with-system (path)
  9324. "Open file at PATH using the system way of opening it."
  9325. (org-open-file path 'system))
  9326. (defun org-open-file-with-emacs (path)
  9327. "Open file at PATH in Emacs."
  9328. (org-open-file path 'emacs))
  9329. ;;; File search
  9330. (defvar org-create-file-search-functions nil
  9331. "List of functions to construct the right search string for a file link.
  9332. These functions are called in turn with point at the location to
  9333. which the link should point.
  9334. A function in the hook should first test if it would like to
  9335. handle this file type, for example by checking the `major-mode'
  9336. or the file extension. If it decides not to handle this file, it
  9337. should just return nil to give other functions a chance. If it
  9338. does handle the file, it must return the search string to be used
  9339. when following the link. The search string will be part of the
  9340. file link, given after a double colon, and `org-open-at-point'
  9341. will automatically search for it. If special measures must be
  9342. taken to make the search successful, another function should be
  9343. added to the companion hook `org-execute-file-search-functions',
  9344. which see.
  9345. A function in this hook may also use `setq' to set the variable
  9346. `description' to provide a suggestion for the descriptive text to
  9347. be used for this link when it gets inserted into an Org buffer
  9348. with \\[org-insert-link].")
  9349. (defvar org-execute-file-search-functions nil
  9350. "List of functions to execute a file search triggered by a link.
  9351. Functions added to this hook must accept a single argument, the
  9352. search string that was part of the file link, the part after the
  9353. double colon. The function must first check if it would like to
  9354. handle this search, for example by checking the `major-mode' or
  9355. the file extension. If it decides not to handle this search, it
  9356. should just return nil to give other functions a chance. If it
  9357. does handle the search, it must return a non-nil value to keep
  9358. other functions from trying.
  9359. Each function can access the current prefix argument through the
  9360. variable `current-prefix-arg'. Note that a single prefix is used
  9361. to force opening a link in Emacs, so it may be good to only use a
  9362. numeric or double prefix to guide the search function.
  9363. In case this is needed, a function in this hook can also restore
  9364. the window configuration before `org-open-at-point' was called using:
  9365. (set-window-configuration org-window-config-before-follow-link)")
  9366. (defun org-search-radio-target (target)
  9367. "Search a radio target matching TARGET in current buffer.
  9368. White spaces are not significant."
  9369. (let ((re (format "<<<%s>>>"
  9370. (mapconcat #'regexp-quote
  9371. (split-string target)
  9372. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9373. (origin (point)))
  9374. (goto-char (point-min))
  9375. (catch :radio-match
  9376. (while (re-search-forward re nil t)
  9377. (backward-char)
  9378. (let ((object (org-element-context)))
  9379. (when (eq (org-element-type object) 'radio-target)
  9380. (goto-char (org-element-property :begin object))
  9381. (org-show-context 'link-search)
  9382. (throw :radio-match nil))))
  9383. (goto-char origin)
  9384. (user-error "No match for radio target: %s" target))))
  9385. (defun org-link-search (s &optional avoid-pos stealth)
  9386. "Search for a search string S.
  9387. If S starts with \"#\", it triggers a custom ID search.
  9388. If S is enclosed within parenthesis, it initiates a coderef
  9389. search.
  9390. If S is surrounded by forward slashes, it is interpreted as
  9391. a regular expression. In Org mode files, this will create an
  9392. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9393. to list matches. If the current buffer is in `dired-mode', grep
  9394. will be used to search in all files.
  9395. When AVOID-POS is given, ignore matches near that position.
  9396. When optional argument STEALTH is non-nil, do not modify
  9397. visibility around point, thus ignoring `org-show-context-detail'
  9398. variable.
  9399. Search is case-insensitive and ignores white spaces. Return type
  9400. of matched result, which is either `dedicated' or `fuzzy'."
  9401. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9402. (let* ((case-fold-search t)
  9403. (origin (point))
  9404. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9405. (starred (eq (string-to-char normalized) ?*))
  9406. (words (split-string (if starred (substring s 1) s)))
  9407. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9408. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9409. type)
  9410. (cond
  9411. ;; Check if there are any special search functions.
  9412. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9413. ((eq (string-to-char s) ?#)
  9414. ;; Look for a custom ID S if S starts with "#".
  9415. (let* ((id (substring normalized 1))
  9416. (match (org-find-property "CUSTOM_ID" id)))
  9417. (if match (progn (goto-char match) (setf type 'dedicated))
  9418. (error "No match for custom ID: %s" id))))
  9419. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9420. ;; Look for coderef targets if S is enclosed within parenthesis.
  9421. (let ((coderef (match-string-no-properties 1 normalized))
  9422. (re (substring s-single-re 1 -1)))
  9423. (goto-char (point-min))
  9424. (catch :coderef-match
  9425. (while (re-search-forward re nil t)
  9426. (let ((element (org-element-at-point)))
  9427. (when (and (memq (org-element-type element)
  9428. '(example-block src-block))
  9429. (org-match-line
  9430. (concat ".*?" (org-src-coderef-regexp
  9431. (org-src-coderef-format element)
  9432. coderef))))
  9433. (setq type 'dedicated)
  9434. (goto-char (match-beginning 2))
  9435. (throw :coderef-match nil))))
  9436. (goto-char origin)
  9437. (error "No match for coderef: %s" coderef))))
  9438. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9439. ;; Look for a regular expression.
  9440. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9441. (match-string 1 s)))
  9442. ;; From here, we handle fuzzy links.
  9443. ;;
  9444. ;; Look for targets, only if not in a headline search.
  9445. ((and (not starred)
  9446. (let ((target (format "<<%s>>" s-multi-re)))
  9447. (catch :target-match
  9448. (goto-char (point-min))
  9449. (while (re-search-forward target nil t)
  9450. (backward-char)
  9451. (let ((context (org-element-context)))
  9452. (when (eq (org-element-type context) 'target)
  9453. (setq type 'dedicated)
  9454. (goto-char (org-element-property :begin context))
  9455. (throw :target-match t))))
  9456. nil))))
  9457. ;; Look for elements named after S, only if not in a headline
  9458. ;; search.
  9459. ((and (not starred)
  9460. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9461. (catch :name-match
  9462. (goto-char (point-min))
  9463. (while (re-search-forward name nil t)
  9464. (let ((element (org-element-at-point)))
  9465. (when (equal words
  9466. (split-string
  9467. (org-element-property :name element)))
  9468. (setq type 'dedicated)
  9469. (beginning-of-line)
  9470. (throw :name-match t))))
  9471. nil))))
  9472. ;; Regular text search. Prefer headlines in Org mode buffers.
  9473. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9474. ;; statistics cookies and tags.
  9475. ((and (derived-mode-p 'org-mode)
  9476. (let ((title-re
  9477. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9478. org-outline-regexp-bol
  9479. org-comment-string
  9480. (mapconcat #'regexp-quote words ".+")))
  9481. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9482. (comment-re (eval-when-compile
  9483. (format "\\`%s[ \t]+" org-comment-string))))
  9484. (goto-char (point-min))
  9485. (catch :found
  9486. (while (re-search-forward title-re nil t)
  9487. (when (equal words
  9488. (split-string
  9489. (replace-regexp-in-string
  9490. cookie-re ""
  9491. (replace-regexp-in-string
  9492. comment-re "" (org-get-heading t t t)))))
  9493. (throw :found t)))
  9494. nil)))
  9495. (beginning-of-line)
  9496. (setq type 'dedicated))
  9497. ;; Offer to create non-existent headline depending on
  9498. ;; `org-link-search-must-match-exact-headline'.
  9499. ((and (derived-mode-p 'org-mode)
  9500. (not org-link-search-inhibit-query)
  9501. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9502. (yes-or-no-p "No match - create this as a new heading? "))
  9503. (goto-char (point-max))
  9504. (unless (bolp) (newline))
  9505. (org-insert-heading nil t t)
  9506. (insert s "\n")
  9507. (beginning-of-line 0))
  9508. ;; Only headlines are looked after. No need to process
  9509. ;; further: throw an error.
  9510. ((and (derived-mode-p 'org-mode)
  9511. (or starred org-link-search-must-match-exact-headline))
  9512. (goto-char origin)
  9513. (error "No match for fuzzy expression: %s" normalized))
  9514. ;; Regular text search.
  9515. ((catch :fuzzy-match
  9516. (goto-char (point-min))
  9517. (while (re-search-forward s-multi-re nil t)
  9518. ;; Skip match if it contains AVOID-POS or it is included in
  9519. ;; a link with a description but outside the description.
  9520. (unless (or (and avoid-pos
  9521. (<= (match-beginning 0) avoid-pos)
  9522. (> (match-end 0) avoid-pos))
  9523. (and (save-match-data
  9524. (org-in-regexp org-bracket-link-regexp))
  9525. (match-beginning 3)
  9526. (or (> (match-beginning 3) (point))
  9527. (<= (match-end 3) (point)))
  9528. (org-element-lineage
  9529. (save-match-data (org-element-context))
  9530. '(link) t)))
  9531. (goto-char (match-beginning 0))
  9532. (setq type 'fuzzy)
  9533. (throw :fuzzy-match t)))
  9534. nil))
  9535. ;; All failed. Throw an error.
  9536. (t (goto-char origin)
  9537. (error "No match for fuzzy expression: %s" normalized)))
  9538. ;; Disclose surroundings of match, if appropriate.
  9539. (when (and (derived-mode-p 'org-mode) (not stealth))
  9540. (org-show-context 'link-search))
  9541. type))
  9542. (defun org-get-buffer-for-internal-link (buffer)
  9543. "Return a buffer to be used for displaying the link target of internal links."
  9544. (cond
  9545. ((not org-display-internal-link-with-indirect-buffer)
  9546. buffer)
  9547. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9548. (message "Buffer is already a clone, not making another one")
  9549. ;; we also do not modify visibility in this case
  9550. buffer)
  9551. (t ; make a new indirect buffer for displaying the link
  9552. (let* ((bn (buffer-name buffer))
  9553. (ibn (concat bn "(Clone)"))
  9554. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9555. (with-current-buffer ib (org-overview))
  9556. ib))))
  9557. (defun org-do-occur (regexp &optional cleanup)
  9558. "Call the Emacs command `occur'.
  9559. If CLEANUP is non-nil, remove the printout of the regular expression
  9560. in the *Occur* buffer. This is useful if the regex is long and not useful
  9561. to read."
  9562. (occur regexp)
  9563. (when cleanup
  9564. (let ((cwin (selected-window)) win beg end)
  9565. (when (setq win (get-buffer-window "*Occur*"))
  9566. (select-window win))
  9567. (goto-char (point-min))
  9568. (when (re-search-forward "match[a-z]+" nil t)
  9569. (setq beg (match-end 0))
  9570. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9571. (setq end (1- (match-beginning 0)))))
  9572. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9573. (goto-char (point-min))
  9574. (select-window cwin))))
  9575. ;;; The Mark Ring
  9576. (defvar org-mark-ring nil
  9577. "Mark ring for positions before jumps in Org mode.")
  9578. (defvar org-mark-ring-last-goto nil
  9579. "Last position in the mark ring used to go back.")
  9580. ;; Fill and close the ring
  9581. (setq org-mark-ring nil)
  9582. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9583. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9584. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9585. org-mark-ring)
  9586. (defun org-mark-ring-push (&optional pos buffer)
  9587. "Put the current position into the mark ring and rotate it.
  9588. Also push position into the Emacs mark ring. If optional
  9589. argument POS and BUFFER are not nil, mark this location instead."
  9590. (interactive)
  9591. (let ((pos (or pos (point)))
  9592. (buffer (or buffer (current-buffer))))
  9593. (with-current-buffer buffer
  9594. (org-with-point-at pos (push-mark nil t)))
  9595. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9596. (move-marker (car org-mark-ring) pos buffer))
  9597. (message
  9598. (substitute-command-keys
  9599. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9600. (defun org-mark-ring-goto (&optional n)
  9601. "Jump to the previous position in the mark ring.
  9602. With prefix arg N, jump back that many stored positions. When
  9603. called several times in succession, walk through the entire ring.
  9604. Org mode commands jumping to a different position in the current file,
  9605. or to another Org file, automatically push the old position onto the ring."
  9606. (interactive "p")
  9607. (let (p m)
  9608. (if (eq last-command this-command)
  9609. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9610. (setq p org-mark-ring))
  9611. (setq org-mark-ring-last-goto p)
  9612. (setq m (car p))
  9613. (pop-to-buffer-same-window (marker-buffer m))
  9614. (goto-char m)
  9615. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9616. (defun org-add-angle-brackets (s)
  9617. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9618. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9619. s)
  9620. ;;; Following specific links
  9621. (defvar org-agenda-buffer-tmp-name)
  9622. (defvar org-agenda-start-on-weekday)
  9623. (defun org-follow-timestamp-link ()
  9624. "Open an agenda view for the time-stamp date/range at point."
  9625. (cond
  9626. ((org-at-date-range-p t)
  9627. (let ((org-agenda-start-on-weekday)
  9628. (t1 (match-string 1))
  9629. (t2 (match-string 2)) tt1 tt2)
  9630. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9631. tt2 (time-to-days (org-time-string-to-time t2)))
  9632. (let ((org-agenda-buffer-tmp-name
  9633. (format "*Org Agenda(a:%s)"
  9634. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9635. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9636. ((org-at-timestamp-p 'lax)
  9637. (let ((org-agenda-buffer-tmp-name
  9638. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9639. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9640. (substring (match-string 1) 0 10)))
  9641. 1)))
  9642. (t (error "This should not happen"))))
  9643. ;;; Following file links
  9644. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9645. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9646. (declare-function mailcap-mime-info
  9647. "mailcap" (string &optional request no-decode))
  9648. (defvar org-wait nil)
  9649. (defun org-open-file (path &optional in-emacs line search)
  9650. "Open the file at PATH.
  9651. First, this expands any special file name abbreviations. Then the
  9652. configuration variable `org-file-apps' is checked if it contains an
  9653. entry for this file type, and if yes, the corresponding command is launched.
  9654. If no application is found, Emacs simply visits the file.
  9655. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9656. With a double \\[universal-argument] \\[universal-argument] \
  9657. prefix arg, Org tries to avoid opening in Emacs
  9658. and to use an external application to visit the file.
  9659. Optional LINE specifies a line to go to, optional SEARCH a string
  9660. to search for. If LINE or SEARCH is given, the file will be
  9661. opened in Emacs, unless an entry from org-file-apps that makes
  9662. use of groups in a regexp matches.
  9663. If you want to change the way frames are used when following a
  9664. link, please customize `org-link-frame-setup'.
  9665. If the file does not exist, an error is thrown."
  9666. (let* ((file (if (equal path "")
  9667. buffer-file-name
  9668. (substitute-in-file-name (expand-file-name path))))
  9669. (file-apps (append org-file-apps (org-default-apps)))
  9670. (apps (cl-remove-if
  9671. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9672. (apps-dlink (cl-remove-if-not
  9673. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9674. (remp (and (assq 'remote apps) (file-remote-p file)))
  9675. (dirp (unless remp (file-directory-p file)))
  9676. (file (if (and dirp org-open-directory-means-index-dot-org)
  9677. (concat (file-name-as-directory file) "index.org")
  9678. file))
  9679. (a-m-a-p (assq 'auto-mode apps))
  9680. (dfile (downcase file))
  9681. ;; Reconstruct the original link from the PATH, LINE and
  9682. ;; SEARCH args.
  9683. (link (cond (line (concat file "::" (number-to-string line)))
  9684. (search (concat file "::" search))
  9685. (t file)))
  9686. (dlink (downcase link))
  9687. (ext
  9688. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9689. (match-string 1 dfile)))
  9690. (save-position-maybe
  9691. (let ((old-buffer (current-buffer))
  9692. (old-pos (point))
  9693. (old-mode major-mode))
  9694. (lambda ()
  9695. (and (derived-mode-p 'org-mode)
  9696. (eq old-mode 'org-mode)
  9697. (or (not (eq old-buffer (current-buffer)))
  9698. (not (eq old-pos (point))))
  9699. (org-mark-ring-push old-pos old-buffer)))))
  9700. cmd link-match-data)
  9701. (cond
  9702. ((member in-emacs '((16) system))
  9703. (setq cmd (cdr (assq 'system apps))))
  9704. (in-emacs (setq cmd 'emacs))
  9705. (t
  9706. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9707. (and dirp (cdr (assq 'directory apps)))
  9708. ;; First, try matching against apps-dlink if we
  9709. ;; get a match here, store the match data for
  9710. ;; later.
  9711. (let ((match (assoc-default dlink apps-dlink
  9712. 'string-match)))
  9713. (if match
  9714. (progn (setq link-match-data (match-data))
  9715. match)
  9716. (progn (setq in-emacs (or in-emacs line search))
  9717. nil))) ; if we have no match in apps-dlink,
  9718. ; always open the file in emacs if line or search
  9719. ; is given (for backwards compatibility)
  9720. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9721. 'string-match)
  9722. (cdr (assoc ext apps))
  9723. (cdr (assq t apps))))))
  9724. (when (eq cmd 'system)
  9725. (setq cmd (cdr (assq 'system apps))))
  9726. (when (eq cmd 'default)
  9727. (setq cmd (cdr (assoc t apps))))
  9728. (when (eq cmd 'mailcap)
  9729. (require 'mailcap)
  9730. (mailcap-parse-mailcaps)
  9731. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9732. (command (mailcap-mime-info mime-type)))
  9733. (if (stringp command)
  9734. (setq cmd command)
  9735. (setq cmd 'emacs))))
  9736. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9737. (not (file-exists-p file))
  9738. (not org-open-non-existing-files))
  9739. (user-error "No such file: %s" file))
  9740. (cond
  9741. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9742. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9743. (while (string-match "['\"]%s['\"]" cmd)
  9744. (setq cmd (replace-match "%s" t t cmd)))
  9745. (setq cmd (replace-regexp-in-string
  9746. "%s"
  9747. (shell-quote-argument (convert-standard-filename file))
  9748. cmd
  9749. nil t))
  9750. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9751. (save-match-data
  9752. (let ((match-index 1)
  9753. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9754. (set-match-data link-match-data)
  9755. (while (<= match-index number-of-groups)
  9756. (let ((regex (concat "%" (number-to-string match-index)))
  9757. (replace-with (match-string match-index dlink)))
  9758. (while (string-match regex cmd)
  9759. (setq cmd (replace-match replace-with t t cmd))))
  9760. (setq match-index (+ match-index 1)))))
  9761. (save-window-excursion
  9762. (message "Running %s...done" cmd)
  9763. (start-process-shell-command cmd nil cmd)
  9764. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9765. ((or (stringp cmd)
  9766. (eq cmd 'emacs))
  9767. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9768. (widen)
  9769. (cond (line (org-goto-line line)
  9770. (when (derived-mode-p 'org-mode) (org-reveal)))
  9771. (search (condition-case err
  9772. (org-link-search search)
  9773. ;; Save position before error-ing out so user
  9774. ;; can easily move back to the original buffer.
  9775. (error (funcall save-position-maybe)
  9776. (error (nth 1 err)))))))
  9777. ((functionp cmd)
  9778. (save-match-data
  9779. (set-match-data link-match-data)
  9780. (condition-case nil
  9781. (funcall cmd file link)
  9782. ;; FIXME: Remove this check when most default installations
  9783. ;; of Emacs have at least Org 9.0.
  9784. ((debug wrong-number-of-arguments wrong-type-argument
  9785. invalid-function)
  9786. (user-error "Please see Org News for version 9.0 about \
  9787. `org-file-apps'--Lisp error: %S" cmd)))))
  9788. ((consp cmd)
  9789. ;; FIXME: Remove this check when most default installations of
  9790. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9791. ;; fall back to `org-link-frame-setup' for an old usage of
  9792. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9793. (user-error "Please see Org News for version 9.0 about \
  9794. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9795. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9796. (funcall save-position-maybe)))
  9797. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9798. "This function returns non-nil if `entry' uses a regular
  9799. expression which should be matched against the whole link by
  9800. org-open-file.
  9801. It assumes that is the case when the entry uses a regular
  9802. expression which has at least one grouping construct and the
  9803. action is either a lisp form or a command string containing
  9804. `%1', i.e. using at least one subexpression match as a
  9805. parameter."
  9806. (let ((selector (car entry))
  9807. (action (cdr entry)))
  9808. (if (stringp selector)
  9809. (and (> (regexp-opt-depth selector) 0)
  9810. (or (and (stringp action)
  9811. (string-match "%[0-9]" action))
  9812. (consp action)))
  9813. nil)))
  9814. (defun org-default-apps ()
  9815. "Return the default applications for this operating system."
  9816. (cond
  9817. ((eq system-type 'darwin)
  9818. org-file-apps-defaults-macosx)
  9819. ((eq system-type 'windows-nt)
  9820. org-file-apps-defaults-windowsnt)
  9821. (t org-file-apps-defaults-gnu)))
  9822. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9823. "Convert extensions to regular expressions in the cars of LIST.
  9824. Also, weed out any non-string entries, because the return value is used
  9825. only for regexp matching.
  9826. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9827. point to the symbol `emacs', indicating that the file should
  9828. be opened in Emacs."
  9829. (append
  9830. (delq nil
  9831. (mapcar (lambda (x)
  9832. (unless (not (stringp (car x)))
  9833. (if (string-match "\\W" (car x))
  9834. x
  9835. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9836. list))
  9837. (when add-auto-mode
  9838. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9839. ;;;; Refiling
  9840. (defun org-get-org-file ()
  9841. "Read a filename, with default directory `org-directory'."
  9842. (let ((default (or org-default-notes-file remember-data-file)))
  9843. (read-file-name (format "File name [%s]: " default)
  9844. (file-name-as-directory org-directory)
  9845. default)))
  9846. (defun org-notes-order-reversed-p ()
  9847. "Check if the current file should receive notes in reversed order."
  9848. (cond
  9849. ((not org-reverse-note-order) nil)
  9850. ((eq t org-reverse-note-order) t)
  9851. ((not (listp org-reverse-note-order)) nil)
  9852. (t (catch 'exit
  9853. (dolist (entry org-reverse-note-order)
  9854. (when (string-match (car entry) buffer-file-name)
  9855. (throw 'exit (cdr entry))))))))
  9856. (defvar org-refile-target-table nil
  9857. "The list of refile targets, created by `org-refile'.")
  9858. (defvar org-agenda-new-buffers nil
  9859. "Buffers created to visit agenda files.")
  9860. (defvar org-refile-cache nil
  9861. "Cache for refile targets.")
  9862. (defvar org-refile-markers nil
  9863. "All the markers used for caching refile locations.")
  9864. (defun org-refile-marker (pos)
  9865. "Get a new refile marker, but only if caching is in use."
  9866. (if (not org-refile-use-cache)
  9867. pos
  9868. (let ((m (make-marker)))
  9869. (move-marker m pos)
  9870. (push m org-refile-markers)
  9871. m)))
  9872. (defun org-refile-cache-clear ()
  9873. "Clear the refile cache and disable all the markers."
  9874. (dolist (m org-refile-markers) (move-marker m nil))
  9875. (setq org-refile-markers nil)
  9876. (setq org-refile-cache nil)
  9877. (message "Refile cache has been cleared"))
  9878. (defun org-refile-cache-check-set (set)
  9879. "Check if all the markers in the cache still have live buffers."
  9880. (let (marker)
  9881. (catch 'exit
  9882. (while (and set (setq marker (nth 3 (pop set))))
  9883. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9884. (when (and marker (null (marker-buffer marker)))
  9885. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9886. (sit-for 3)
  9887. (throw 'exit nil)))
  9888. t)))
  9889. (defun org-refile-cache-put (set &rest identifiers)
  9890. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9891. (let* ((key (sha1 (prin1-to-string identifiers)))
  9892. (entry (assoc key org-refile-cache)))
  9893. (if entry
  9894. (setcdr entry set)
  9895. (push (cons key set) org-refile-cache))))
  9896. (defun org-refile-cache-get (&rest identifiers)
  9897. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9898. (cond
  9899. ((not org-refile-cache) nil)
  9900. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9901. (t
  9902. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9903. org-refile-cache))))
  9904. (and set (org-refile-cache-check-set set) set)))))
  9905. (defvar org-outline-path-cache nil
  9906. "Alist between buffer positions and outline paths.
  9907. It value is an alist (POSITION . PATH) where POSITION is the
  9908. buffer position at the beginning of an entry and PATH is a list
  9909. of strings describing the outline path for that entry, in reverse
  9910. order.")
  9911. (defun org-refile-get-targets (&optional default-buffer)
  9912. "Produce a table with refile targets."
  9913. (let ((case-fold-search nil)
  9914. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9915. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9916. targets tgs files desc descre)
  9917. (message "Getting targets...")
  9918. (with-current-buffer (or default-buffer (current-buffer))
  9919. (dolist (entry entries)
  9920. (setq files (car entry) desc (cdr entry))
  9921. (cond
  9922. ((null files) (setq files (list (current-buffer))))
  9923. ((eq files 'org-agenda-files)
  9924. (setq files (org-agenda-files 'unrestricted)))
  9925. ((and (symbolp files) (fboundp files))
  9926. (setq files (funcall files)))
  9927. ((and (symbolp files) (boundp files))
  9928. (setq files (symbol-value files))))
  9929. (when (stringp files) (setq files (list files)))
  9930. (cond
  9931. ((eq (car desc) :tag)
  9932. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9933. ((eq (car desc) :todo)
  9934. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9935. ((eq (car desc) :regexp)
  9936. (setq descre (cdr desc)))
  9937. ((eq (car desc) :level)
  9938. (setq descre (concat "^\\*\\{" (number-to-string
  9939. (if org-odd-levels-only
  9940. (1- (* 2 (cdr desc)))
  9941. (cdr desc)))
  9942. "\\}[ \t]")))
  9943. ((eq (car desc) :maxlevel)
  9944. (setq descre (concat "^\\*\\{1," (number-to-string
  9945. (if org-odd-levels-only
  9946. (1- (* 2 (cdr desc)))
  9947. (cdr desc)))
  9948. "\\}[ \t]")))
  9949. (t (error "Bad refiling target description %s" desc)))
  9950. (dolist (f files)
  9951. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9952. (or
  9953. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9954. (progn
  9955. (when (bufferp f)
  9956. (setq f (buffer-file-name (buffer-base-buffer f))))
  9957. (setq f (and f (expand-file-name f)))
  9958. (when (eq org-refile-use-outline-path 'file)
  9959. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9960. (when (eq org-refile-use-outline-path 'buffer-name)
  9961. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9962. (when (eq org-refile-use-outline-path 'full-file-path)
  9963. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9964. (org-with-wide-buffer
  9965. (goto-char (point-min))
  9966. (setq org-outline-path-cache nil)
  9967. (while (re-search-forward descre nil t)
  9968. (beginning-of-line)
  9969. (let ((case-fold-search nil))
  9970. (looking-at org-complex-heading-regexp))
  9971. (let ((begin (point))
  9972. (heading (match-string-no-properties 4)))
  9973. (unless (or (and
  9974. org-refile-target-verify-function
  9975. (not
  9976. (funcall org-refile-target-verify-function)))
  9977. (not heading))
  9978. (let ((re (format org-complex-heading-regexp-format
  9979. (regexp-quote heading)))
  9980. (target
  9981. (if (not org-refile-use-outline-path) heading
  9982. (mapconcat
  9983. #'identity
  9984. (append
  9985. (pcase org-refile-use-outline-path
  9986. (`file (list (file-name-nondirectory
  9987. (buffer-file-name
  9988. (buffer-base-buffer)))))
  9989. (`full-file-path
  9990. (list (buffer-file-name
  9991. (buffer-base-buffer))))
  9992. (`buffer-name
  9993. (list (buffer-name
  9994. (buffer-base-buffer))))
  9995. (_ nil))
  9996. (mapcar (lambda (s) (replace-regexp-in-string
  9997. "/" "\\/" s nil t))
  9998. (org-get-outline-path t t)))
  9999. "/"))))
  10000. (push (list target f re (org-refile-marker (point)))
  10001. tgs)))
  10002. (when (= (point) begin)
  10003. ;; Verification function has not moved point.
  10004. (end-of-line)))))))
  10005. (when org-refile-use-cache
  10006. (org-refile-cache-put tgs (buffer-file-name) descre))
  10007. (setq targets (append tgs targets))))))
  10008. (message "Getting targets...done")
  10009. (delete-dups (nreverse targets))))
  10010. (defun org--get-outline-path-1 (&optional use-cache)
  10011. "Return outline path to current headline.
  10012. Outline path is a list of strings, in reverse order. When
  10013. optional argument USE-CACHE is non-nil, make use of a cache. See
  10014. `org-get-outline-path' for details.
  10015. Assume buffer is widened and point is on a headline."
  10016. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10017. (let ((p (point))
  10018. (heading (let ((case-fold-search nil))
  10019. (looking-at org-complex-heading-regexp)
  10020. (if (not (match-end 4)) ""
  10021. ;; Remove statistics cookies.
  10022. (org-trim
  10023. (org-link-display-format
  10024. (replace-regexp-in-string
  10025. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10026. (match-string-no-properties 4))))))))
  10027. (if (org-up-heading-safe)
  10028. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10029. (when use-cache
  10030. (push (cons p path) org-outline-path-cache))
  10031. path)
  10032. ;; This is a new root node. Since we assume we are moving
  10033. ;; forward, we can drop previous cache so as to limit number
  10034. ;; of associations there.
  10035. (let ((path (list heading)))
  10036. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10037. path)))))
  10038. (defun org-get-outline-path (&optional with-self use-cache)
  10039. "Return the outline path to the current entry.
  10040. An outline path is a list of ancestors for current headline, as
  10041. a list of strings. Statistics cookies are removed and links are
  10042. replaced with their description, if any, or their path otherwise.
  10043. When optional argument WITH-SELF is non-nil, the path also
  10044. includes the current headline.
  10045. When optional argument USE-CACHE is non-nil, cache outline paths
  10046. between calls to this function so as to avoid backtracking. This
  10047. argument is useful when planning to find more than one outline
  10048. path in the same document. In that case, there are two
  10049. conditions to satisfy:
  10050. - `org-outline-path-cache' is set to nil before starting the
  10051. process;
  10052. - outline paths are computed by increasing buffer positions."
  10053. (org-with-wide-buffer
  10054. (and (or (and with-self (org-back-to-heading t))
  10055. (org-up-heading-safe))
  10056. (reverse (org--get-outline-path-1 use-cache)))))
  10057. (defun org-format-outline-path (path &optional width prefix separator)
  10058. "Format the outline path PATH for display.
  10059. WIDTH is the maximum number of characters that is available.
  10060. PREFIX is a prefix to be included in the returned string,
  10061. such as the file name.
  10062. SEPARATOR is inserted between the different parts of the path,
  10063. the default is \"/\"."
  10064. (setq width (or width 79))
  10065. (setq path (delq nil path))
  10066. (unless (> width 0)
  10067. (user-error "Argument `width' must be positive"))
  10068. (setq separator (or separator "/"))
  10069. (let* ((org-odd-levels-only nil)
  10070. (fpath (concat
  10071. prefix (and prefix path separator)
  10072. (mapconcat
  10073. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10074. (cl-loop for head in path
  10075. for n from 0
  10076. collect (org-add-props
  10077. head nil 'face
  10078. (nth (% n org-n-level-faces) org-level-faces)))
  10079. separator))))
  10080. (when (> (length fpath) width)
  10081. (if (< width 7)
  10082. ;; It's unlikely that `width' will be this small, but don't
  10083. ;; waste characters by adding ".." if it is.
  10084. (setq fpath (substring fpath 0 width))
  10085. (setf (substring fpath (- width 2)) "..")))
  10086. fpath))
  10087. (defun org-display-outline-path (&optional file current separator just-return-string)
  10088. "Display the current outline path in the echo area.
  10089. If FILE is non-nil, prepend the output with the file name.
  10090. If CURRENT is non-nil, append the current heading to the output.
  10091. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10092. the different parts of the path and defaults to \"/\".
  10093. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10094. (interactive "P")
  10095. (let* (case-fold-search
  10096. (bfn (buffer-file-name (buffer-base-buffer)))
  10097. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10098. res)
  10099. (when current (setq path (append path
  10100. (save-excursion
  10101. (org-back-to-heading t)
  10102. (when (looking-at org-complex-heading-regexp)
  10103. (list (match-string 4)))))))
  10104. (setq res
  10105. (org-format-outline-path
  10106. path
  10107. (1- (frame-width))
  10108. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10109. separator))
  10110. (if just-return-string
  10111. (org-no-properties res)
  10112. (org-unlogged-message "%s" res))))
  10113. (defvar org-refile-history nil
  10114. "History for refiling operations.")
  10115. (defvar org-after-refile-insert-hook nil
  10116. "Hook run after `org-refile' has inserted its stuff at the new location.
  10117. Note that this is still *before* the stuff will be removed from
  10118. the *old* location.")
  10119. (defvar org-capture-last-stored-marker)
  10120. (defvar org-refile-keep nil
  10121. "Non-nil means `org-refile' will copy instead of refile.")
  10122. (defun org-copy ()
  10123. "Like `org-refile', but copy."
  10124. (interactive)
  10125. (let ((org-refile-keep t))
  10126. (org-refile nil nil nil "Copy")))
  10127. (defun org-refile (&optional arg default-buffer rfloc msg)
  10128. "Move the entry or entries at point to another heading.
  10129. The list of target headings is compiled using the information in
  10130. `org-refile-targets', which see.
  10131. At the target location, the entry is filed as a subitem of the
  10132. target heading. Depending on `org-reverse-note-order', the new
  10133. subitem will either be the first or the last subitem.
  10134. If there is an active region, all entries in that region will be
  10135. refiled. However, the region must fulfill the requirement that
  10136. the first heading sets the top-level of the moved text.
  10137. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10138. location
  10139. and not actually move anything.
  10140. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10141. location where the last
  10142. refiling operation has put the subtree.
  10143. With a numeric prefix argument of `2', refile to the running clock.
  10144. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10145. being set to t and copy to the target location, don't move it.
  10146. Beware that keeping refiled entries may result in duplicated ID
  10147. properties.
  10148. RFLOC can be a refile location obtained in a different way.
  10149. MSG is a string to replace \"Refile\" in the default prompt with
  10150. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10151. See also `org-refile-use-outline-path'.
  10152. If you are using target caching (see `org-refile-use-cache'), you
  10153. have to clear the target cache in order to find new targets.
  10154. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10155. prefix argument (`C-u C-u C-u C-c C-w')."
  10156. (interactive "P")
  10157. (if (member arg '(0 (64)))
  10158. (org-refile-cache-clear)
  10159. (let* ((actionmsg (cond (msg msg)
  10160. ((equal arg 3) "Refile (and keep)")
  10161. (t "Refile")))
  10162. (regionp (org-region-active-p))
  10163. (region-start (and regionp (region-beginning)))
  10164. (region-end (and regionp (region-end)))
  10165. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10166. pos it nbuf file level reversed)
  10167. (setq last-command nil)
  10168. (when regionp
  10169. (goto-char region-start)
  10170. (or (bolp) (goto-char (point-at-bol)))
  10171. (setq region-start (point))
  10172. (unless (or (org-kill-is-subtree-p
  10173. (buffer-substring region-start region-end))
  10174. (prog1 org-refile-active-region-within-subtree
  10175. (let ((s (point-at-eol)))
  10176. (org-toggle-heading)
  10177. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10178. (user-error "The region is not a (sequence of) subtree(s)")))
  10179. (if (equal arg '(16))
  10180. (org-refile-goto-last-stored)
  10181. (when (or
  10182. (and (equal arg 2)
  10183. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10184. (prog1
  10185. (setq it (list (or org-clock-heading "running clock")
  10186. (buffer-file-name
  10187. (marker-buffer org-clock-hd-marker))
  10188. ""
  10189. (marker-position org-clock-hd-marker)))
  10190. (setq arg nil)))
  10191. (setq it
  10192. (or rfloc
  10193. (let (heading-text)
  10194. (save-excursion
  10195. (unless (and arg (listp arg))
  10196. (org-back-to-heading t)
  10197. (setq heading-text
  10198. (replace-regexp-in-string
  10199. org-bracket-link-regexp
  10200. "\\3"
  10201. (or (nth 4 (org-heading-components))
  10202. ""))))
  10203. (org-refile-get-location
  10204. (cond ((and arg (listp arg)) "Goto")
  10205. (regionp (concat actionmsg " region to"))
  10206. (t (concat actionmsg " subtree \""
  10207. heading-text "\" to")))
  10208. default-buffer
  10209. (and (not (equal '(4) arg))
  10210. org-refile-allow-creating-parent-nodes)))))))
  10211. (setq file (nth 1 it)
  10212. pos (nth 3 it))
  10213. (when (and (not arg)
  10214. pos
  10215. (equal (buffer-file-name) file)
  10216. (if regionp
  10217. (and (>= pos region-start)
  10218. (<= pos region-end))
  10219. (and (>= pos (point))
  10220. (< pos (save-excursion
  10221. (org-end-of-subtree t t))))))
  10222. (error "Cannot refile to position inside the tree or region"))
  10223. (setq nbuf (or (find-buffer-visiting file)
  10224. (find-file-noselect file)))
  10225. (if (and arg (not (equal arg 3)))
  10226. (progn
  10227. (pop-to-buffer-same-window nbuf)
  10228. (goto-char (cond (pos)
  10229. ((org-notes-order-reversed-p) (point-min))
  10230. (t (point-max))))
  10231. (org-show-context 'org-goto))
  10232. (if regionp
  10233. (progn
  10234. (org-kill-new (buffer-substring region-start region-end))
  10235. (org-save-markers-in-region region-start region-end))
  10236. (org-copy-subtree 1 nil t))
  10237. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10238. (find-file-noselect file)))
  10239. (setq reversed (org-notes-order-reversed-p))
  10240. (org-with-wide-buffer
  10241. (if pos
  10242. (progn
  10243. (goto-char pos)
  10244. (setq level (org-get-valid-level (funcall outline-level) 1))
  10245. (goto-char
  10246. (if reversed
  10247. (or (outline-next-heading) (point-max))
  10248. (or (save-excursion (org-get-next-sibling))
  10249. (org-end-of-subtree t t)
  10250. (point-max)))))
  10251. (setq level 1)
  10252. (if (not reversed)
  10253. (goto-char (point-max))
  10254. (goto-char (point-min))
  10255. (or (outline-next-heading) (goto-char (point-max)))))
  10256. (unless (bolp) (newline))
  10257. (org-paste-subtree level nil nil t)
  10258. (when org-log-refile
  10259. (org-add-log-setup 'refile nil nil org-log-refile)
  10260. (unless (eq org-log-refile 'note)
  10261. (save-excursion (org-add-log-note))))
  10262. (and org-auto-align-tags
  10263. (let ((org-loop-over-headlines-in-active-region nil))
  10264. (org-align-tags)))
  10265. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10266. :last-refile)))
  10267. (when bookmark-name
  10268. (with-demoted-errors
  10269. (bookmark-set bookmark-name))))
  10270. ;; If we are refiling for capture, make sure that the
  10271. ;; last-capture pointers point here
  10272. (when (bound-and-true-p org-capture-is-refiling)
  10273. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10274. :last-capture-marker)))
  10275. (when bookmark-name
  10276. (with-demoted-errors
  10277. (bookmark-set bookmark-name))))
  10278. (move-marker org-capture-last-stored-marker (point)))
  10279. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10280. (run-hooks 'org-after-refile-insert-hook)))
  10281. (unless org-refile-keep
  10282. (if regionp
  10283. (delete-region (point) (+ (point) (- region-end region-start)))
  10284. (org-preserve-local-variables
  10285. (delete-region
  10286. (and (org-back-to-heading t) (point))
  10287. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10288. (when (featurep 'org-inlinetask)
  10289. (org-inlinetask-remove-END-maybe))
  10290. (setq org-markers-to-move nil)
  10291. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10292. (defun org-refile-goto-last-stored ()
  10293. "Go to the location where the last refile was stored."
  10294. (interactive)
  10295. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10296. (message "This is the location of the last refile"))
  10297. (defun org-refile--get-location (refloc tbl)
  10298. "When user refile to REFLOC, find the associated target in TBL.
  10299. Also check `org-refile-target-table'."
  10300. (car (delq
  10301. nil
  10302. (mapcar
  10303. (lambda (r) (or (assoc r tbl)
  10304. (assoc r org-refile-target-table)))
  10305. (list (replace-regexp-in-string "/$" "" refloc)
  10306. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10307. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10308. "Prompt the user for a refile location, using PROMPT.
  10309. PROMPT should not be suffixed with a colon and a space, because
  10310. this function appends the default value from
  10311. `org-refile-history' automatically, if that is not empty."
  10312. (let ((org-refile-targets org-refile-targets)
  10313. (org-refile-use-outline-path org-refile-use-outline-path))
  10314. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10315. (unless org-refile-target-table
  10316. (user-error "No refile targets"))
  10317. (let* ((cbuf (current-buffer))
  10318. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10319. (cfunc (if (and org-refile-use-outline-path
  10320. org-outline-path-complete-in-steps)
  10321. #'org-olpath-completing-read
  10322. #'completing-read))
  10323. (extra (if org-refile-use-outline-path "/" ""))
  10324. (cbnex (concat (buffer-name) extra))
  10325. (filename (and cfn (expand-file-name cfn)))
  10326. (tbl (mapcar
  10327. (lambda (x)
  10328. (if (and (not (member org-refile-use-outline-path
  10329. '(file full-file-path)))
  10330. (not (equal filename (nth 1 x))))
  10331. (cons (concat (car x) extra " ("
  10332. (file-name-nondirectory (nth 1 x)) ")")
  10333. (cdr x))
  10334. (cons (concat (car x) extra) (cdr x))))
  10335. org-refile-target-table))
  10336. (completion-ignore-case t)
  10337. cdef
  10338. (prompt (concat prompt
  10339. (or (and (car org-refile-history)
  10340. (concat " (default " (car org-refile-history) ")"))
  10341. (and (assoc cbnex tbl) (setq cdef cbnex)
  10342. (concat " (default " cbnex ")"))) ": "))
  10343. pa answ parent-target child parent old-hist)
  10344. (setq old-hist org-refile-history)
  10345. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10346. nil 'org-refile-history (or cdef (car org-refile-history))))
  10347. (if (setq pa (org-refile--get-location answ tbl))
  10348. (progn
  10349. (org-refile-check-position pa)
  10350. (when (or (not org-refile-history)
  10351. (not (eq old-hist org-refile-history))
  10352. (not (equal (car pa) (car org-refile-history))))
  10353. (setq org-refile-history
  10354. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10355. org-refile-history
  10356. (cdr org-refile-history))))
  10357. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10358. (pop org-refile-history)))
  10359. pa)
  10360. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10361. (progn
  10362. (setq parent (match-string 1 answ)
  10363. child (match-string 2 answ))
  10364. (setq parent-target (org-refile--get-location parent tbl))
  10365. (when (and parent-target
  10366. (or (eq new-nodes t)
  10367. (and (eq new-nodes 'confirm)
  10368. (y-or-n-p (format "Create new node \"%s\"? "
  10369. child)))))
  10370. (org-refile-new-child parent-target child)))
  10371. (user-error "Invalid target location")))))
  10372. (declare-function org-string-nw-p "org-macs" (s))
  10373. (defun org-refile-check-position (refile-pointer)
  10374. "Check if the refile pointer matches the headline to which it points."
  10375. (let* ((file (nth 1 refile-pointer))
  10376. (re (nth 2 refile-pointer))
  10377. (pos (nth 3 refile-pointer))
  10378. buffer)
  10379. (if (and (not (markerp pos)) (not file))
  10380. (user-error "Please indicate a target file in the refile path")
  10381. (when (org-string-nw-p re)
  10382. (setq buffer (if (markerp pos)
  10383. (marker-buffer pos)
  10384. (or (find-buffer-visiting file)
  10385. (find-file-noselect file))))
  10386. (with-current-buffer buffer
  10387. (org-with-wide-buffer
  10388. (goto-char pos)
  10389. (beginning-of-line 1)
  10390. (unless (looking-at-p re)
  10391. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10392. (defun org-refile-new-child (parent-target child)
  10393. "Use refile target PARENT-TARGET to add new CHILD below it."
  10394. (unless parent-target
  10395. (error "Cannot find parent for new node"))
  10396. (let ((file (nth 1 parent-target))
  10397. (pos (nth 3 parent-target))
  10398. level)
  10399. (with-current-buffer (or (find-buffer-visiting file)
  10400. (find-file-noselect file))
  10401. (org-with-wide-buffer
  10402. (if pos
  10403. (goto-char pos)
  10404. (goto-char (point-max))
  10405. (unless (bolp) (newline)))
  10406. (when (looking-at org-outline-regexp)
  10407. (setq level (funcall outline-level))
  10408. (org-end-of-subtree t t))
  10409. (org-back-over-empty-lines)
  10410. (insert "\n" (make-string
  10411. (if pos (org-get-valid-level level 1) 1) ?*)
  10412. " " child "\n")
  10413. (beginning-of-line 0)
  10414. (list (concat (car parent-target) "/" child) file "" (point))))))
  10415. (defun org-olpath-completing-read (prompt collection &rest args)
  10416. "Read an outline path like a file name."
  10417. (let ((thetable collection))
  10418. (apply #'completing-read
  10419. prompt
  10420. (lambda (string predicate &optional flag)
  10421. (cond
  10422. ((eq flag nil) (try-completion string thetable))
  10423. ((eq flag t)
  10424. (let ((l (length string)))
  10425. (mapcar (lambda (x)
  10426. (let ((r (substring x l))
  10427. (f (if (string-match " ([^)]*)$" x)
  10428. (match-string 0 x)
  10429. "")))
  10430. (if (string-match "/" r)
  10431. (concat string (substring r 0 (match-end 0)) f)
  10432. x)))
  10433. (all-completions string thetable predicate))))
  10434. ;; Exact match?
  10435. ((eq flag 'lambda) (assoc string thetable))))
  10436. args)))
  10437. ;;;; Dynamic blocks
  10438. (defun org-find-dblock (name)
  10439. "Find the first dynamic block with name NAME in the buffer.
  10440. If not found, stay at current position and return nil."
  10441. (let ((case-fold-search t) pos)
  10442. (save-excursion
  10443. (goto-char (point-min))
  10444. (setq pos (and (re-search-forward
  10445. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10446. (match-beginning 0))))
  10447. (when pos (goto-char pos))
  10448. pos))
  10449. (defun org-create-dblock (plist)
  10450. "Create a dynamic block section, with parameters taken from PLIST.
  10451. PLIST must contain a :name entry which is used as the name of the block."
  10452. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10453. (end-of-line 1)
  10454. (newline))
  10455. (let ((col (current-column))
  10456. (name (plist-get plist :name)))
  10457. (insert "#+BEGIN: " name)
  10458. (while plist
  10459. (if (eq (car plist) :name)
  10460. (setq plist (cddr plist))
  10461. (insert " " (prin1-to-string (pop plist)))))
  10462. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10463. (beginning-of-line -2)))
  10464. (defun org-prepare-dblock ()
  10465. "Prepare dynamic block for refresh.
  10466. This empties the block, puts the cursor at the insert position and returns
  10467. the property list including an extra property :name with the block name."
  10468. (unless (looking-at org-dblock-start-re)
  10469. (user-error "Not at a dynamic block"))
  10470. (let* ((begdel (1+ (match-end 0)))
  10471. (name (org-no-properties (match-string 1)))
  10472. (params (append (list :name name)
  10473. (read (concat "(" (match-string 3) ")")))))
  10474. (save-excursion
  10475. (beginning-of-line 1)
  10476. (skip-chars-forward " \t")
  10477. (setq params (plist-put params :indentation-column (current-column))))
  10478. (unless (re-search-forward org-dblock-end-re nil t)
  10479. (error "Dynamic block not terminated"))
  10480. (setq params
  10481. (append params
  10482. (list :content (buffer-substring
  10483. begdel (match-beginning 0)))))
  10484. (delete-region begdel (match-beginning 0))
  10485. (goto-char begdel)
  10486. (open-line 1)
  10487. params))
  10488. (defun org-map-dblocks (&optional command)
  10489. "Apply COMMAND to all dynamic blocks in the current buffer.
  10490. If COMMAND is not given, use `org-update-dblock'."
  10491. (let ((cmd (or command 'org-update-dblock)))
  10492. (save-excursion
  10493. (goto-char (point-min))
  10494. (while (re-search-forward org-dblock-start-re nil t)
  10495. (goto-char (match-beginning 0))
  10496. (save-excursion
  10497. (condition-case nil
  10498. (funcall cmd)
  10499. (error (message "Error during update of dynamic block"))))
  10500. (unless (re-search-forward org-dblock-end-re nil t)
  10501. (error "Dynamic block not terminated"))))))
  10502. (defun org-dblock-update (&optional arg)
  10503. "User command for updating dynamic blocks.
  10504. Update the dynamic block at point. With prefix ARG, update all dynamic
  10505. blocks in the buffer."
  10506. (interactive "P")
  10507. (if arg
  10508. (org-update-all-dblocks)
  10509. (or (looking-at org-dblock-start-re)
  10510. (org-beginning-of-dblock))
  10511. (org-update-dblock)))
  10512. (defun org-update-dblock ()
  10513. "Update the dynamic block at point.
  10514. This means to empty the block, parse for parameters and then call
  10515. the correct writing function."
  10516. (interactive)
  10517. (save-excursion
  10518. (let* ((win (selected-window))
  10519. (pos (point))
  10520. (line (org-current-line))
  10521. (params (org-prepare-dblock))
  10522. (name (plist-get params :name))
  10523. (indent (plist-get params :indentation-column))
  10524. (cmd (intern (concat "org-dblock-write:" name))))
  10525. (message "Updating dynamic block `%s' at line %d..." name line)
  10526. (funcall cmd params)
  10527. (message "Updating dynamic block `%s' at line %d...done" name line)
  10528. (goto-char pos)
  10529. (when (and indent (> indent 0))
  10530. (setq indent (make-string indent ?\ ))
  10531. (save-excursion
  10532. (select-window win)
  10533. (org-beginning-of-dblock)
  10534. (forward-line 1)
  10535. (while (not (looking-at org-dblock-end-re))
  10536. (insert indent)
  10537. (beginning-of-line 2))
  10538. (when (looking-at org-dblock-end-re)
  10539. (and (looking-at "[ \t]+")
  10540. (replace-match ""))
  10541. (insert indent)))))))
  10542. (defun org-beginning-of-dblock ()
  10543. "Find the beginning of the dynamic block at point.
  10544. Error if there is no such block at point."
  10545. (let ((pos (point))
  10546. beg)
  10547. (end-of-line 1)
  10548. (if (and (re-search-backward org-dblock-start-re nil t)
  10549. (setq beg (match-beginning 0))
  10550. (re-search-forward org-dblock-end-re nil t)
  10551. (> (match-end 0) pos))
  10552. (goto-char beg)
  10553. (goto-char pos)
  10554. (error "Not in a dynamic block"))))
  10555. (defun org-update-all-dblocks ()
  10556. "Update all dynamic blocks in the buffer.
  10557. This function can be used in a hook."
  10558. (interactive)
  10559. (when (derived-mode-p 'org-mode)
  10560. (org-map-dblocks 'org-update-dblock)))
  10561. ;;;; Completion
  10562. (declare-function org-export-backend-options "ox" (cl-x) t)
  10563. (defun org-get-export-keywords ()
  10564. "Return a list of all currently understood export keywords.
  10565. Export keywords include options, block names, attributes and
  10566. keywords relative to each registered export back-end."
  10567. (let (keywords)
  10568. (dolist (backend
  10569. (bound-and-true-p org-export-registered-backends)
  10570. (delq nil keywords))
  10571. ;; Back-end name (for keywords, like #+LATEX:)
  10572. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10573. (dolist (option-entry (org-export-backend-options backend))
  10574. ;; Back-end options.
  10575. (push (nth 1 option-entry) keywords)))))
  10576. (defconst org-options-keywords
  10577. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10578. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10579. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10580. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10581. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10582. (defcustom org-structure-template-alist
  10583. '(("a" . "export ascii")
  10584. ("c" . "center")
  10585. ("C" . "comment")
  10586. ("e" . "example")
  10587. ("E" . "export")
  10588. ("h" . "export html")
  10589. ("l" . "export latex")
  10590. ("q" . "quote")
  10591. ("s" . "src")
  10592. ("v" . "verse"))
  10593. "An alist of keys and block types.
  10594. `org-insert-structure-template' will display a menu with this
  10595. list of templates to choose from. The block type is inserted,
  10596. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10597. The menu keys are defined by the car of each entry in this alist.
  10598. If two entries have the keys \"a\" and \"aa\" respectively, the
  10599. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10600. latter will be inserted by typing \"aa\". If an entry with the
  10601. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10602. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10603. block can be inserted by pressing TAB after the string \"<KEY\"."
  10604. :group 'org-edit-structure
  10605. :type '(repeat
  10606. (cons (string :tag "Key")
  10607. (string :tag "Template")))
  10608. :package-version '(Org . "9.2"))
  10609. (defun org--check-org-structure-template-alist (&optional checklist)
  10610. "Check whether `org-structure-template-alist' is set up correctly.
  10611. In particular, check if the Org 9.2 format is used as opposed to
  10612. previous format.
  10613. "
  10614. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  10615. (or (eval checklist)
  10616. org-structure-template-alist))))
  10617. (when elm
  10618. (org-display-warning
  10619. (format "
  10620. Please update the entries of `%s'.
  10621. In Org 9.2 the format was changed from something like
  10622. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  10623. to something like
  10624. (\"s\" . \"src\")
  10625. Please refer to the documentation of `org-structure-template-alist'.
  10626. The following entries must be updated:
  10627. %s"
  10628. (or checklist 'org-structure-template-alist)
  10629. (pp-to-string elm))))))
  10630. (defun org--insert-structure-template-mks ()
  10631. "Present `org-structure-template-alist' with `org-mks'.
  10632. Menus are added if keys require more than one keystroke. Tabs
  10633. are added to single key entries when more than one stroke is
  10634. needed. Keys longer than two characters are reduced to two
  10635. characters."
  10636. (org--check-org-structure-template-alist)
  10637. (let* (case-fold-search
  10638. (templates (append org-structure-template-alist
  10639. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10640. (keys (mapcar #'car templates))
  10641. (start-letters
  10642. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10643. ;; Sort each element of `org-structure-template-alist' into
  10644. ;; sublists according to the first letter.
  10645. (superlist
  10646. (mapcar (lambda (letter)
  10647. (list letter
  10648. (cl-remove-if-not
  10649. (apply-partially #'string-match-p (concat "^" letter))
  10650. templates :key #'car)))
  10651. start-letters)))
  10652. (org-mks
  10653. (apply #'append
  10654. ;; Make an `org-mks' table. If only one element is
  10655. ;; present in a sublist, make it part of the top-menu,
  10656. ;; otherwise make a submenu according to the starting
  10657. ;; letter and populate it.
  10658. (mapcar (lambda (sublist)
  10659. (if (eq 1 (length (cadr sublist)))
  10660. (mapcar (lambda (elm)
  10661. (list (substring (car elm) 0 1)
  10662. (cdr elm) ""))
  10663. (cadr sublist))
  10664. ;; Create submenu.
  10665. (let* ((topkey (car sublist))
  10666. (elms (cadr sublist))
  10667. (keys (mapcar #'car elms))
  10668. (long (> (length elms) 3)))
  10669. (append
  10670. (list
  10671. ;; Make a description of the submenu.
  10672. (list topkey
  10673. (concat
  10674. (mapconcat #'cdr
  10675. (cl-subseq elms 0 (if long 3 (length elms)))
  10676. ", ")
  10677. (when long ", ..."))))
  10678. ;; List of entries in submenu.
  10679. (cl-mapcar #'list
  10680. (org--insert-structure-template-unique-keys keys)
  10681. (mapcar #'cdr elms)
  10682. (make-list (length elms) ""))))))
  10683. superlist))
  10684. "Select a key\n============"
  10685. "Key: ")))
  10686. (defun org--insert-structure-template-unique-keys (keys)
  10687. "Make a list of unique, two characters long elements from KEYS.
  10688. Elements of length one have a tab appended. Elements of length
  10689. two are kept as is. Longer elements are truncated to length two.
  10690. If an element cannot be made unique, an error is raised."
  10691. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10692. menu-keys)
  10693. (dolist (key orderd-keys)
  10694. (let ((potential-key
  10695. (cl-case (length key)
  10696. (1 (concat key "\t"))
  10697. (2 key)
  10698. (otherwise
  10699. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10700. (mapcar (apply-partially #'concat (substring key 0 1))
  10701. (split-string (substring key 1) "" t)))))))
  10702. (if (or (not potential-key) (assoc potential-key menu-keys))
  10703. (user-error "Could not make unique key for %s." key)
  10704. (push (cons potential-key key) menu-keys))))
  10705. (mapcar #'car
  10706. (cl-sort menu-keys #'<
  10707. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10708. (defun org-insert-structure-template (type)
  10709. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10710. Select a block from `org-structure-template-alist' then type
  10711. either RET, TAB or SPC to write the block type. With an active
  10712. region, wrap the region in the block. Otherwise, insert an empty
  10713. block."
  10714. (interactive
  10715. (list (pcase (org--insert-structure-template-mks)
  10716. (`("\t" . ,_) (read-string "Structure type: "))
  10717. (`(,_ ,choice . ,_) choice))))
  10718. (let* ((region? (use-region-p))
  10719. (region-start (and region? (region-beginning)))
  10720. (region-end (and region? (copy-marker (region-end))))
  10721. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  10722. (verbatim? (string-match-p
  10723. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10724. type)))
  10725. (when region? (goto-char region-start))
  10726. (let ((column (current-indentation)))
  10727. (if (save-excursion (skip-chars-backward " \t") (bolp))
  10728. (beginning-of-line)
  10729. (insert "\n"))
  10730. (save-excursion
  10731. (indent-to column)
  10732. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  10733. (when region?
  10734. (when verbatim? (org-escape-code-in-region (point) region-end))
  10735. (goto-char region-end)
  10736. ;; Ignore empty lines at the end of the region.
  10737. (skip-chars-backward " \r\t\n")
  10738. (end-of-line))
  10739. (unless (bolp) (insert "\n"))
  10740. (indent-to column)
  10741. (insert (format "#+end_%s" (car (split-string type))))
  10742. (if (looking-at "[ \t]*$") (replace-match "")
  10743. (insert "\n"))
  10744. (when (and (eobp) (not (bolp))) (insert "\n")))
  10745. (if extended? (end-of-line)
  10746. (forward-line)
  10747. (skip-chars-forward " \t")))))
  10748. ;;;; TODO, DEADLINE, Comments
  10749. (defun org-toggle-comment ()
  10750. "Change the COMMENT state of an entry."
  10751. (interactive)
  10752. (save-excursion
  10753. (org-back-to-heading)
  10754. (let ((case-fold-search nil))
  10755. (looking-at org-complex-heading-regexp))
  10756. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10757. (skip-chars-forward " \t")
  10758. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10759. (if (org-in-commented-heading-p t)
  10760. (delete-region (point)
  10761. (progn (search-forward " " (line-end-position) 'move)
  10762. (skip-chars-forward " \t")
  10763. (point)))
  10764. (insert org-comment-string)
  10765. (unless (eolp) (insert " ")))))
  10766. (defvar org-last-todo-state-is-todo nil
  10767. "This is non-nil when the last TODO state change led to a TODO state.
  10768. If the last change removed the TODO tag or switched to DONE, then
  10769. this is nil.")
  10770. (defvar org-todo-setup-filter-hook nil
  10771. "Hook for functions that pre-filter todo specs.
  10772. Each function takes a todo spec and returns either nil or the spec
  10773. transformed into canonical form." )
  10774. (defvar org-todo-get-default-hook nil
  10775. "Hook for functions that get a default item for todo.
  10776. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10777. nil or a string to be used for the todo mark." )
  10778. (defvar org-agenda-headline-snapshot-before-repeat)
  10779. (defun org-current-effective-time ()
  10780. "Return current time adjusted for `org-extend-today-until' variable."
  10781. (let* ((ct (org-current-time))
  10782. (dct (decode-time ct))
  10783. (ct1
  10784. (cond
  10785. (org-use-last-clock-out-time-as-effective-time
  10786. (or (org-clock-get-last-clock-out-time) ct))
  10787. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10788. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10789. (t ct))))
  10790. ct1))
  10791. (defun org-todo-yesterday (&optional arg)
  10792. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10793. (interactive "P")
  10794. (if (eq major-mode 'org-agenda-mode)
  10795. (apply 'org-agenda-todo-yesterday arg)
  10796. (let* ((org-use-effective-time t)
  10797. (hour (nth 2 (decode-time (org-current-time))))
  10798. (org-extend-today-until (1+ hour)))
  10799. (org-todo arg))))
  10800. (defvar org-block-entry-blocking ""
  10801. "First entry preventing the TODO state change.")
  10802. (defun org-cancel-repeater ()
  10803. "Cancel a repeater by setting its numeric value to zero."
  10804. (interactive)
  10805. (save-excursion
  10806. (org-back-to-heading t)
  10807. (let ((bound1 (point))
  10808. (bound0 (save-excursion (outline-next-heading) (point))))
  10809. (when (and (re-search-forward
  10810. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10811. org-deadline-time-regexp "\\)\\|\\("
  10812. org-ts-regexp "\\)")
  10813. bound0 t)
  10814. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10815. bound1 t))
  10816. (replace-match "0" t nil nil 1)))))
  10817. (defvar org-state)
  10818. (defvar org-blocked-by-checkboxes)
  10819. (defun org-todo (&optional arg)
  10820. "Change the TODO state of an item.
  10821. The state of an item is given by a keyword at the start of the heading,
  10822. like
  10823. *** TODO Write paper
  10824. *** DONE Call mom
  10825. The different keywords are specified in the variable `org-todo-keywords'.
  10826. By default the available states are \"TODO\" and \"DONE\". So, for this
  10827. example: when the item starts with TODO, it is changed to DONE.
  10828. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10829. DONE are present, add TODO at the beginning of the heading.
  10830. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10831. state.
  10832. With numeric prefix ARG, switch to that state.
  10833. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10834. next set of TODO \
  10835. keywords (nextset).
  10836. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10837. prefix, circumvent any state blocking.
  10838. With a numeric prefix arg of 0, inhibit note taking for the change.
  10839. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10840. When called through ELisp, arg is also interpreted in the following way:
  10841. `none' -> empty state
  10842. \"\" -> switch to empty state
  10843. `done' -> switch to DONE
  10844. `nextset' -> switch to the next set of keywords
  10845. `previousset' -> switch to the previous set of keywords
  10846. \"WAITING\" -> switch to the specified keyword, but only if it
  10847. really is a member of `org-todo-keywords'."
  10848. (interactive "P")
  10849. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10850. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10851. 'region-start-level 'region))
  10852. org-loop-over-headlines-in-active-region)
  10853. (org-map-entries
  10854. `(org-todo ,arg)
  10855. org-loop-over-headlines-in-active-region
  10856. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10857. (when (equal arg '(16)) (setq arg 'nextset))
  10858. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10859. (let ((org-blocker-hook org-blocker-hook)
  10860. commentp
  10861. case-fold-search)
  10862. (when (equal arg '(64))
  10863. (setq arg nil org-blocker-hook nil))
  10864. (when (and org-blocker-hook
  10865. (or org-inhibit-blocking
  10866. (org-entry-get nil "NOBLOCKING")))
  10867. (setq org-blocker-hook nil))
  10868. (save-excursion
  10869. (catch 'exit
  10870. (org-back-to-heading t)
  10871. (when (org-in-commented-heading-p t)
  10872. (org-toggle-comment)
  10873. (setq commentp t))
  10874. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10875. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10876. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10877. (let* ((match-data (match-data))
  10878. (startpos (copy-marker (line-beginning-position)))
  10879. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10880. (org-log-done org-log-done)
  10881. (org-log-repeat org-log-repeat)
  10882. (org-todo-log-states org-todo-log-states)
  10883. (org-inhibit-logging
  10884. (if (equal arg 0)
  10885. (progn (setq arg nil) 'note) org-inhibit-logging))
  10886. (this (match-string 1))
  10887. (hl-pos (match-beginning 0))
  10888. (head (org-get-todo-sequence-head this))
  10889. (ass (assoc head org-todo-kwd-alist))
  10890. (interpret (nth 1 ass))
  10891. (done-word (nth 3 ass))
  10892. (final-done-word (nth 4 ass))
  10893. (org-last-state (or this ""))
  10894. (completion-ignore-case t)
  10895. (member (member this org-todo-keywords-1))
  10896. (tail (cdr member))
  10897. (org-state (cond
  10898. ((and org-todo-key-trigger
  10899. (or (and (equal arg '(4))
  10900. (eq org-use-fast-todo-selection 'prefix))
  10901. (and (not arg) org-use-fast-todo-selection
  10902. (not (eq org-use-fast-todo-selection
  10903. 'prefix)))))
  10904. ;; Use fast selection.
  10905. (org-fast-todo-selection))
  10906. ((and (equal arg '(4))
  10907. (or (not org-use-fast-todo-selection)
  10908. (not org-todo-key-trigger)))
  10909. ;; Read a state with completion.
  10910. (completing-read
  10911. "State: " (mapcar #'list org-todo-keywords-1)
  10912. nil t))
  10913. ((eq arg 'right)
  10914. (if this
  10915. (if tail (car tail) nil)
  10916. (car org-todo-keywords-1)))
  10917. ((eq arg 'left)
  10918. (unless (equal member org-todo-keywords-1)
  10919. (if this
  10920. (nth (- (length org-todo-keywords-1)
  10921. (length tail) 2)
  10922. org-todo-keywords-1)
  10923. (org-last org-todo-keywords-1))))
  10924. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10925. (setq arg nil))) ;hack to fall back to cycling
  10926. (arg
  10927. ;; User or caller requests a specific state.
  10928. (cond
  10929. ((equal arg "") nil)
  10930. ((eq arg 'none) nil)
  10931. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10932. ((eq arg 'nextset)
  10933. (or (car (cdr (member head org-todo-heads)))
  10934. (car org-todo-heads)))
  10935. ((eq arg 'previousset)
  10936. (let ((org-todo-heads (reverse org-todo-heads)))
  10937. (or (car (cdr (member head org-todo-heads)))
  10938. (car org-todo-heads))))
  10939. ((car (member arg org-todo-keywords-1)))
  10940. ((stringp arg)
  10941. (user-error "State `%s' not valid in this file" arg))
  10942. ((nth (1- (prefix-numeric-value arg))
  10943. org-todo-keywords-1))))
  10944. ((null member) (or head (car org-todo-keywords-1)))
  10945. ((equal this final-done-word) nil) ;-> make empty
  10946. ((null tail) nil) ;-> first entry
  10947. ((memq interpret '(type priority))
  10948. (if (eq this-command last-command)
  10949. (car tail)
  10950. (if (> (length tail) 0)
  10951. (or done-word (car org-done-keywords))
  10952. nil)))
  10953. (t
  10954. (car tail))))
  10955. (org-state (or
  10956. (run-hook-with-args-until-success
  10957. 'org-todo-get-default-hook org-state org-last-state)
  10958. org-state))
  10959. (next (if org-state (concat " " org-state " ") " "))
  10960. (change-plist (list :type 'todo-state-change :from this :to org-state
  10961. :position startpos))
  10962. dolog now-done-p)
  10963. (when org-blocker-hook
  10964. (let (org-blocked-by-checkboxes block-reason)
  10965. (setq org-last-todo-state-is-todo
  10966. (not (member this org-done-keywords)))
  10967. (unless (save-excursion
  10968. (save-match-data
  10969. (org-with-wide-buffer
  10970. (run-hook-with-args-until-failure
  10971. 'org-blocker-hook change-plist))))
  10972. (setq block-reason (if org-blocked-by-checkboxes
  10973. "contained checkboxes"
  10974. (format "\"%s\"" org-block-entry-blocking)))
  10975. (if (called-interactively-p 'interactive)
  10976. (user-error "TODO state change from %s to %s blocked (by %s)"
  10977. this org-state block-reason)
  10978. ;; Fail silently.
  10979. (message "TODO state change from %s to %s blocked (by %s)"
  10980. this org-state block-reason)
  10981. (throw 'exit nil)))))
  10982. (store-match-data match-data)
  10983. (replace-match next t t)
  10984. (cond ((equal this org-state)
  10985. (message "TODO state was already %s" (org-trim next)))
  10986. ((not (pos-visible-in-window-p hl-pos))
  10987. (message "TODO state changed to %s" (org-trim next))))
  10988. (unless head
  10989. (setq head (org-get-todo-sequence-head org-state)
  10990. ass (assoc head org-todo-kwd-alist)
  10991. interpret (nth 1 ass)
  10992. done-word (nth 3 ass)
  10993. final-done-word (nth 4 ass)))
  10994. (when (memq arg '(nextset previousset))
  10995. (message "Keyword-Set %d/%d: %s"
  10996. (- (length org-todo-sets) -1
  10997. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10998. (length org-todo-sets)
  10999. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11000. (setq org-last-todo-state-is-todo
  11001. (not (member org-state org-done-keywords)))
  11002. (setq now-done-p (and (member org-state org-done-keywords)
  11003. (not (member this org-done-keywords))))
  11004. (and logging (org-local-logging logging))
  11005. (when (and (or org-todo-log-states org-log-done)
  11006. (not (eq org-inhibit-logging t))
  11007. (not (memq arg '(nextset previousset))))
  11008. ;; We need to look at recording a time and note.
  11009. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11010. (nth 2 (assoc this org-todo-log-states))))
  11011. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11012. (setq dolog 'time))
  11013. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11014. (and org-state
  11015. (member org-state org-not-done-keywords)
  11016. (not (member this org-not-done-keywords))))
  11017. ;; This is now a todo state and was not one before
  11018. ;; If there was a CLOSED time stamp, get rid of it.
  11019. (org-add-planning-info nil nil 'closed))
  11020. (when (and now-done-p org-log-done)
  11021. ;; It is now done, and it was not done before.
  11022. (org-add-planning-info 'closed (org-current-effective-time))
  11023. (when (and (not dolog) (eq 'note org-log-done))
  11024. (org-add-log-setup 'done org-state this 'note)))
  11025. (when (and org-state dolog)
  11026. ;; This is a non-nil state, and we need to log it.
  11027. (org-add-log-setup 'state org-state this dolog)))
  11028. ;; Fixup tag positioning.
  11029. (org-todo-trigger-tag-changes org-state)
  11030. (when org-auto-align-tags (org-align-tags))
  11031. (when org-provide-todo-statistics
  11032. (org-update-parent-todo-statistics))
  11033. (org-clock-out-if-current)
  11034. (run-hooks 'org-after-todo-state-change-hook)
  11035. (when (and arg (not (member org-state org-done-keywords)))
  11036. (setq head (org-get-todo-sequence-head org-state)))
  11037. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11038. ;; Do we need to trigger a repeat?
  11039. (when now-done-p
  11040. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11041. ;; This is for the agenda, take a snapshot of the headline.
  11042. (save-match-data
  11043. (setq org-agenda-headline-snapshot-before-repeat
  11044. (org-get-heading))))
  11045. (org-auto-repeat-maybe org-state))
  11046. ;; Fixup cursor location if close to the keyword.
  11047. (when (and (outline-on-heading-p)
  11048. (not (bolp))
  11049. (save-excursion (beginning-of-line 1)
  11050. (looking-at org-todo-line-regexp))
  11051. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11052. (goto-char (or (match-end 2) (match-end 1)))
  11053. (and (looking-at " ") (just-one-space)))
  11054. (when org-trigger-hook
  11055. (save-excursion
  11056. (run-hook-with-args 'org-trigger-hook change-plist)))
  11057. (when commentp (org-toggle-comment))))))))
  11058. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11059. "Block turning an entry into a TODO, using the hierarchy.
  11060. This checks whether the current task should be blocked from state
  11061. changes. Such blocking occurs when:
  11062. 1. The task has children which are not all in a completed state.
  11063. 2. A task has a parent with the property :ORDERED:, and there
  11064. are siblings prior to the current task with incomplete
  11065. status.
  11066. 3. The parent of the task is blocked because it has siblings that should
  11067. be done first, or is child of a block grandparent TODO entry."
  11068. (if (not org-enforce-todo-dependencies)
  11069. t ; if locally turned off don't block
  11070. (catch 'dont-block
  11071. ;; If this is not a todo state change, or if this entry is already DONE,
  11072. ;; do not block
  11073. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11074. (member (plist-get change-plist :from)
  11075. (cons 'done org-done-keywords))
  11076. (member (plist-get change-plist :to)
  11077. (cons 'todo org-not-done-keywords))
  11078. (not (plist-get change-plist :to)))
  11079. (throw 'dont-block t))
  11080. ;; If this task has children, and any are undone, it's blocked
  11081. (save-excursion
  11082. (org-back-to-heading t)
  11083. (let ((this-level (funcall outline-level)))
  11084. (outline-next-heading)
  11085. (let ((child-level (funcall outline-level)))
  11086. (while (and (not (eobp))
  11087. (> child-level this-level))
  11088. ;; this todo has children, check whether they are all
  11089. ;; completed
  11090. (when (and (not (org-entry-is-done-p))
  11091. (org-entry-is-todo-p))
  11092. (setq org-block-entry-blocking (org-get-heading))
  11093. (throw 'dont-block nil))
  11094. (outline-next-heading)
  11095. (setq child-level (funcall outline-level))))))
  11096. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11097. ;; any previous siblings are undone, it's blocked
  11098. (save-excursion
  11099. (org-back-to-heading t)
  11100. (let* ((pos (point))
  11101. (parent-pos (and (org-up-heading-safe) (point)))
  11102. (case-fold-search nil))
  11103. (unless parent-pos (throw 'dont-block t)) ; no parent
  11104. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11105. (forward-line 1)
  11106. (re-search-forward org-not-done-heading-regexp pos t))
  11107. (setq org-block-entry-blocking (match-string 0))
  11108. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11109. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11110. (while t
  11111. (goto-char parent-pos)
  11112. (unless (looking-at org-not-done-heading-regexp)
  11113. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11114. (setq pos (point))
  11115. (setq parent-pos (and (org-up-heading-safe) (point)))
  11116. (unless parent-pos (throw 'dont-block t)) ; no parent
  11117. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11118. (forward-line 1)
  11119. (re-search-forward org-not-done-heading-regexp pos t)
  11120. (setq org-block-entry-blocking (org-get-heading)))
  11121. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11122. (defcustom org-track-ordered-property-with-tag nil
  11123. "Should the ORDERED property also be shown as a tag?
  11124. The ORDERED property decides if an entry should require subtasks to be
  11125. completed in sequence. Since a property is not very visible, setting
  11126. this option means that toggling the ORDERED property with the command
  11127. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11128. not relevant for the behavior, but it makes things more visible.
  11129. Note that toggling the tag with tags commands will not change the property
  11130. and therefore not influence behavior!
  11131. This can be t, meaning the tag ORDERED should be used, It can also be a
  11132. string to select a different tag for this task."
  11133. :group 'org-todo
  11134. :type '(choice
  11135. (const :tag "No tracking" nil)
  11136. (const :tag "Track with ORDERED tag" t)
  11137. (string :tag "Use other tag")))
  11138. (defun org-toggle-ordered-property ()
  11139. "Toggle the ORDERED property of the current entry.
  11140. For better visibility, you can track the value of this property with a tag.
  11141. See variable `org-track-ordered-property-with-tag'."
  11142. (interactive)
  11143. (let* ((t1 org-track-ordered-property-with-tag)
  11144. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11145. (save-excursion
  11146. (org-back-to-heading)
  11147. (if (org-entry-get nil "ORDERED")
  11148. (progn
  11149. (org-delete-property "ORDERED")
  11150. (and tag (org-toggle-tag tag 'off))
  11151. (message "Subtasks can be completed in arbitrary order"))
  11152. (org-entry-put nil "ORDERED" "t")
  11153. (and tag (org-toggle-tag tag 'on))
  11154. (message "Subtasks must be completed in sequence")))))
  11155. (defun org-block-todo-from-checkboxes (change-plist)
  11156. "Block turning an entry into a TODO, using checkboxes.
  11157. This checks whether the current task should be blocked from state
  11158. changes because there are unchecked boxes in this entry."
  11159. (if (not org-enforce-todo-checkbox-dependencies)
  11160. t ; if locally turned off don't block
  11161. (catch 'dont-block
  11162. ;; If this is not a todo state change, or if this entry is already DONE,
  11163. ;; do not block
  11164. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11165. (member (plist-get change-plist :from)
  11166. (cons 'done org-done-keywords))
  11167. (member (plist-get change-plist :to)
  11168. (cons 'todo org-not-done-keywords))
  11169. (not (plist-get change-plist :to)))
  11170. (throw 'dont-block t))
  11171. ;; If this task has checkboxes that are not checked, it's blocked
  11172. (save-excursion
  11173. (org-back-to-heading t)
  11174. (let ((beg (point)) end)
  11175. (outline-next-heading)
  11176. (setq end (point))
  11177. (goto-char beg)
  11178. (when (org-list-search-forward
  11179. (concat (org-item-beginning-re)
  11180. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11181. "\\[[- ]\\]")
  11182. end t)
  11183. (when (boundp 'org-blocked-by-checkboxes)
  11184. (setq org-blocked-by-checkboxes t))
  11185. (throw 'dont-block nil))))
  11186. t))) ; do not block
  11187. (defun org-entry-blocked-p ()
  11188. "Non-nil if entry at point is blocked."
  11189. (and (not (org-entry-get nil "NOBLOCKING"))
  11190. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11191. (not (run-hook-with-args-until-failure
  11192. 'org-blocker-hook
  11193. (list :type 'todo-state-change
  11194. :position (point)
  11195. :from 'todo
  11196. :to 'done)))))
  11197. (defun org-update-statistics-cookies (all)
  11198. "Update the statistics cookie, either from TODO or from checkboxes.
  11199. This should be called with the cursor in a line with a statistics
  11200. cookie. When called with a \\[universal-argument] prefix, update
  11201. all statistics cookies in the buffer."
  11202. (interactive "P")
  11203. (if all
  11204. (progn
  11205. (org-update-checkbox-count 'all)
  11206. (org-map-entries 'org-update-parent-todo-statistics))
  11207. (if (not (org-at-heading-p))
  11208. (org-update-checkbox-count)
  11209. (let ((pos (point-marker))
  11210. end l1 l2)
  11211. (ignore-errors (org-back-to-heading t))
  11212. (if (not (org-at-heading-p))
  11213. (org-update-checkbox-count)
  11214. (setq l1 (org-outline-level))
  11215. (setq end (save-excursion
  11216. (outline-next-heading)
  11217. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11218. (point)))
  11219. (if (and (save-excursion
  11220. (re-search-forward
  11221. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11222. (not (save-excursion (re-search-forward
  11223. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11224. (org-update-checkbox-count)
  11225. (if (and l2 (> l2 l1))
  11226. (progn
  11227. (goto-char end)
  11228. (org-update-parent-todo-statistics))
  11229. (goto-char pos)
  11230. (beginning-of-line 1)
  11231. (while (re-search-forward
  11232. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11233. (point-at-eol) t)
  11234. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11235. (goto-char pos)
  11236. (move-marker pos nil)))))
  11237. (defvar org-entry-property-inherited-from) ;; defined below
  11238. (defun org-update-parent-todo-statistics ()
  11239. "Update any statistics cookie in the parent of the current headline.
  11240. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11241. the entire subtree and this will travel up the hierarchy and update
  11242. statistics everywhere."
  11243. (let* ((prop (save-excursion (org-up-heading-safe)
  11244. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11245. (recursive (or (not org-hierarchical-todo-statistics)
  11246. (and prop (string-match "\\<recursive\\>" prop))))
  11247. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11248. 0))
  11249. (first t)
  11250. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11251. level ltoggle l1 new ndel
  11252. (cnt-all 0) (cnt-done 0) is-percent kwd
  11253. checkbox-beg cookie-present)
  11254. (catch 'exit
  11255. (save-excursion
  11256. (beginning-of-line 1)
  11257. (setq ltoggle (funcall outline-level))
  11258. ;; Three situations are to consider:
  11259. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11260. ;; to the top-level ancestor on the headline;
  11261. ;; 2. If parent has "recursive" property, repeat up to the
  11262. ;; headline setting that property, taking inheritance into
  11263. ;; account;
  11264. ;; 3. Else, move up to direct parent and proceed only once.
  11265. (while (and (setq level (org-up-heading-safe))
  11266. (or recursive first)
  11267. (>= (point) lim))
  11268. (setq first nil cookie-present nil)
  11269. (unless (and level
  11270. (not (string-match
  11271. "\\<checkbox\\>"
  11272. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11273. "")))))
  11274. (throw 'exit nil))
  11275. (while (re-search-forward box-re (point-at-eol) t)
  11276. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11277. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11278. (save-match-data
  11279. (unless (outline-next-heading) (throw 'exit nil))
  11280. (while (and (looking-at org-complex-heading-regexp)
  11281. (> (setq l1 (length (match-string 1))) level))
  11282. (setq kwd (and (or recursive (= l1 ltoggle))
  11283. (match-string 2)))
  11284. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11285. (and (eq org-provide-todo-statistics t)
  11286. (or (member kwd org-done-keywords)))
  11287. (and (listp org-provide-todo-statistics)
  11288. (stringp (car org-provide-todo-statistics))
  11289. (or (member kwd org-provide-todo-statistics)
  11290. (member kwd org-done-keywords)))
  11291. (and (listp org-provide-todo-statistics)
  11292. (listp (car org-provide-todo-statistics))
  11293. (or (member kwd (car org-provide-todo-statistics))
  11294. (and (member kwd org-done-keywords)
  11295. (member kwd (cadr org-provide-todo-statistics))))))
  11296. (setq cnt-all (1+ cnt-all))
  11297. (and (eq org-provide-todo-statistics t)
  11298. kwd
  11299. (setq cnt-all (1+ cnt-all))))
  11300. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11301. (member kwd org-done-keywords))
  11302. (and (listp org-provide-todo-statistics)
  11303. (listp (car org-provide-todo-statistics))
  11304. (member kwd org-done-keywords)
  11305. (member kwd (cadr org-provide-todo-statistics)))
  11306. (and (listp org-provide-todo-statistics)
  11307. (stringp (car org-provide-todo-statistics))
  11308. (member kwd org-done-keywords)))
  11309. (setq cnt-done (1+ cnt-done)))
  11310. (outline-next-heading)))
  11311. (setq new
  11312. (if is-percent
  11313. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11314. (max 1 cnt-all)))
  11315. (format "[%d/%d]" cnt-done cnt-all))
  11316. ndel (- (match-end 0) checkbox-beg))
  11317. (goto-char checkbox-beg)
  11318. (insert new)
  11319. (delete-region (point) (+ (point) ndel))
  11320. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11321. (when cookie-present
  11322. (run-hook-with-args 'org-after-todo-statistics-hook
  11323. cnt-done (- cnt-all cnt-done))))))
  11324. (run-hooks 'org-todo-statistics-hook)))
  11325. (defvar org-after-todo-statistics-hook nil
  11326. "Hook that is called after a TODO statistics cookie has been updated.
  11327. Each function is called with two arguments: the number of not-done entries
  11328. and the number of done entries.
  11329. For example, the following function, when added to this hook, will switch
  11330. an entry to DONE when all children are done, and back to TODO when new
  11331. entries are set to a TODO status. Note that this hook is only called
  11332. when there is a statistics cookie in the headline!
  11333. (defun org-summary-todo (n-done n-not-done)
  11334. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11335. (let (org-log-done org-log-states) ; turn off logging
  11336. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11337. ")
  11338. (defvar org-todo-statistics-hook nil
  11339. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11340. This hook runs even if there is no statistics cookie present, in which case
  11341. `org-after-todo-statistics-hook' would not run.")
  11342. (defun org-todo-trigger-tag-changes (state)
  11343. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11344. (let ((l org-todo-state-tags-triggers)
  11345. changes)
  11346. (when (or (not state) (equal state ""))
  11347. (setq changes (append changes (cdr (assoc "" l)))))
  11348. (when (and (stringp state) (> (length state) 0))
  11349. (setq changes (append changes (cdr (assoc state l)))))
  11350. (when (member state org-not-done-keywords)
  11351. (setq changes (append changes (cdr (assq 'todo l)))))
  11352. (when (member state org-done-keywords)
  11353. (setq changes (append changes (cdr (assq 'done l)))))
  11354. (dolist (c changes)
  11355. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11356. (defun org-local-logging (value)
  11357. "Get logging settings from a property VALUE."
  11358. ;; Directly set the variables, they are already local.
  11359. (setq org-log-done nil
  11360. org-log-repeat nil
  11361. org-todo-log-states nil)
  11362. (dolist (w (split-string value))
  11363. (let (a)
  11364. (cond
  11365. ((setq a (assoc w org-startup-options))
  11366. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11367. (set (nth 1 a) (nth 2 a))))
  11368. ((setq a (org-extract-log-state-settings w))
  11369. (and (member (car a) org-todo-keywords-1)
  11370. (push a org-todo-log-states)))))))
  11371. (defun org-get-todo-sequence-head (kwd)
  11372. "Return the head of the TODO sequence to which KWD belongs.
  11373. If KWD is not set, check if there is a text property remembering the
  11374. right sequence."
  11375. (let (p)
  11376. (cond
  11377. ((not kwd)
  11378. (or (get-text-property (point-at-bol) 'org-todo-head)
  11379. (progn
  11380. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11381. nil (point-at-eol)))
  11382. (get-text-property p 'org-todo-head))))
  11383. ((not (member kwd org-todo-keywords-1))
  11384. (car org-todo-keywords-1))
  11385. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11386. (defun org-fast-todo-selection ()
  11387. "Fast TODO keyword selection with single keys.
  11388. Returns the new TODO keyword, or nil if no state change should occur."
  11389. (let* ((fulltable org-todo-key-alist)
  11390. (done-keywords org-done-keywords) ;; needed for the faces.
  11391. (maxlen (apply 'max (mapcar
  11392. (lambda (x)
  11393. (if (stringp (car x)) (string-width (car x)) 0))
  11394. fulltable)))
  11395. (expert nil)
  11396. (fwidth (+ maxlen 3 1 3))
  11397. (ncol (/ (- (window-width) 4) fwidth))
  11398. tg cnt e c tbl
  11399. groups ingroup)
  11400. (save-excursion
  11401. (save-window-excursion
  11402. (if expert
  11403. (set-buffer (get-buffer-create " *Org todo*"))
  11404. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11405. (erase-buffer)
  11406. (setq-local org-done-keywords done-keywords)
  11407. (setq tbl fulltable cnt 0)
  11408. (while (setq e (pop tbl))
  11409. (cond
  11410. ((equal e '(:startgroup))
  11411. (push '() groups) (setq ingroup t)
  11412. (unless (= cnt 0)
  11413. (setq cnt 0)
  11414. (insert "\n"))
  11415. (insert "{ "))
  11416. ((equal e '(:endgroup))
  11417. (setq ingroup nil cnt 0)
  11418. (insert "}\n"))
  11419. ((equal e '(:newline))
  11420. (unless (= cnt 0)
  11421. (setq cnt 0)
  11422. (insert "\n")
  11423. (setq e (car tbl))
  11424. (while (equal (car tbl) '(:newline))
  11425. (insert "\n")
  11426. (setq tbl (cdr tbl)))))
  11427. (t
  11428. (setq tg (car e) c (cdr e))
  11429. (when ingroup (push tg (car groups)))
  11430. (setq tg (org-add-props tg nil 'face
  11431. (org-get-todo-face tg)))
  11432. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11433. (insert "[" c "] " tg (make-string
  11434. (- fwidth 4 (length tg)) ?\ ))
  11435. (when (= (setq cnt (1+ cnt)) ncol)
  11436. (insert "\n")
  11437. (when ingroup (insert " "))
  11438. (setq cnt 0)))))
  11439. (insert "\n")
  11440. (goto-char (point-min))
  11441. (unless expert (org-fit-window-to-buffer))
  11442. (message "[a-z..]:Set [SPC]:clear")
  11443. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11444. (cond
  11445. ((or (= c ?\C-g)
  11446. (and (= c ?q) (not (rassoc c fulltable))))
  11447. (setq quit-flag t))
  11448. ((= c ?\ ) nil)
  11449. ((setq e (rassoc c fulltable) tg (car e))
  11450. tg)
  11451. (t (setq quit-flag t)))))))
  11452. (defun org-entry-is-todo-p ()
  11453. (member (org-get-todo-state) org-not-done-keywords))
  11454. (defun org-entry-is-done-p ()
  11455. (member (org-get-todo-state) org-done-keywords))
  11456. (defun org-get-todo-state ()
  11457. "Return the TODO keyword of the current subtree."
  11458. (save-excursion
  11459. (org-back-to-heading t)
  11460. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11461. (match-end 2)
  11462. (match-string 2))))
  11463. (defun org-at-date-range-p (&optional inactive-ok)
  11464. "Non-nil if point is inside a date range.
  11465. When optional argument INACTIVE-OK is non-nil, also consider
  11466. inactive time ranges.
  11467. When this function returns a non-nil value, match data is set
  11468. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11469. on INACTIVE-OK."
  11470. (interactive)
  11471. (save-excursion
  11472. (catch 'exit
  11473. (let ((pos (point)))
  11474. (skip-chars-backward "^[<\r\n")
  11475. (skip-chars-backward "<[")
  11476. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11477. (>= (match-end 0) pos)
  11478. (throw 'exit t))
  11479. (skip-chars-backward "^<[\r\n")
  11480. (skip-chars-backward "<[")
  11481. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11482. (>= (match-end 0) pos)
  11483. (throw 'exit t)))
  11484. nil)))
  11485. (defun org-get-repeat (&optional timestamp)
  11486. "Check if there is a time-stamp with repeater in this entry.
  11487. Return the repeater, as a string, or nil. Also return nil when
  11488. this function is called before first heading.
  11489. When optional argument TIMESTAMP is a string, extract the
  11490. repeater from there instead."
  11491. (save-match-data
  11492. (cond (timestamp
  11493. (and (string-match org-repeat-re timestamp)
  11494. (match-string-no-properties 1 timestamp)))
  11495. ((org-before-first-heading-p) nil)
  11496. (t
  11497. (save-excursion
  11498. (org-back-to-heading t)
  11499. (let ((end (org-entry-end-position)))
  11500. (catch :repeat
  11501. (while (re-search-forward org-repeat-re end t)
  11502. (when (save-match-data (org-at-timestamp-p 'agenda))
  11503. (throw :repeat (match-string-no-properties 1)))))))))))
  11504. (defvar org-last-changed-timestamp)
  11505. (defvar org-last-inserted-timestamp)
  11506. (defvar org-log-post-message)
  11507. (defvar org-log-note-purpose)
  11508. (defvar org-log-note-how nil)
  11509. (defvar org-log-note-extra)
  11510. (defun org-auto-repeat-maybe (done-word)
  11511. "Check if the current headline contains a repeated time-stamp.
  11512. If yes, set TODO state back to what it was and change the base date
  11513. of repeating deadline/scheduled time stamps to new date.
  11514. This function is run automatically after each state change to a DONE state."
  11515. (let* ((repeat (org-get-repeat))
  11516. (aa (assoc org-last-state org-todo-kwd-alist))
  11517. (interpret (nth 1 aa))
  11518. (head (nth 2 aa))
  11519. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11520. (msg "Entry repeats: ")
  11521. (org-log-done nil)
  11522. (org-todo-log-states nil)
  11523. (end (copy-marker (org-entry-end-position))))
  11524. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  11525. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11526. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11527. (and (stringp org-todo-repeat-to-state)
  11528. org-todo-repeat-to-state)
  11529. (and org-todo-repeat-to-state org-last-state))))
  11530. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  11531. to-state)
  11532. ((eq interpret 'type) org-last-state)
  11533. (head)
  11534. (t 'none))))
  11535. (org-back-to-heading t)
  11536. (org-add-planning-info nil nil 'closed)
  11537. ;; When `org-log-repeat' is non-nil or entry contains
  11538. ;; a clock, set LAST_REPEAT property.
  11539. (when (or org-log-repeat
  11540. (catch :clock
  11541. (save-excursion
  11542. (while (re-search-forward org-clock-line-re end t)
  11543. (when (org-at-clock-log-p) (throw :clock t))))))
  11544. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11545. (org-time-stamp-format t t))))
  11546. (when org-log-repeat
  11547. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11548. (memq 'org-add-log-note post-command-hook))
  11549. ;; We are already setup for some record.
  11550. (when (eq org-log-repeat 'note)
  11551. ;; Make sure we take a note, not only a time stamp.
  11552. (setq org-log-note-how 'note))
  11553. ;; Set up for taking a record.
  11554. (org-add-log-setup 'state
  11555. (or done-word (car org-done-keywords))
  11556. org-last-state
  11557. org-log-repeat)))
  11558. ;; Time-stamps without a repeater are usually skipped. However,
  11559. ;; a SCHEDULED time-stamp without one is removed, as they are no
  11560. ;; longer relevant.
  11561. (save-excursion
  11562. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  11563. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  11564. (org-remove-timestamp-with-keyword org-scheduled-string))))
  11565. ;; Update every time-stamp with a repeater in the entry.
  11566. (let ((planning-re (regexp-opt
  11567. (list org-scheduled-string org-deadline-string))))
  11568. (while (re-search-forward org-repeat-re end t)
  11569. (let* ((ts (match-string 0))
  11570. (type (if (not (org-at-planning-p)) "Plain:"
  11571. (save-excursion
  11572. (re-search-backward
  11573. planning-re (line-beginning-position) t)
  11574. (match-string 0)))))
  11575. (when (and (org-at-timestamp-p 'agenda)
  11576. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11577. (let ((n (string-to-number (match-string 2 ts)))
  11578. (what (match-string 3 ts)))
  11579. (when (equal what "w") (setq n (* n 7) what "d"))
  11580. (when (and (equal what "h")
  11581. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11582. ts)))
  11583. (user-error
  11584. "Cannot repeat in %d hour(s) because no hour has been set"
  11585. n))
  11586. ;; Preparation, see if we need to modify the start
  11587. ;; date for the change.
  11588. (when (match-end 1)
  11589. (let ((time (save-match-data (org-time-string-to-time ts)))
  11590. (repeater-type (match-string 1 ts)))
  11591. (cond
  11592. ((equal "." repeater-type)
  11593. ;; Shift starting date to today.
  11594. (org-timestamp-change (- (org-today) (time-to-days time))
  11595. 'day))
  11596. ((equal "+" repeater-type)
  11597. (let ((nshiftmax 10)
  11598. (nshift 0))
  11599. (while (or (= nshift 0)
  11600. (not (time-less-p (current-time) time)))
  11601. (when (= nshiftmax (cl-incf nshift))
  11602. (or (y-or-n-p
  11603. (format "%d repeater intervals were not \
  11604. enough to shift date past today. Continue? "
  11605. nshift))
  11606. (user-error "Abort")))
  11607. (org-timestamp-change n (cdr (assoc what whata)))
  11608. (org-in-regexp org-ts-regexp3)
  11609. (setq ts (match-string 1))
  11610. (setq time
  11611. (save-match-data
  11612. (org-time-string-to-time ts)))))
  11613. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11614. ;; Rematch, so that we have everything in place
  11615. ;; for the real shift.
  11616. (org-in-regexp org-ts-regexp3)
  11617. (setq ts (match-string 1))
  11618. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11619. ts)))))
  11620. (save-excursion
  11621. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11622. (setq msg
  11623. (concat msg type " " org-last-changed-timestamp " ")))))))
  11624. (run-hooks 'org-todo-repeat-hook)
  11625. (setq org-log-post-message msg)
  11626. (message msg))))
  11627. (defun org-show-todo-tree (arg)
  11628. "Make a compact tree which shows all headlines marked with TODO.
  11629. The tree will show the lines where the regexp matches, and all higher
  11630. headlines above the match.
  11631. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11632. With a numeric prefix N, construct a sparse tree for the Nth element
  11633. of `org-todo-keywords-1'."
  11634. (interactive "P")
  11635. (let ((case-fold-search nil)
  11636. (kwd-re
  11637. (cond ((null arg) org-not-done-regexp)
  11638. ((equal arg '(4))
  11639. (let ((kwd
  11640. (completing-read "Keyword (or KWD1|KWD2|...): "
  11641. (mapcar #'list org-todo-keywords-1))))
  11642. (concat "\\("
  11643. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11644. "\\)\\>")))
  11645. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11646. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11647. org-todo-keywords-1)))
  11648. (t (user-error "Invalid prefix argument: %s" arg)))))
  11649. (message "%d TODO entries found"
  11650. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11651. (defun org--deadline-or-schedule (arg type time)
  11652. "Insert DEADLINE or SCHEDULE information in current entry.
  11653. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11654. `org-schedule' for information about ARG and TIME arguments."
  11655. (let* ((deadline? (eq type 'deadline))
  11656. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11657. (log (if deadline? org-log-redeadline org-log-reschedule))
  11658. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11659. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11660. ;; Save repeater cookie from either TIME or current scheduled
  11661. ;; time stamp. We are going to insert it back at the end of
  11662. ;; the process.
  11663. (repeater (or (and (org-string-nw-p time)
  11664. ;; We use `org-repeat-re' because we need
  11665. ;; to tell the difference between a real
  11666. ;; repeater and a time delta, e.g. "+2d".
  11667. (string-match org-repeat-re time)
  11668. (match-string 1 time))
  11669. (and (org-string-nw-p old-date)
  11670. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11671. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11672. old-date)
  11673. (match-string 1 old-date)))))
  11674. (pcase arg
  11675. (`(4)
  11676. (if (not old-date)
  11677. (message (if deadline? "Entry had no deadline to remove"
  11678. "Entry was not scheduled"))
  11679. (when (and old-date log)
  11680. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11681. nil old-date log))
  11682. (org-remove-timestamp-with-keyword keyword)
  11683. (message (if deadline? "Entry no longer has a deadline."
  11684. "Entry is no longer scheduled."))))
  11685. (`(16)
  11686. (save-excursion
  11687. (org-back-to-heading t)
  11688. (let ((regexp (if deadline? org-deadline-time-regexp
  11689. org-scheduled-time-regexp)))
  11690. (if (not (re-search-forward regexp (line-end-position 2) t))
  11691. (user-error (if deadline? "No deadline information to update"
  11692. "No scheduled information to update"))
  11693. (let* ((rpl0 (match-string 1))
  11694. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11695. (msg (if deadline? "Warn starting from" "Delay until")))
  11696. (replace-match
  11697. (concat keyword
  11698. " <" rpl
  11699. (format " -%dd"
  11700. (abs (- (time-to-days
  11701. (save-match-data
  11702. (org-read-date
  11703. nil t nil msg old-date-time)))
  11704. (time-to-days old-date-time))))
  11705. ">") t t))))))
  11706. (_
  11707. (org-add-planning-info type time 'closed)
  11708. (when (and old-date
  11709. log
  11710. (not (equal old-date org-last-inserted-timestamp)))
  11711. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11712. org-last-inserted-timestamp
  11713. old-date
  11714. log))
  11715. (when repeater
  11716. (save-excursion
  11717. (org-back-to-heading t)
  11718. (when (re-search-forward
  11719. (concat keyword " " org-last-inserted-timestamp)
  11720. (line-end-position 2)
  11721. t)
  11722. (goto-char (1- (match-end 0)))
  11723. (insert " " repeater)
  11724. (setq org-last-inserted-timestamp
  11725. (concat (substring org-last-inserted-timestamp 0 -1)
  11726. " " repeater
  11727. (substring org-last-inserted-timestamp -1))))))
  11728. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11729. org-last-inserted-timestamp)))))
  11730. (defun org-deadline (arg &optional time)
  11731. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11732. With one universal prefix argument, remove any deadline from the item.
  11733. With two universal prefix arguments, prompt for a warning delay.
  11734. With argument TIME, set the deadline at the corresponding date. TIME
  11735. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11736. (interactive "P")
  11737. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11738. (org-map-entries
  11739. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11740. nil
  11741. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11742. 'region-start-level
  11743. 'region)
  11744. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11745. (org--deadline-or-schedule arg 'deadline time)))
  11746. (defun org-schedule (arg &optional time)
  11747. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11748. With one universal prefix argument, remove any scheduling date from the item.
  11749. With two universal prefix arguments, prompt for a delay cookie.
  11750. With argument TIME, scheduled at the corresponding date. TIME can
  11751. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11752. (interactive "P")
  11753. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11754. (org-map-entries
  11755. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11756. nil
  11757. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11758. 'region-start-level
  11759. 'region)
  11760. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11761. (org--deadline-or-schedule arg 'scheduled time)))
  11762. (defun org-get-scheduled-time (pom &optional inherit)
  11763. "Get the scheduled time as a time tuple, of a format suitable
  11764. for calling org-schedule with, or if there is no scheduling,
  11765. returns nil."
  11766. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11767. (when time
  11768. (apply 'encode-time (org-parse-time-string time)))))
  11769. (defun org-get-deadline-time (pom &optional inherit)
  11770. "Get the deadline as a time tuple, of a format suitable for
  11771. calling org-deadline with, or if there is no scheduling, returns
  11772. nil."
  11773. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11774. (when time
  11775. (apply 'encode-time (org-parse-time-string time)))))
  11776. (defun org-remove-timestamp-with-keyword (keyword)
  11777. "Remove all time stamps with KEYWORD in the current entry."
  11778. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11779. beg)
  11780. (save-excursion
  11781. (org-back-to-heading t)
  11782. (setq beg (point))
  11783. (outline-next-heading)
  11784. (while (re-search-backward re beg t)
  11785. (replace-match "")
  11786. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11787. (equal (char-before) ?\ ))
  11788. (backward-delete-char 1)
  11789. (when (string-match "^[ \t]*$" (buffer-substring
  11790. (point-at-bol) (point-at-eol)))
  11791. (delete-region (point-at-bol)
  11792. (min (point-max) (1+ (point-at-eol))))))))))
  11793. (defvar org-time-was-given) ; dynamically scoped parameter
  11794. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11795. (defun org-at-planning-p ()
  11796. "Non-nil when point is on a planning info line."
  11797. ;; This is as accurate and faster than `org-element-at-point' since
  11798. ;; planning info location is fixed in the section.
  11799. (org-with-wide-buffer
  11800. (beginning-of-line)
  11801. (and (looking-at-p org-planning-line-re)
  11802. (eq (point)
  11803. (ignore-errors
  11804. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11805. (org-back-to-heading t)
  11806. (org-with-limited-levels (org-back-to-heading t)))
  11807. (line-beginning-position 2))))))
  11808. (defun org-add-planning-info (what &optional time &rest remove)
  11809. "Insert new timestamp with keyword in the planning line.
  11810. WHAT indicates what kind of time stamp to add. It is a symbol
  11811. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11812. the time to use. If none is given, the user is prompted for
  11813. a date. REMOVE indicates what kind of entries to remove. An old
  11814. WHAT entry will also be removed."
  11815. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11816. (catch 'exit
  11817. (when (and (memq what '(scheduled deadline))
  11818. (or (not time)
  11819. (and (stringp time)
  11820. (string-match "^[-+]+[0-9]" time))))
  11821. ;; Try to get a default date/time from existing timestamp
  11822. (save-excursion
  11823. (org-back-to-heading t)
  11824. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11825. (when (re-search-forward (if (eq what 'scheduled)
  11826. org-scheduled-time-regexp
  11827. org-deadline-time-regexp)
  11828. end t)
  11829. (setq ts (match-string 1)
  11830. default-time (apply 'encode-time (org-parse-time-string ts))
  11831. default-input (and ts (org-get-compact-tod ts)))))))
  11832. (when what
  11833. (setq time
  11834. (if (stringp time)
  11835. ;; This is a string (relative or absolute), set
  11836. ;; proper date.
  11837. (apply #'encode-time
  11838. (org-read-date-analyze
  11839. time default-time (decode-time default-time)))
  11840. ;; If necessary, get the time from the user
  11841. (or time (org-read-date nil 'to-time nil
  11842. (cl-case what
  11843. (deadline "DEADLINE")
  11844. (scheduled "SCHEDULED")
  11845. (otherwise nil))
  11846. default-time default-input)))))
  11847. (org-with-wide-buffer
  11848. (org-back-to-heading t)
  11849. (forward-line)
  11850. (unless (bolp) (insert "\n"))
  11851. (cond ((looking-at-p org-planning-line-re)
  11852. ;; Move to current indentation.
  11853. (skip-chars-forward " \t")
  11854. ;; Check if we have to remove something.
  11855. (dolist (type (if what (cons what remove) remove))
  11856. (save-excursion
  11857. (when (re-search-forward
  11858. (cl-case type
  11859. (closed org-closed-time-regexp)
  11860. (deadline org-deadline-time-regexp)
  11861. (scheduled org-scheduled-time-regexp)
  11862. (otherwise
  11863. (error "Invalid planning type: %s" type)))
  11864. (line-end-position) t)
  11865. ;; Delete until next keyword or end of line.
  11866. (delete-region
  11867. (match-beginning 0)
  11868. (if (re-search-forward org-keyword-time-not-clock-regexp
  11869. (line-end-position)
  11870. t)
  11871. (match-beginning 0)
  11872. (line-end-position))))))
  11873. ;; If there is nothing more to add and no more keyword
  11874. ;; is left, remove the line completely.
  11875. (if (and (looking-at-p "[ \t]*$") (not what))
  11876. (delete-region (line-beginning-position)
  11877. (line-beginning-position 2))
  11878. ;; If we removed last keyword, do not leave trailing
  11879. ;; white space at the end of line.
  11880. (let ((p (point)))
  11881. (save-excursion
  11882. (end-of-line)
  11883. (unless (= (skip-chars-backward " \t" p) 0)
  11884. (delete-region (point) (line-end-position)))))))
  11885. ((not what) (throw 'exit nil)) ; Nothing to do.
  11886. (t (insert-before-markers "\n")
  11887. (backward-char 1)
  11888. (when org-adapt-indentation
  11889. (indent-to-column (1+ (org-outline-level))))))
  11890. (when what
  11891. ;; Insert planning keyword.
  11892. (insert (cl-case what
  11893. (closed org-closed-string)
  11894. (deadline org-deadline-string)
  11895. (scheduled org-scheduled-string)
  11896. (otherwise (error "Invalid planning type: %s" what)))
  11897. " ")
  11898. ;; Insert associated timestamp.
  11899. (let ((ts (org-insert-time-stamp
  11900. time
  11901. (or org-time-was-given
  11902. (and (eq what 'closed) org-log-done-with-time))
  11903. (eq what 'closed)
  11904. nil nil (list org-end-time-was-given))))
  11905. (unless (eolp) (insert " "))
  11906. ts))))))
  11907. (defvar org-log-note-marker (make-marker)
  11908. "Marker pointing at the entry where the note is to be inserted.")
  11909. (defvar org-log-note-purpose nil)
  11910. (defvar org-log-note-state nil)
  11911. (defvar org-log-note-previous-state nil)
  11912. (defvar org-log-note-extra nil)
  11913. (defvar org-log-note-window-configuration nil)
  11914. (defvar org-log-note-return-to (make-marker))
  11915. (defvar org-log-note-effective-time nil
  11916. "Remembered current time so that dynamically scoped
  11917. `org-extend-today-until' affects timestamps in state change log")
  11918. (defvar org-log-post-message nil
  11919. "Message to be displayed after a log note has been stored.
  11920. The auto-repeater uses this.")
  11921. (defun org-add-note ()
  11922. "Add a note to the current entry.
  11923. This is done in the same way as adding a state change note."
  11924. (interactive)
  11925. (org-add-log-setup 'note))
  11926. (defun org-log-beginning (&optional create)
  11927. "Return expected start of log notes in current entry.
  11928. When optional argument CREATE is non-nil, the function creates
  11929. a drawer to store notes, if necessary. Returned position ignores
  11930. narrowing."
  11931. (org-with-wide-buffer
  11932. (let ((drawer (org-log-into-drawer)))
  11933. (cond
  11934. (drawer
  11935. (org-end-of-meta-data)
  11936. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11937. (end (if (org-at-heading-p) (point)
  11938. (save-excursion (outline-next-heading) (point))))
  11939. (case-fold-search t))
  11940. (catch 'exit
  11941. ;; Try to find existing drawer.
  11942. (while (re-search-forward regexp end t)
  11943. (let ((element (org-element-at-point)))
  11944. (when (eq (org-element-type element) 'drawer)
  11945. (let ((cend (org-element-property :contents-end element)))
  11946. (when (and (not org-log-states-order-reversed) cend)
  11947. (goto-char cend)))
  11948. (throw 'exit nil))))
  11949. ;; No drawer found. Create one, if permitted.
  11950. (when create
  11951. (unless (bolp) (insert "\n"))
  11952. (let ((beg (point)))
  11953. (insert ":" drawer ":\n:END:\n")
  11954. (org-indent-region beg (point))
  11955. (org-flag-region
  11956. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11957. (end-of-line -1)))))
  11958. (t
  11959. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11960. (skip-chars-forward " \t\n")
  11961. (beginning-of-line)
  11962. (unless org-log-states-order-reversed
  11963. (org-skip-over-state-notes)
  11964. (skip-chars-backward " \t\n")
  11965. (forward-line)))))
  11966. (if (bolp) (point) (line-beginning-position 2))))
  11967. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11968. "Set up the post command hook to take a note.
  11969. If this is about to TODO state change, the new state is expected in STATE.
  11970. HOW is an indicator what kind of note should be created.
  11971. EXTRA is additional text that will be inserted into the notes buffer."
  11972. (move-marker org-log-note-marker (point))
  11973. (setq org-log-note-purpose purpose
  11974. org-log-note-state state
  11975. org-log-note-previous-state prev-state
  11976. org-log-note-how how
  11977. org-log-note-extra extra
  11978. org-log-note-effective-time (org-current-effective-time))
  11979. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11980. (defun org-skip-over-state-notes ()
  11981. "Skip past the list of State notes in an entry."
  11982. (when (ignore-errors (goto-char (org-in-item-p)))
  11983. (let* ((struct (org-list-struct))
  11984. (prevs (org-list-prevs-alist struct))
  11985. (regexp
  11986. (concat "[ \t]*- +"
  11987. (replace-regexp-in-string
  11988. " +" " +"
  11989. (org-replace-escapes
  11990. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11991. `(("%d" . ,org-ts-regexp-inactive)
  11992. ("%D" . ,org-ts-regexp)
  11993. ("%s" . "\\(?:\"\\S-+\"\\)?")
  11994. ("%S" . "\\(?:\"\\S-+\"\\)?")
  11995. ("%t" . ,org-ts-regexp-inactive)
  11996. ("%T" . ,org-ts-regexp)
  11997. ("%u" . ".*?")
  11998. ("%U" . ".*?")))))))
  11999. (while (looking-at-p regexp)
  12000. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12001. (org-list-get-item-end (point) struct)))))))
  12002. (defun org-add-log-note (&optional _purpose)
  12003. "Pop up a window for taking a note, and add this note later."
  12004. (remove-hook 'post-command-hook 'org-add-log-note)
  12005. (setq org-log-note-window-configuration (current-window-configuration))
  12006. (delete-other-windows)
  12007. (move-marker org-log-note-return-to (point))
  12008. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12009. (goto-char org-log-note-marker)
  12010. (org-switch-to-buffer-other-window "*Org Note*")
  12011. (erase-buffer)
  12012. (if (memq org-log-note-how '(time state))
  12013. (org-store-log-note)
  12014. (let ((org-inhibit-startup t)) (org-mode))
  12015. (insert (format "# Insert note for %s.
  12016. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12017. (cl-case org-log-note-purpose
  12018. (clock-out "stopped clock")
  12019. (done "closed todo item")
  12020. (reschedule "rescheduling")
  12021. (delschedule "no longer scheduled")
  12022. (redeadline "changing deadline")
  12023. (deldeadline "removing deadline")
  12024. (refile "refiling")
  12025. (note "this entry")
  12026. (state
  12027. (format "state change from \"%s\" to \"%s\""
  12028. (or org-log-note-previous-state "")
  12029. (or org-log-note-state "")))
  12030. (t (error "This should not happen")))))
  12031. (when org-log-note-extra (insert org-log-note-extra))
  12032. (setq-local org-finish-function 'org-store-log-note)
  12033. (run-hooks 'org-log-buffer-setup-hook)))
  12034. (defvar org-note-abort nil) ; dynamically scoped
  12035. (defun org-store-log-note ()
  12036. "Finish taking a log note, and insert it to where it belongs."
  12037. (let ((txt (prog1 (buffer-string)
  12038. (kill-buffer)))
  12039. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12040. lines)
  12041. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12042. (setq txt (replace-match "" t t txt)))
  12043. (when (string-match "\\s-+\\'" txt)
  12044. (setq txt (replace-match "" t t txt)))
  12045. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12046. (when (org-string-nw-p note)
  12047. (setq note
  12048. (org-replace-escapes
  12049. note
  12050. (list (cons "%u" (user-login-name))
  12051. (cons "%U" user-full-name)
  12052. (cons "%t" (format-time-string
  12053. (org-time-stamp-format 'long 'inactive)
  12054. org-log-note-effective-time))
  12055. (cons "%T" (format-time-string
  12056. (org-time-stamp-format 'long nil)
  12057. org-log-note-effective-time))
  12058. (cons "%d" (format-time-string
  12059. (org-time-stamp-format nil 'inactive)
  12060. org-log-note-effective-time))
  12061. (cons "%D" (format-time-string
  12062. (org-time-stamp-format nil nil)
  12063. org-log-note-effective-time))
  12064. (cons "%s" (cond
  12065. ((not org-log-note-state) "")
  12066. ((string-match-p org-ts-regexp
  12067. org-log-note-state)
  12068. (format "\"[%s]\""
  12069. (substring org-log-note-state 1 -1)))
  12070. (t (format "\"%s\"" org-log-note-state))))
  12071. (cons "%S"
  12072. (cond
  12073. ((not org-log-note-previous-state) "")
  12074. ((string-match-p org-ts-regexp
  12075. org-log-note-previous-state)
  12076. (format "\"[%s]\""
  12077. (substring
  12078. org-log-note-previous-state 1 -1)))
  12079. (t (format "\"%s\""
  12080. org-log-note-previous-state)))))))
  12081. (when lines (setq note (concat note " \\\\")))
  12082. (push note lines))
  12083. (when (and lines (not org-note-abort))
  12084. (with-current-buffer (marker-buffer org-log-note-marker)
  12085. (org-with-wide-buffer
  12086. ;; Find location for the new note.
  12087. (goto-char org-log-note-marker)
  12088. (set-marker org-log-note-marker nil)
  12089. ;; Note associated to a clock is to be located right after
  12090. ;; the clock. Do not move point.
  12091. (unless (eq org-log-note-purpose 'clock-out)
  12092. (goto-char (org-log-beginning t)))
  12093. ;; Make sure point is at the beginning of an empty line.
  12094. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12095. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12096. ;; In an existing list, add a new item at the top level.
  12097. ;; Otherwise, indent line like a regular one.
  12098. (let ((itemp (org-in-item-p)))
  12099. (if itemp
  12100. (indent-line-to
  12101. (let ((struct (save-excursion
  12102. (goto-char itemp) (org-list-struct))))
  12103. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12104. (org-indent-line)))
  12105. (insert (org-list-bullet-string "-") (pop lines))
  12106. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12107. (dolist (line lines)
  12108. (insert "\n")
  12109. (indent-line-to ind)
  12110. (insert line)))
  12111. (message "Note stored")
  12112. (org-back-to-heading t))
  12113. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12114. ;; from within `org-add-log-note' because `buffer-undo-list'
  12115. ;; is then modified outside of `org-with-remote-undo'.
  12116. (when (eq this-command 'org-agenda-todo)
  12117. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12118. ;; Don't add undo information when called from `org-agenda-todo'.
  12119. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12120. (set-window-configuration org-log-note-window-configuration)
  12121. (with-current-buffer (marker-buffer org-log-note-return-to)
  12122. (goto-char org-log-note-return-to))
  12123. (move-marker org-log-note-return-to nil)
  12124. (when org-log-post-message (message "%s" org-log-post-message))))
  12125. (defun org-remove-empty-drawer-at (pos)
  12126. "Remove an empty drawer at position POS.
  12127. POS may also be a marker."
  12128. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12129. (org-with-wide-buffer
  12130. (goto-char pos)
  12131. (let ((drawer (org-element-at-point)))
  12132. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12133. (not (org-element-property :contents-begin drawer)))
  12134. (delete-region (org-element-property :begin drawer)
  12135. (progn (goto-char (org-element-property :end drawer))
  12136. (skip-chars-backward " \r\t\n")
  12137. (forward-line)
  12138. (point))))))))
  12139. (defvar org-ts-type nil)
  12140. (defun org-sparse-tree (&optional arg type)
  12141. "Create a sparse tree, prompt for the details.
  12142. This command can create sparse trees. You first need to select the type
  12143. of match used to create the tree:
  12144. t Show all TODO entries.
  12145. T Show entries with a specific TODO keyword.
  12146. m Show entries selected by a tags/property match.
  12147. p Enter a property name and its value (both with completion on existing
  12148. names/values) and show entries with that property.
  12149. r Show entries matching a regular expression (`/' can be used as well).
  12150. b Show deadlines and scheduled items before a date.
  12151. a Show deadlines and scheduled items after a date.
  12152. d Show deadlines due within `org-deadline-warning-days'.
  12153. D Show deadlines and scheduled items between a date range."
  12154. (interactive "P")
  12155. (setq type (or type org-sparse-tree-default-date-type))
  12156. (setq org-ts-type type)
  12157. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12158. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12159. \[c]ycle through date types: %s"
  12160. (cl-case type
  12161. (all "all timestamps")
  12162. (scheduled "only scheduled")
  12163. (deadline "only deadline")
  12164. (active "only active timestamps")
  12165. (inactive "only inactive timestamps")
  12166. (closed "with a closed time-stamp")
  12167. (otherwise "scheduled/deadline")))
  12168. (let ((answer (read-char-exclusive)))
  12169. (cl-case answer
  12170. (?c
  12171. (org-sparse-tree
  12172. arg
  12173. (cadr
  12174. (memq type '(nil all scheduled deadline active inactive closed)))))
  12175. (?d (call-interactively 'org-check-deadlines))
  12176. (?b (call-interactively 'org-check-before-date))
  12177. (?a (call-interactively 'org-check-after-date))
  12178. (?D (call-interactively 'org-check-dates-range))
  12179. (?t (call-interactively 'org-show-todo-tree))
  12180. (?T (org-show-todo-tree '(4)))
  12181. (?m (call-interactively 'org-match-sparse-tree))
  12182. ((?p ?P)
  12183. (let* ((kwd (completing-read
  12184. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12185. (value (completing-read
  12186. "Value: " (mapcar #'list (org-property-values kwd)))))
  12187. (unless (string-match "\\`{.*}\\'" value)
  12188. (setq value (concat "\"" value "\"")))
  12189. (org-match-sparse-tree arg (concat kwd "=" value))))
  12190. ((?r ?R ?/) (call-interactively 'org-occur))
  12191. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12192. (defvar-local org-occur-highlights nil
  12193. "List of overlays used for occur matches.")
  12194. (defvar-local org-occur-parameters nil
  12195. "Parameters of the active org-occur calls.
  12196. This is a list, each call to org-occur pushes as cons cell,
  12197. containing the regular expression and the callback, onto the list.
  12198. The list can contain several entries if `org-occur' has been called
  12199. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12200. will only contain one set of parameters. When the highlights are
  12201. removed (for example with `C-c C-c', or with the next edit (depending
  12202. on `org-remove-highlights-with-change'), this variable is emptied
  12203. as well.")
  12204. (defun org-occur (regexp &optional keep-previous callback)
  12205. "Make a compact tree which shows all matches of REGEXP.
  12206. The tree will show the lines where the regexp matches, and any other context
  12207. defined in `org-show-context-detail', which see.
  12208. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12209. done by a previous call to `org-occur' will be kept, to allow stacking of
  12210. calls to this command.
  12211. Optional argument CALLBACK can be a function of no argument. In this case,
  12212. it is called with point at the end of the match, match data being set
  12213. accordingly. Current match is shown only if the return value is non-nil.
  12214. The function must neither move point nor alter narrowing."
  12215. (interactive "sRegexp: \nP")
  12216. (when (equal regexp "")
  12217. (user-error "Regexp cannot be empty"))
  12218. (unless keep-previous
  12219. (org-remove-occur-highlights nil nil t))
  12220. (push (cons regexp callback) org-occur-parameters)
  12221. (let ((cnt 0))
  12222. (save-excursion
  12223. (goto-char (point-min))
  12224. (when (or (not keep-previous) ; do not want to keep
  12225. (not org-occur-highlights)) ; no previous matches
  12226. ;; hide everything
  12227. (org-overview))
  12228. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12229. (isearch-no-upper-case-p regexp t)
  12230. org-occur-case-fold-search)))
  12231. (while (re-search-forward regexp nil t)
  12232. (when (or (not callback)
  12233. (save-match-data (funcall callback)))
  12234. (setq cnt (1+ cnt))
  12235. (when org-highlight-sparse-tree-matches
  12236. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12237. (org-show-context 'occur-tree)))))
  12238. (when org-remove-highlights-with-change
  12239. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12240. nil 'local))
  12241. (unless org-sparse-tree-open-archived-trees
  12242. (org-hide-archived-subtrees (point-min) (point-max)))
  12243. (run-hooks 'org-occur-hook)
  12244. (when (called-interactively-p 'interactive)
  12245. (message "%d match(es) for regexp %s" cnt regexp))
  12246. cnt))
  12247. (defun org-occur-next-match (&optional n _reset)
  12248. "Function for `next-error-function' to find sparse tree matches.
  12249. N is the number of matches to move, when negative move backwards.
  12250. This function always goes back to the starting point when no
  12251. match is found."
  12252. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12253. (search-func (if (< n 0)
  12254. 'previous-single-char-property-change
  12255. 'next-single-char-property-change))
  12256. (n (abs n))
  12257. (pos (point))
  12258. p1)
  12259. (catch 'exit
  12260. (while (setq p1 (funcall search-func (point) 'org-type))
  12261. (when (equal p1 limit)
  12262. (goto-char pos)
  12263. (user-error "No more matches"))
  12264. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12265. (setq n (1- n))
  12266. (when (= n 0)
  12267. (goto-char p1)
  12268. (throw 'exit (point))))
  12269. (goto-char p1))
  12270. (goto-char p1)
  12271. (user-error "No more matches"))))
  12272. (defun org-highlight-new-match (beg end)
  12273. "Highlight from BEG to END and mark the highlight is an occur headline."
  12274. (let ((ov (make-overlay beg end)))
  12275. (overlay-put ov 'face 'secondary-selection)
  12276. (overlay-put ov 'org-type 'org-occur)
  12277. (push ov org-occur-highlights)))
  12278. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12279. "Remove the occur highlights from the buffer.
  12280. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12281. from the `before-change-functions' in the current buffer."
  12282. (interactive)
  12283. (unless org-inhibit-highlight-removal
  12284. (mapc #'delete-overlay org-occur-highlights)
  12285. (setq org-occur-highlights nil)
  12286. (setq org-occur-parameters nil)
  12287. (unless noremove
  12288. (remove-hook 'before-change-functions
  12289. 'org-remove-occur-highlights 'local))))
  12290. ;;;; Priorities
  12291. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12292. "Regular expression matching the priority indicator.")
  12293. (defvar org-remove-priority-next-time nil)
  12294. (defun org-priority-up ()
  12295. "Increase the priority of the current item."
  12296. (interactive)
  12297. (org-priority 'up))
  12298. (defun org-priority-down ()
  12299. "Decrease the priority of the current item."
  12300. (interactive)
  12301. (org-priority 'down))
  12302. (defun org-priority (&optional action show)
  12303. "Change the priority of an item.
  12304. When called interactively with a `\\[universal-argument]' prefix,
  12305. show the priority in the minibuffer instead of changing it.
  12306. When called programatically, ACTION can be `set', `up', `down',
  12307. or a character."
  12308. (interactive "P")
  12309. (when show
  12310. ;; Deprecation warning inserted for Org 9.2; once enough time has
  12311. ;; passed the SHOW argument should be removed.
  12312. (warn "`org-priority' called with deprecated SHOW argument"))
  12313. (if (equal action '(4))
  12314. (org-show-priority)
  12315. (unless org-enable-priority-commands
  12316. (user-error "Priority commands are disabled"))
  12317. (setq action (or action 'set))
  12318. (let (current new news have remove)
  12319. (save-excursion
  12320. (org-back-to-heading t)
  12321. (when (looking-at org-priority-regexp)
  12322. (setq current (string-to-char (match-string 2))
  12323. have t))
  12324. (cond
  12325. ((eq action 'remove)
  12326. (setq remove t new ?\ ))
  12327. ((or (eq action 'set)
  12328. (integerp action))
  12329. (if (not (eq action 'set))
  12330. (setq new action)
  12331. (message "Priority %c-%c, SPC to remove: "
  12332. org-highest-priority org-lowest-priority)
  12333. (save-match-data
  12334. (setq new (read-char-exclusive))))
  12335. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12336. (= (upcase org-lowest-priority) org-lowest-priority))
  12337. (setq new (upcase new)))
  12338. (cond ((equal new ?\s) (setq remove t))
  12339. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12340. (user-error "Priority must be between `%c' and `%c'"
  12341. org-highest-priority org-lowest-priority))))
  12342. ((eq action 'up)
  12343. (setq new (if have
  12344. (1- current) ; normal cycling
  12345. ;; last priority was empty
  12346. (if (eq last-command this-command)
  12347. org-lowest-priority ; wrap around empty to lowest
  12348. ;; default
  12349. (if org-priority-start-cycle-with-default
  12350. org-default-priority
  12351. (1- org-default-priority))))))
  12352. ((eq action 'down)
  12353. (setq new (if have
  12354. (1+ current) ; normal cycling
  12355. ;; last priority was empty
  12356. (if (eq last-command this-command)
  12357. org-highest-priority ; wrap around empty to highest
  12358. ;; default
  12359. (if org-priority-start-cycle-with-default
  12360. org-default-priority
  12361. (1+ org-default-priority))))))
  12362. (t (user-error "Invalid action")))
  12363. (when (or (< (upcase new) org-highest-priority)
  12364. (> (upcase new) org-lowest-priority))
  12365. (if (and (memq action '(up down))
  12366. (not have) (not (eq last-command this-command)))
  12367. ;; `new' is from default priority
  12368. (error
  12369. "The default can not be set, see `org-default-priority' why")
  12370. ;; normal cycling: `new' is beyond highest/lowest priority
  12371. ;; and is wrapped around to the empty priority
  12372. (setq remove t)))
  12373. (setq news (format "%c" new))
  12374. (if have
  12375. (if remove
  12376. (replace-match "" t t nil 1)
  12377. (replace-match news t t nil 2))
  12378. (if remove
  12379. (user-error "No priority cookie found in line")
  12380. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12381. (if (match-end 2)
  12382. (progn
  12383. (goto-char (match-end 2))
  12384. (insert " [#" news "]"))
  12385. (goto-char (match-beginning 3))
  12386. (insert "[#" news "] "))))
  12387. (org-align-tags))
  12388. (if remove
  12389. (message "Priority removed")
  12390. (message "Priority of current item set to %s" news)))))
  12391. (defun org-show-priority ()
  12392. "Show the priority of the current item.
  12393. This priority is composed of the main priority given with the [#A] cookies,
  12394. and by additional input from the age of a schedules or deadline entry."
  12395. (interactive)
  12396. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12397. (org-get-at-bol 'priority)
  12398. (save-excursion
  12399. (save-match-data
  12400. (beginning-of-line)
  12401. (and (looking-at org-heading-regexp)
  12402. (org-get-priority (match-string 0))))))))
  12403. (message "Priority is %d" (if pri pri -1000))))
  12404. (defun org-get-priority (s)
  12405. "Find priority cookie and return priority."
  12406. (save-match-data
  12407. (if (functionp org-get-priority-function)
  12408. (funcall org-get-priority-function)
  12409. (if (not (string-match org-priority-regexp s))
  12410. (* 1000 (- org-lowest-priority org-default-priority))
  12411. (* 1000 (- org-lowest-priority
  12412. (string-to-char (match-string 2 s))))))))
  12413. ;;;; Tags
  12414. (defvar org-agenda-archives-mode)
  12415. (defvar org-map-continue-from nil
  12416. "Position from where mapping should continue.
  12417. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12418. (defvar org-scanner-tags nil
  12419. "The current tag list while the tags scanner is running.")
  12420. (defvar org-trust-scanner-tags nil
  12421. "Should `org-get-tags' use the tags for the scanner.
  12422. This is for internal dynamical scoping only.
  12423. When this is non-nil, the function `org-get-tags' will return the value
  12424. of `org-scanner-tags' instead of building the list by itself. This
  12425. can lead to large speed-ups when the tags scanner is used in a file with
  12426. many entries, and when the list of tags is retrieved, for example to
  12427. obtain a list of properties. Building the tags list for each entry in such
  12428. a file becomes an N^2 operation - but with this variable set, it scales
  12429. as N.")
  12430. (defvar org--matcher-tags-todo-only nil)
  12431. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12432. "Scan headline tags with inheritance and produce output ACTION.
  12433. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12434. or `agenda' to produce an entry list for an agenda view. It can also be
  12435. a Lisp form or a function that should be called at each matched headline, in
  12436. this case the return value is a list of all return values from these calls.
  12437. MATCHER is a function accepting three arguments, returning
  12438. a non-nil value whenever a given set of tags qualifies a headline
  12439. for inclusion. See `org-make-tags-matcher' for more information.
  12440. As a special case, it can also be set to t (respectively nil) in
  12441. order to match all (respectively none) headline.
  12442. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12443. included in the output.
  12444. START-LEVEL can be a string with asterisks, reducing the scope to
  12445. headlines matching this string."
  12446. (require 'org-agenda)
  12447. (let* ((re (concat "^"
  12448. (if start-level
  12449. ;; Get the correct level to match
  12450. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12451. org-outline-regexp)
  12452. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12453. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12454. (props (list 'face 'default
  12455. 'done-face 'org-agenda-done
  12456. 'undone-face 'default
  12457. 'mouse-face 'highlight
  12458. 'org-not-done-regexp org-not-done-regexp
  12459. 'org-todo-regexp org-todo-regexp
  12460. 'org-complex-heading-regexp org-complex-heading-regexp
  12461. 'help-echo
  12462. (format "mouse-2 or RET jump to Org file %S"
  12463. (abbreviate-file-name
  12464. (or (buffer-file-name (buffer-base-buffer))
  12465. (buffer-name (buffer-base-buffer)))))))
  12466. (org-map-continue-from nil)
  12467. lspos tags tags-list
  12468. (tags-alist (list (cons 0 org-file-tags)))
  12469. (llast 0) rtn rtn1 level category i txt
  12470. todo marker entry priority
  12471. ts-date ts-date-type ts-date-pair)
  12472. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12473. (setq action (list 'lambda nil action)))
  12474. (save-excursion
  12475. (goto-char (point-min))
  12476. (when (eq action 'sparse-tree)
  12477. (org-overview)
  12478. (org-remove-occur-highlights))
  12479. (while (let (case-fold-search)
  12480. (re-search-forward re nil t))
  12481. (setq org-map-continue-from nil)
  12482. (catch :skip
  12483. ;; Ignore closing parts of inline tasks.
  12484. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12485. (throw :skip t))
  12486. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  12487. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  12488. (goto-char (setq lspos (match-beginning 0)))
  12489. (setq level (org-reduced-level (org-outline-level))
  12490. category (org-get-category))
  12491. (when (eq action 'agenda)
  12492. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12493. ts-date (car ts-date-pair)
  12494. ts-date-type (cdr ts-date-pair)))
  12495. (setq i llast llast level)
  12496. ;; remove tag lists from same and sublevels
  12497. (while (>= i level)
  12498. (when (setq entry (assoc i tags-alist))
  12499. (setq tags-alist (delete entry tags-alist)))
  12500. (setq i (1- i)))
  12501. ;; add the next tags
  12502. (when tags
  12503. (setq tags (org-split-string tags ":")
  12504. tags-alist
  12505. (cons (cons level tags) tags-alist)))
  12506. ;; compile tags for current headline
  12507. (setq tags-list
  12508. (if org-use-tag-inheritance
  12509. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12510. tags)
  12511. org-scanner-tags tags-list)
  12512. (when org-use-tag-inheritance
  12513. (setcdr (car tags-alist)
  12514. (mapcar (lambda (x)
  12515. (setq x (copy-sequence x))
  12516. (org-add-prop-inherited x))
  12517. (cdar tags-alist))))
  12518. (when (and tags org-use-tag-inheritance
  12519. (or (not (eq t org-use-tag-inheritance))
  12520. org-tags-exclude-from-inheritance))
  12521. ;; Selective inheritance, remove uninherited ones.
  12522. (setcdr (car tags-alist)
  12523. (org-remove-uninherited-tags (cdar tags-alist))))
  12524. (when (and
  12525. ;; eval matcher only when the todo condition is OK
  12526. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12527. (if (functionp matcher)
  12528. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12529. (funcall matcher todo tags-list level))
  12530. matcher))
  12531. ;; Call the skipper, but return t if it does not
  12532. ;; skip, so that the `and' form continues evaluating.
  12533. (progn
  12534. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12535. t)
  12536. ;; Check if timestamps are deselecting this entry
  12537. (or (not todo-only)
  12538. (and (member todo org-todo-keywords-1)
  12539. (or (not org-agenda-tags-todo-honor-ignore-options)
  12540. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12541. ;; select this headline
  12542. (cond
  12543. ((eq action 'sparse-tree)
  12544. (and org-highlight-sparse-tree-matches
  12545. (org-get-heading) (match-end 0)
  12546. (org-highlight-new-match
  12547. (match-beginning 1) (match-end 1)))
  12548. (org-show-context 'tags-tree))
  12549. ((eq action 'agenda)
  12550. (setq txt (org-agenda-format-item
  12551. ""
  12552. (concat
  12553. (if (eq org-tags-match-list-sublevels 'indented)
  12554. (make-string (1- level) ?.) "")
  12555. (org-get-heading))
  12556. (make-string level ?\s)
  12557. category
  12558. tags-list)
  12559. priority (org-get-priority txt))
  12560. (goto-char lspos)
  12561. (setq marker (org-agenda-new-marker))
  12562. (org-add-props txt props
  12563. 'org-marker marker 'org-hd-marker marker 'org-category category
  12564. 'todo-state todo
  12565. 'ts-date ts-date
  12566. 'priority priority
  12567. 'type (concat "tagsmatch" ts-date-type))
  12568. (push txt rtn))
  12569. ((functionp action)
  12570. (setq org-map-continue-from nil)
  12571. (save-excursion
  12572. (setq rtn1 (funcall action))
  12573. (push rtn1 rtn)))
  12574. (t (user-error "Invalid action")))
  12575. ;; if we are to skip sublevels, jump to end of subtree
  12576. (unless org-tags-match-list-sublevels
  12577. (org-end-of-subtree t)
  12578. (backward-char 1))))
  12579. ;; Get the correct position from where to continue
  12580. (if org-map-continue-from
  12581. (goto-char org-map-continue-from)
  12582. (and (= (point) lspos) (end-of-line 1)))))
  12583. (when (and (eq action 'sparse-tree)
  12584. (not org-sparse-tree-open-archived-trees))
  12585. (org-hide-archived-subtrees (point-min) (point-max)))
  12586. (nreverse rtn)))
  12587. (defun org-remove-uninherited-tags (tags)
  12588. "Remove all tags that are not inherited from the list TAGS."
  12589. (cond
  12590. ((eq org-use-tag-inheritance t)
  12591. (if org-tags-exclude-from-inheritance
  12592. (org-delete-all org-tags-exclude-from-inheritance tags)
  12593. tags))
  12594. ((not org-use-tag-inheritance) nil)
  12595. ((stringp org-use-tag-inheritance)
  12596. (delq nil (mapcar
  12597. (lambda (x)
  12598. (if (and (string-match org-use-tag-inheritance x)
  12599. (not (member x org-tags-exclude-from-inheritance)))
  12600. x nil))
  12601. tags)))
  12602. ((listp org-use-tag-inheritance)
  12603. (delq nil (mapcar
  12604. (lambda (x)
  12605. (if (member x org-use-tag-inheritance) x nil))
  12606. tags)))))
  12607. (defun org-match-sparse-tree (&optional todo-only match)
  12608. "Create a sparse tree according to tags string MATCH.
  12609. MATCH is a string with match syntax. It can contain a selection
  12610. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12611. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12612. those. See the manual for details.
  12613. If optional argument TODO-ONLY is non-nil, only select lines that
  12614. are also TODO tasks."
  12615. (interactive "P")
  12616. (org-agenda-prepare-buffers (list (current-buffer)))
  12617. (let ((org--matcher-tags-todo-only todo-only))
  12618. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12619. org--matcher-tags-todo-only)))
  12620. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12621. (defvar org-cached-props nil)
  12622. (defun org-cached-entry-get (pom property)
  12623. (if (or (eq t org-use-property-inheritance)
  12624. (and (stringp org-use-property-inheritance)
  12625. (let ((case-fold-search t))
  12626. (string-match-p org-use-property-inheritance property)))
  12627. (and (listp org-use-property-inheritance)
  12628. (member-ignore-case property org-use-property-inheritance)))
  12629. ;; Caching is not possible, check it directly.
  12630. (org-entry-get pom property 'inherit)
  12631. ;; Get all properties, so we can do complicated checks easily.
  12632. (cdr (assoc-string property
  12633. (or org-cached-props
  12634. (setq org-cached-props (org-entry-properties pom)))
  12635. t))))
  12636. (defun org-global-tags-completion-table (&optional files)
  12637. "Return the list of all tags in all agenda buffer/files.
  12638. Optional FILES argument is a list of files which can be used
  12639. instead of the agenda files."
  12640. (save-excursion
  12641. (org-uniquify
  12642. (delq nil
  12643. (apply #'append
  12644. (mapcar
  12645. (lambda (file)
  12646. (set-buffer (find-file-noselect file))
  12647. (org--tag-add-to-alist
  12648. (org-get-buffer-tags)
  12649. (mapcar (lambda (x)
  12650. (and (stringp (car-safe x))
  12651. (list (car-safe x))))
  12652. org-current-tag-alist)))
  12653. (if (car-safe files) files
  12654. (org-agenda-files))))))))
  12655. (defun org-make-tags-matcher (match)
  12656. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12657. Returns a cons of the selection string MATCH and a function
  12658. implementing the matcher.
  12659. The matcher is to be called at an Org entry, with point on the
  12660. headline, and returns non-nil if the entry matches the selection
  12661. string MATCH. It must be called with three arguments: the TODO
  12662. keyword at the entry (or nil if none), the list of all tags at
  12663. the entry including inherited ones and the reduced level of the
  12664. headline. Additionally, the category of the entry, if any, must
  12665. be specified as the text property `org-category' on the headline.
  12666. This function sets the variable `org--matcher-tags-todo-only' to
  12667. a non-nil value if the matcher restricts matching to TODO
  12668. entries, otherwise it is not touched.
  12669. See also `org-scan-tags'."
  12670. (unless match
  12671. ;; Get a new match request, with completion against the global
  12672. ;; tags table and the local tags in current buffer.
  12673. (let ((org-last-tags-completion-table
  12674. (org--tag-add-to-alist
  12675. (org-get-buffer-tags)
  12676. (org-global-tags-completion-table))))
  12677. (setq match
  12678. (completing-read
  12679. "Match: "
  12680. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12681. (let ((match0 match)
  12682. (re (concat
  12683. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12684. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12685. "\\([<>=]\\{1,2\\}\\)"
  12686. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12687. "\\|" org-tag-re "\\)"))
  12688. (start 0)
  12689. tagsmatch todomatch tagsmatcher todomatcher)
  12690. ;; Expand group tags.
  12691. (setq match (org-tags-expand match))
  12692. ;; Check if there is a TODO part of this match, which would be the
  12693. ;; part after a "/". To make sure that this slash is not part of
  12694. ;; a property value to be matched against, we also check that
  12695. ;; there is no / after that slash. First, find the last slash.
  12696. (let ((s 0))
  12697. (while (string-match "/+" match s)
  12698. (setq start (match-beginning 0))
  12699. (setq s (match-end 0))))
  12700. (if (and (string-match "/+" match start)
  12701. (not (string-match-p "\"" match start)))
  12702. ;; Match contains also a TODO-matching request.
  12703. (progn
  12704. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12705. (setq todomatch (substring match (match-end 0)))
  12706. (when (string-prefix-p "!" todomatch)
  12707. (setq org--matcher-tags-todo-only t)
  12708. (setq todomatch (substring todomatch 1)))
  12709. (when (string-match "\\`\\s-*\\'" todomatch)
  12710. (setq todomatch nil)))
  12711. ;; Only matching tags.
  12712. (setq tagsmatch match)
  12713. (setq todomatch nil))
  12714. ;; Make the tags matcher.
  12715. (when (org-string-nw-p tagsmatch)
  12716. (let ((orlist nil)
  12717. (orterms (org-split-string tagsmatch "|"))
  12718. term)
  12719. (while (setq term (pop orterms))
  12720. (while (and (equal (substring term -1) "\\") orterms)
  12721. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12722. (while (string-match re term)
  12723. (let* ((rest (substring term (match-end 0)))
  12724. (minus (and (match-end 1)
  12725. (equal (match-string 1 term) "-")))
  12726. (tag (save-match-data
  12727. (replace-regexp-in-string
  12728. "\\\\-" "-" (match-string 2 term))))
  12729. (regexp (eq (string-to-char tag) ?{))
  12730. (levelp (match-end 4))
  12731. (propp (match-end 5))
  12732. (mm
  12733. (cond
  12734. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12735. (levelp
  12736. `(,(org-op-to-function (match-string 3 term))
  12737. level
  12738. ,(string-to-number (match-string 4 term))))
  12739. (propp
  12740. (let* ((gv (pcase (upcase (match-string 5 term))
  12741. ("CATEGORY"
  12742. '(get-text-property (point) 'org-category))
  12743. ("TODO" 'todo)
  12744. (p `(org-cached-entry-get nil ,p))))
  12745. (pv (match-string 7 term))
  12746. (regexp (eq (string-to-char pv) ?{))
  12747. (strp (eq (string-to-char pv) ?\"))
  12748. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12749. (po (org-op-to-function (match-string 6 term)
  12750. (if timep 'time strp))))
  12751. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12752. (when timep (setq pv (org-matcher-time pv)))
  12753. (cond ((and regexp (eq po '/=))
  12754. `(not (string-match ,pv (or ,gv ""))))
  12755. (regexp `(string-match ,pv (or ,gv "")))
  12756. (strp `(,po (or ,gv "") ,pv))
  12757. (t
  12758. `(,po
  12759. (string-to-number (or ,gv ""))
  12760. ,(string-to-number pv))))))
  12761. (t `(member ,tag tags-list)))))
  12762. (push (if minus `(not ,mm) mm) tagsmatcher)
  12763. (setq term rest)))
  12764. (push `(and ,@tagsmatcher) orlist)
  12765. (setq tagsmatcher nil))
  12766. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12767. ;; Make the TODO matcher.
  12768. (when (org-string-nw-p todomatch)
  12769. (let ((orlist nil))
  12770. (dolist (term (org-split-string todomatch "|"))
  12771. (while (string-match re term)
  12772. (let* ((minus (and (match-end 1)
  12773. (equal (match-string 1 term) "-")))
  12774. (kwd (match-string 2 term))
  12775. (regexp (eq (string-to-char kwd) ?{))
  12776. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12777. `(equal todo ,kwd))))
  12778. (push (if minus `(not ,mm) mm) todomatcher))
  12779. (setq term (substring term (match-end 0))))
  12780. (push (if (> (length todomatcher) 1)
  12781. (cons 'and todomatcher)
  12782. (car todomatcher))
  12783. orlist)
  12784. (setq todomatcher nil))
  12785. (setq todomatcher (cons 'or orlist))))
  12786. ;; Return the string and function of the matcher. If no
  12787. ;; tags-specific or todo-specific matcher exists, match
  12788. ;; everything.
  12789. (let ((matcher (if (and tagsmatcher todomatcher)
  12790. `(and ,tagsmatcher ,todomatcher)
  12791. (or tagsmatcher todomatcher t))))
  12792. (when org--matcher-tags-todo-only
  12793. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12794. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12795. (defun org--tags-expand-group (group tag-groups expanded)
  12796. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  12797. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  12798. an accumulator used in recursive calls."
  12799. (dolist (tag group)
  12800. (unless (member tag expanded)
  12801. (let ((group (assoc tag tag-groups)))
  12802. (push tag expanded)
  12803. (when group
  12804. (setq expanded
  12805. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  12806. expanded)
  12807. (defun org-tags-expand (match &optional single-as-list downcased)
  12808. "Expand group tags in MATCH.
  12809. This replaces every group tag in MATCH with a regexp tag search.
  12810. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12811. will be replaced like this:
  12812. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12813. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12814. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12815. Replacing by a regexp preserves the structure of the match.
  12816. E.g., this expansion
  12817. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12818. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12819. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  12820. A group tag in MATCH can contain regular expressions of its own.
  12821. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12822. will be replaced like this:
  12823. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12824. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12825. assumed to be a single group tag, and the function will return
  12826. the list of tags in this group.
  12827. When DOWNCASED is non-nil, expand downcased TAGS."
  12828. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  12829. (let ((tag-groups
  12830. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  12831. (if (not downcased) g
  12832. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  12833. (cond
  12834. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  12835. (org-group-tags
  12836. (let* ((case-fold-search t)
  12837. (tag-syntax org-mode-syntax-table)
  12838. (group-keys (mapcar #'car tag-groups))
  12839. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  12840. (return-match (if downcased (downcase match) match)))
  12841. ;; Mark regexp-expressions in the match-expression so that we
  12842. ;; do not replace them later on.
  12843. (let ((s 0))
  12844. (while (string-match "{.+?}" return-match s)
  12845. (setq s (match-end 0))
  12846. (add-text-properties
  12847. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  12848. ;; @ and _ are allowed as word-components in tags.
  12849. (modify-syntax-entry ?@ "w" tag-syntax)
  12850. (modify-syntax-entry ?_ "w" tag-syntax)
  12851. ;; For each tag token found in MATCH, compute a regexp and it
  12852. (with-syntax-table tag-syntax
  12853. (replace-regexp-in-string
  12854. key-regexp
  12855. (lambda (m)
  12856. (if (get-text-property (match-beginning 2) 'regexp m)
  12857. m ;regexp tag: ignore
  12858. (let* ((operator (match-string 1 m))
  12859. (tag-token (let ((tag (match-string 2 m)))
  12860. (list (if downcased (downcase tag) tag))))
  12861. regexp-tags regular-tags)
  12862. ;; Partition tags between regexp and regular tags.
  12863. ;; Remove curly bracket syntax from regexp tags.
  12864. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  12865. (save-match-data
  12866. (if (string-match "{\\(.+?\\)}" tag)
  12867. (push (match-string 1 tag) regexp-tags)
  12868. (push tag regular-tags))))
  12869. ;; Replace tag token by the appropriate regexp.
  12870. ;; Regular tags need to be regexp-quoted, whereas
  12871. ;; regexp-tags are inserted as-is.
  12872. (let ((regular (regexp-opt regular-tags))
  12873. (regexp (mapconcat #'identity regexp-tags "\\|")))
  12874. (concat operator
  12875. (cond
  12876. ((null regular-tags) (format "{%s}" regexp))
  12877. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  12878. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  12879. return-match
  12880. t t))))
  12881. (t match))))
  12882. (defun org-op-to-function (op &optional stringp)
  12883. "Turn an operator into the appropriate function."
  12884. (setq op
  12885. (cond
  12886. ((equal op "<" ) '(< org-string< org-time<))
  12887. ((equal op ">" ) '(> org-string> org-time>))
  12888. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12889. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12890. ((member op '("=" "==")) '(= string= org-time=))
  12891. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12892. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12893. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12894. (defvar org-tags-overlay (make-overlay 1 1))
  12895. (delete-overlay org-tags-overlay)
  12896. (defun org-add-prop-inherited (s)
  12897. (add-text-properties 0 (length s) '(inherited t) s)
  12898. s)
  12899. (defun org-toggle-tag (tag &optional onoff)
  12900. "Toggle the tag TAG for the current line.
  12901. If ONOFF is `on' or `off', don't toggle but set to this state."
  12902. (save-excursion
  12903. (org-back-to-heading t)
  12904. (let ((current
  12905. ;; Reverse the tags list so any new tag is appended to the
  12906. ;; current list of tags.
  12907. (nreverse (org-get-tags nil t)))
  12908. res)
  12909. (pcase onoff
  12910. (`off (setq current (delete tag current)))
  12911. ((or `on (guard (not (member tag current))))
  12912. (setq res t)
  12913. (cl-pushnew tag current :test #'equal))
  12914. (_ (setq current (delete tag current))))
  12915. (org-set-tags (nreverse current))
  12916. res)))
  12917. (defun org--align-tags-here (to-col)
  12918. "Align tags on the current headline to TO-COL.
  12919. Assume point is on a headline. Preserve point when aligning
  12920. tags."
  12921. (when (org-match-line org-tag-line-re)
  12922. (let* ((tags-start (match-beginning 1))
  12923. (blank-start (save-excursion
  12924. (goto-char tags-start)
  12925. (skip-chars-backward " \t")
  12926. (point)))
  12927. (new (max (if (>= to-col 0) to-col
  12928. (- (abs to-col) (string-width (match-string 1))))
  12929. ;; Introduce at least one space after the heading
  12930. ;; or the stars.
  12931. (save-excursion
  12932. (goto-char blank-start)
  12933. (1+ (current-column)))))
  12934. (current
  12935. (save-excursion (goto-char tags-start) (current-column)))
  12936. (origin (point-marker))
  12937. (column (current-column))
  12938. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  12939. (when (/= new current)
  12940. (delete-region blank-start tags-start)
  12941. (goto-char blank-start)
  12942. (let ((indent-tabs-mode nil)) (indent-to new))
  12943. ;; Try to move back to original position. If point was in the
  12944. ;; blanks before the tags, ORIGIN marker is of no use because
  12945. ;; it now points to BLANK-START. Use COLUMN instead.
  12946. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  12947. (defun org-set-tags-command (&optional arg)
  12948. "Set the tags for the current visible entry.
  12949. When called with `\\[universal-argument]' prefix argument ARG, \
  12950. realign all tags
  12951. in the current buffer. If a region is active, set tags for
  12952. all headlines in the region.
  12953. This function is for interactive use only;
  12954. in Lisp code use `org-set-tags' instead."
  12955. (interactive "P")
  12956. (cond
  12957. (arg (org-align-tags t))
  12958. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12959. ;; Disable `org-loop-over-headlines-in-active-region' for
  12960. ;; successive calls.
  12961. (let (org-loop-over-headlines-in-active-region)
  12962. (org-map-entries
  12963. #'org-set-tags-command
  12964. nil
  12965. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12966. 'region-start-level
  12967. 'region)
  12968. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12969. (t
  12970. (save-excursion
  12971. (org-back-to-heading)
  12972. (let* ((all-tags (org-get-tags))
  12973. (table (setq org-last-tags-completion-table
  12974. (org--tag-add-to-alist
  12975. (and org-complete-tags-always-offer-all-agenda-tags
  12976. (org-global-tags-completion-table
  12977. (org-agenda-files)))
  12978. (or org-current-tag-alist (org-get-buffer-tags)))))
  12979. (current-tags
  12980. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12981. all-tags))
  12982. (inherited-tags
  12983. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12984. all-tags))
  12985. (tags
  12986. (replace-regexp-in-string
  12987. ;; Ignore all forbidden characters in tags.
  12988. "[^[:alnum:]_@#%]+" ":"
  12989. (if (or (eq t org-use-fast-tag-selection)
  12990. (and org-use-fast-tag-selection
  12991. (delq nil (mapcar #'cdr table))))
  12992. (org-fast-tag-selection
  12993. current-tags
  12994. inherited-tags
  12995. table
  12996. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12997. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12998. (org-trim (completing-read
  12999. "Tags: "
  13000. #'org-tags-completion-function
  13001. nil nil (org-make-tag-string current-tags)
  13002. 'org-tags-history)))))))
  13003. (org-set-tags tags))))))
  13004. (defun org-align-tags (&optional all)
  13005. "Align tags in current entry.
  13006. When optional argument ALL is non-nil, align all tags in the
  13007. visible part of the buffer."
  13008. (let ((get-indent-column
  13009. (lambda ()
  13010. (let ((offset (if (bound-and-true-p org-indent-mode)
  13011. (* (1- org-indent-indentation-per-level)
  13012. (1- (org-current-level)))
  13013. 0)))
  13014. (+ org-tags-column
  13015. (if (> org-tags-column 0) (- offset) offset))))))
  13016. (if (and (not all) (org-at-heading-p))
  13017. (org--align-tags-here (funcall get-indent-column))
  13018. (save-excursion
  13019. (if all
  13020. (progn
  13021. (goto-char (point-min))
  13022. (while (re-search-forward org-tag-line-re nil t)
  13023. (org--align-tags-here (funcall get-indent-column))))
  13024. (org-back-to-heading t)
  13025. (org--align-tags-here (funcall get-indent-column)))))))
  13026. (defun org-set-tags (tags)
  13027. "Set the tags of the current entry to TAGS, replacing current tags.
  13028. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  13029. If TAGS is nil or the empty string, all tags are removed.
  13030. This function assumes point is on a headline."
  13031. (org-with-wide-buffer
  13032. (let ((tags (pcase tags
  13033. ((pred listp) tags)
  13034. ((pred stringp) (split-string (org-trim tags) ":" t))
  13035. (_ (error "Invalid tag specification: %S" tags))))
  13036. (old-tags (org-get-tags nil t))
  13037. (tags-change? nil))
  13038. (when (functionp org-tags-sort-function)
  13039. (setq tags (sort tags org-tags-sort-function)))
  13040. (setq tags-change? (not (equal tags old-tags)))
  13041. (when tags-change?
  13042. ;; Delete previous tags and any trailing white space.
  13043. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  13044. (line-end-position)))
  13045. (skip-chars-backward " \t")
  13046. (delete-region (point) (line-end-position))
  13047. ;; Deleting white spaces may break an otherwise empty headline.
  13048. ;; Re-introduce one space in this case.
  13049. (unless (org-at-heading-p) (insert " "))
  13050. (when tags
  13051. (save-excursion (insert " " (org-make-tag-string tags)))
  13052. ;; When text is being inserted on an invisible region
  13053. ;; boundary, it can be inadvertently sucked into
  13054. ;; invisibility.
  13055. (unless (org-invisible-p (line-beginning-position))
  13056. (org-flag-region (point) (line-end-position) nil 'outline))))
  13057. ;; Align tags, if any.
  13058. (when tags (org-align-tags))
  13059. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  13060. (defun org-change-tag-in-region (beg end tag off)
  13061. "Add or remove TAG for each entry in the region.
  13062. This works in the agenda, and also in an Org buffer."
  13063. (interactive
  13064. (list (region-beginning) (region-end)
  13065. (let ((org-last-tags-completion-table
  13066. (if (derived-mode-p 'org-mode)
  13067. (org--tag-add-to-alist
  13068. (org-get-buffer-tags)
  13069. (org-global-tags-completion-table))
  13070. (org-global-tags-completion-table))))
  13071. (completing-read
  13072. "Tag: " 'org-tags-completion-function nil nil nil
  13073. 'org-tags-history))
  13074. (progn
  13075. (message "[s]et or [r]emove? ")
  13076. (equal (read-char-exclusive) ?r))))
  13077. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13078. (let ((agendap (equal major-mode 'org-agenda-mode))
  13079. l1 l2 m buf pos newhead (cnt 0))
  13080. (goto-char end)
  13081. (setq l2 (1- (org-current-line)))
  13082. (goto-char beg)
  13083. (setq l1 (org-current-line))
  13084. (cl-loop for l from l1 to l2 do
  13085. (org-goto-line l)
  13086. (setq m (get-text-property (point) 'org-hd-marker))
  13087. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13088. (and agendap m))
  13089. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13090. pos (if agendap m (point)))
  13091. (with-current-buffer buf
  13092. (save-excursion
  13093. (save-restriction
  13094. (goto-char pos)
  13095. (setq cnt (1+ cnt))
  13096. (org-toggle-tag tag (if off 'off 'on))
  13097. (setq newhead (org-get-heading)))))
  13098. (and agendap (org-agenda-change-all-lines newhead m))))
  13099. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13100. (defun org-tags-completion-function (string _predicate &optional flag)
  13101. "Complete tag STRING.
  13102. FLAG specifies the type of completion operation to perform. This
  13103. function is passed as a collection function to `completing-read',
  13104. which see."
  13105. (let ((completion-ignore-case nil) ;tags are case-sensitive
  13106. (confirm (lambda (x) (stringp (car x))))
  13107. (prefix ""))
  13108. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13109. (setq prefix (match-string 1 string))
  13110. (setq string (match-string 2 string)))
  13111. (pcase flag
  13112. (`t (all-completions string org-last-tags-completion-table confirm))
  13113. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  13114. (`nil
  13115. (pcase (try-completion string org-last-tags-completion-table confirm)
  13116. ((and completion (pred stringp))
  13117. (concat prefix
  13118. completion
  13119. (if (and org-add-colon-after-tag-completion
  13120. (assoc completion org-last-tags-completion-table))
  13121. ":"
  13122. "")))
  13123. (completion completion)))
  13124. (_ nil))))
  13125. (defun org-fast-tag-insert (kwd tags face &optional end)
  13126. "Insert KWD, and the TAGS, the latter with face FACE.
  13127. Also insert END."
  13128. (insert (format "%-12s" (concat kwd ":"))
  13129. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13130. (or end "")))
  13131. (defun org-fast-tag-show-exit (flag)
  13132. (save-excursion
  13133. (org-goto-line 3)
  13134. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13135. (replace-match ""))
  13136. (when flag
  13137. (end-of-line 1)
  13138. (org-move-to-column (- (window-width) 19) t)
  13139. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13140. (defun org-set-current-tags-overlay (current prefix)
  13141. "Add an overlay to CURRENT tag with PREFIX."
  13142. (let ((s (org-make-tag-string current)))
  13143. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13144. (org-overlay-display org-tags-overlay (concat prefix s))))
  13145. (defvar org-last-tag-selection-key nil)
  13146. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13147. "Fast tag selection with single keys.
  13148. CURRENT is the current list of tags in the headline, INHERITED is the
  13149. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13150. possibly with grouping information. TODO-TABLE is a similar table with
  13151. TODO keywords, should these have keys assigned to them.
  13152. If the keys are nil, a-z are automatically assigned.
  13153. Returns the new tags string, or nil to not change the current settings."
  13154. (let* ((fulltable (append table todo-table))
  13155. (maxlen (if (null fulltable) 0
  13156. (apply #'max
  13157. (mapcar (lambda (x)
  13158. (if (stringp (car x)) (string-width (car x))
  13159. 0))
  13160. fulltable))))
  13161. (buf (current-buffer))
  13162. (expert (eq org-fast-tag-selection-single-key 'expert))
  13163. (buffer-tags nil)
  13164. (fwidth (+ maxlen 3 1 3))
  13165. (ncol (/ (- (window-width) 4) fwidth))
  13166. (i-face 'org-done)
  13167. (c-face 'org-todo)
  13168. tg cnt e c char c1 c2 ntable tbl rtn
  13169. ov-start ov-end ov-prefix
  13170. (exit-after-next org-fast-tag-selection-single-key)
  13171. (done-keywords org-done-keywords)
  13172. groups ingroup intaggroup)
  13173. (save-excursion
  13174. (beginning-of-line)
  13175. (if (looking-at org-tag-line-re)
  13176. (setq ov-start (match-beginning 1)
  13177. ov-end (match-end 1)
  13178. ov-prefix "")
  13179. (setq ov-start (1- (point-at-eol))
  13180. ov-end (1+ ov-start))
  13181. (skip-chars-forward "^\n\r")
  13182. (setq ov-prefix
  13183. (concat
  13184. (buffer-substring (1- (point)) (point))
  13185. (if (> (current-column) org-tags-column)
  13186. " "
  13187. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13188. (move-overlay org-tags-overlay ov-start ov-end)
  13189. (save-window-excursion
  13190. (if expert
  13191. (set-buffer (get-buffer-create " *Org tags*"))
  13192. (delete-other-windows)
  13193. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13194. (org-switch-to-buffer-other-window " *Org tags*"))
  13195. (erase-buffer)
  13196. (setq-local org-done-keywords done-keywords)
  13197. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13198. (org-fast-tag-insert "Current" current c-face "\n\n")
  13199. (org-fast-tag-show-exit exit-after-next)
  13200. (org-set-current-tags-overlay current ov-prefix)
  13201. (setq tbl fulltable char ?a cnt 0)
  13202. (while (setq e (pop tbl))
  13203. (cond
  13204. ((eq (car e) :startgroup)
  13205. (push '() groups) (setq ingroup t)
  13206. (unless (zerop cnt)
  13207. (setq cnt 0)
  13208. (insert "\n"))
  13209. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13210. ((eq (car e) :endgroup)
  13211. (setq ingroup nil cnt 0)
  13212. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13213. ((eq (car e) :startgrouptag)
  13214. (setq intaggroup t)
  13215. (unless (zerop cnt)
  13216. (setq cnt 0)
  13217. (insert "\n"))
  13218. (insert "[ "))
  13219. ((eq (car e) :endgrouptag)
  13220. (setq intaggroup nil cnt 0)
  13221. (insert "]\n"))
  13222. ((equal e '(:newline))
  13223. (unless (zerop cnt)
  13224. (setq cnt 0)
  13225. (insert "\n")
  13226. (setq e (car tbl))
  13227. (while (equal (car tbl) '(:newline))
  13228. (insert "\n")
  13229. (setq tbl (cdr tbl)))))
  13230. ((equal e '(:grouptags)) (insert " : "))
  13231. (t
  13232. (setq tg (copy-sequence (car e)) c2 nil)
  13233. (if (cdr e)
  13234. (setq c (cdr e))
  13235. ;; automatically assign a character.
  13236. (setq c1 (string-to-char
  13237. (downcase (substring
  13238. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13239. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13240. (while (or (rassoc char ntable) (rassoc char table))
  13241. (setq char (1+ char)))
  13242. (setq c2 c1))
  13243. (setq c (or c2 char)))
  13244. (when ingroup (push tg (car groups)))
  13245. (setq tg (org-add-props tg nil 'face
  13246. (cond
  13247. ((not (assoc tg table))
  13248. (org-get-todo-face tg))
  13249. ((member tg current) c-face)
  13250. ((member tg inherited) i-face))))
  13251. (when (equal (caar tbl) :grouptags)
  13252. (org-add-props tg nil 'face 'org-tag-group))
  13253. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13254. (insert "[" c "] " tg (make-string
  13255. (- fwidth 4 (length tg)) ?\ ))
  13256. (push (cons tg c) ntable)
  13257. (when (= (cl-incf cnt) ncol)
  13258. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  13259. (insert "\n")
  13260. (when (or ingroup intaggroup) (insert " ")))
  13261. (setq cnt 0)))))
  13262. (setq ntable (nreverse ntable))
  13263. (insert "\n")
  13264. (goto-char (point-min))
  13265. (unless expert (org-fit-window-to-buffer))
  13266. (setq rtn
  13267. (catch 'exit
  13268. (while t
  13269. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13270. (if (not groups) "no " "")
  13271. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13272. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13273. (setq org-last-tag-selection-key c)
  13274. (cond
  13275. ((= c ?\r) (throw 'exit t))
  13276. ((= c ?!)
  13277. (setq groups (not groups))
  13278. (goto-char (point-min))
  13279. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13280. ((= c ?\C-c)
  13281. (if (not expert)
  13282. (org-fast-tag-show-exit
  13283. (setq exit-after-next (not exit-after-next)))
  13284. (setq expert nil)
  13285. (delete-other-windows)
  13286. (set-window-buffer (split-window-vertically) " *Org tags*")
  13287. (org-switch-to-buffer-other-window " *Org tags*")
  13288. (org-fit-window-to-buffer)))
  13289. ((or (= c ?\C-g)
  13290. (and (= c ?q) (not (rassoc c ntable))))
  13291. (delete-overlay org-tags-overlay)
  13292. (setq quit-flag t))
  13293. ((= c ?\ )
  13294. (setq current nil)
  13295. (when exit-after-next (setq exit-after-next 'now)))
  13296. ((= c ?\t)
  13297. (condition-case nil
  13298. (setq tg (completing-read
  13299. "Tag: "
  13300. (or buffer-tags
  13301. (with-current-buffer buf
  13302. (setq buffer-tags
  13303. (org-get-buffer-tags))))))
  13304. (quit (setq tg "")))
  13305. (when (string-match "\\S-" tg)
  13306. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13307. (if (member tg current)
  13308. (setq current (delete tg current))
  13309. (push tg current)))
  13310. (when exit-after-next (setq exit-after-next 'now)))
  13311. ((setq e (rassoc c todo-table) tg (car e))
  13312. (with-current-buffer buf
  13313. (save-excursion (org-todo tg)))
  13314. (when exit-after-next (setq exit-after-next 'now)))
  13315. ((setq e (rassoc c ntable) tg (car e))
  13316. (if (member tg current)
  13317. (setq current (delete tg current))
  13318. (cl-loop for g in groups do
  13319. (when (member tg g)
  13320. (dolist (x g) (setq current (delete x current)))))
  13321. (push tg current))
  13322. (when exit-after-next (setq exit-after-next 'now))))
  13323. ;; Create a sorted list
  13324. (setq current
  13325. (sort current
  13326. (lambda (a b)
  13327. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13328. (when (eq exit-after-next 'now) (throw 'exit t))
  13329. (goto-char (point-min))
  13330. (beginning-of-line 2)
  13331. (delete-region (point) (point-at-eol))
  13332. (org-fast-tag-insert "Current" current c-face)
  13333. (org-set-current-tags-overlay current ov-prefix)
  13334. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13335. (while (re-search-forward tag-re nil t)
  13336. (let ((tag (match-string 1)))
  13337. (add-text-properties
  13338. (match-beginning 1) (match-end 1)
  13339. (list 'face
  13340. (cond
  13341. ((member tag current) c-face)
  13342. ((member tag inherited) i-face)
  13343. (t (get-text-property (match-beginning 1) '
  13344. face))))))))
  13345. (goto-char (point-min)))))
  13346. (delete-overlay org-tags-overlay)
  13347. (if rtn
  13348. (mapconcat 'identity current ":")
  13349. nil))))
  13350. (defun org-make-tag-string (tags)
  13351. "Return string associated to TAGS.
  13352. TAGS is a list of strings."
  13353. (if (null tags) ""
  13354. (format ":%s:" (mapconcat #'identity tags ":"))))
  13355. (defun org--get-local-tags ()
  13356. "Return list of tags for the current headline.
  13357. Assume point is at the beginning of the headline."
  13358. (and (looking-at org-tag-line-re)
  13359. (split-string (match-string-no-properties 2) ":" t)))
  13360. (defun org-get-tags (&optional pos local)
  13361. "Get the list of tags specified in the current headline.
  13362. When argument POS is non-nil, retrieve tags for headline at POS.
  13363. According to `org-use-tag-inheritance', tags may be inherited
  13364. from parent headlines, and from the whole document, through
  13365. `org-file-tags'. In this case, the returned list of tags
  13366. contains tags in this order: file tags, tags inherited from
  13367. parent headlines, local tags.
  13368. However, when optional argument LOCAL is non-nil, only return
  13369. tags specified at the headline.
  13370. Inherited tags have the `inherited' text property."
  13371. (if (and org-trust-scanner-tags
  13372. (or (not pos) (eq pos (point)))
  13373. (not local))
  13374. org-scanner-tags
  13375. (org-with-point-at (or pos (point))
  13376. (unless (org-before-first-heading-p)
  13377. (org-back-to-heading t)
  13378. (let ((ltags (org--get-local-tags)) itags)
  13379. (if (or local (not org-use-tag-inheritance)) ltags
  13380. (while (org-up-heading-safe)
  13381. (setq itags (append (mapcar #'org-add-prop-inherited
  13382. (org--get-local-tags))
  13383. itags)))
  13384. (setq itags (append org-file-tags itags))
  13385. (delete-dups
  13386. (append (org-remove-uninherited-tags itags) ltags))))))))
  13387. (defun org-get-buffer-tags ()
  13388. "Get a table of all tags used in the buffer, for completion."
  13389. (org-with-point-at 1
  13390. (let (tags)
  13391. (while (re-search-forward org-tag-line-re nil t)
  13392. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13393. tags)))
  13394. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13395. ;;;; The mapping API
  13396. (defvar org-agenda-skip-comment-trees)
  13397. (defvar org-agenda-skip-function)
  13398. (defun org-map-entries (func &optional match scope &rest skip)
  13399. "Call FUNC at each headline selected by MATCH in SCOPE.
  13400. FUNC is a function or a lisp form. The function will be called without
  13401. arguments, with the cursor positioned at the beginning of the headline.
  13402. The return values of all calls to the function will be collected and
  13403. returned as a list.
  13404. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13405. does not need to preserve point. After evaluation, the cursor will be
  13406. moved to the end of the line (presumably of the headline of the
  13407. processed entry) and search continues from there. Under some
  13408. circumstances, this may not produce the wanted results. For example,
  13409. if you have removed (e.g. archived) the current (sub)tree it could
  13410. mean that the next entry will be skipped entirely. In such cases, you
  13411. can specify the position from where search should continue by making
  13412. FUNC set the variable `org-map-continue-from' to the desired buffer
  13413. position.
  13414. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13415. Only headlines that are matched by this query will be considered during
  13416. the iteration. When MATCH is nil or t, all headlines will be
  13417. visited by the iteration.
  13418. SCOPE determines the scope of this command. It can be any of:
  13419. nil The current buffer, respecting the restriction if any
  13420. tree The subtree started with the entry at point
  13421. region The entries within the active region, if any
  13422. region-start-level
  13423. The entries within the active region, but only those at
  13424. the same level than the first one.
  13425. file The current buffer, without restriction
  13426. file-with-archives
  13427. The current buffer, and any archives associated with it
  13428. agenda All agenda files
  13429. agenda-with-archives
  13430. All agenda files with any archive files associated with them
  13431. \(file1 file2 ...)
  13432. If this is a list, all files in the list will be scanned
  13433. The remaining args are treated as settings for the skipping facilities of
  13434. the scanner. The following items can be given here:
  13435. archive skip trees with the archive tag
  13436. comment skip trees with the COMMENT keyword
  13437. function or Emacs Lisp form:
  13438. will be used as value for `org-agenda-skip-function', so
  13439. whenever the function returns a position, FUNC will not be
  13440. called for that entry and search will continue from the
  13441. position returned
  13442. If your function needs to retrieve the tags including inherited tags
  13443. at the *current* entry, you can use the value of the variable
  13444. `org-scanner-tags' which will be much faster than getting the value
  13445. with `org-get-tags'. If your function gets properties with
  13446. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13447. to t around the call to `org-entry-properties' to get the same speedup.
  13448. Note that if your function moves around to retrieve tags and properties at
  13449. a *different* entry, you cannot use these techniques."
  13450. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13451. (not (org-region-active-p)))
  13452. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13453. (org-agenda-skip-archived-trees (memq 'archive skip))
  13454. (org-agenda-skip-comment-trees (memq 'comment skip))
  13455. (org-agenda-skip-function
  13456. (car (org-delete-all '(comment archive) skip)))
  13457. (org-tags-match-list-sublevels t)
  13458. (start-level (eq scope 'region-start-level))
  13459. matcher res
  13460. org-todo-keywords-for-agenda
  13461. org-done-keywords-for-agenda
  13462. org-todo-keyword-alist-for-agenda
  13463. org-tag-alist-for-agenda
  13464. org--matcher-tags-todo-only)
  13465. (cond
  13466. ((eq match t) (setq matcher t))
  13467. ((eq match nil) (setq matcher t))
  13468. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13469. (save-excursion
  13470. (save-restriction
  13471. (cond ((eq scope 'tree)
  13472. (org-back-to-heading t)
  13473. (org-narrow-to-subtree)
  13474. (setq scope nil))
  13475. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13476. (org-region-active-p))
  13477. ;; If needed, set start-level to a string like "2"
  13478. (when start-level
  13479. (save-excursion
  13480. (goto-char (region-beginning))
  13481. (unless (org-at-heading-p) (outline-next-heading))
  13482. (setq start-level (org-current-level))))
  13483. (narrow-to-region (region-beginning)
  13484. (save-excursion
  13485. (goto-char (region-end))
  13486. (unless (and (bolp) (org-at-heading-p))
  13487. (outline-next-heading))
  13488. (point)))
  13489. (setq scope nil)))
  13490. (if (not scope)
  13491. (progn
  13492. (org-agenda-prepare-buffers
  13493. (and buffer-file-name (list buffer-file-name)))
  13494. (setq res
  13495. (org-scan-tags
  13496. func matcher org--matcher-tags-todo-only start-level)))
  13497. ;; Get the right scope
  13498. (cond
  13499. ((and scope (listp scope) (symbolp (car scope)))
  13500. (setq scope (eval scope)))
  13501. ((eq scope 'agenda)
  13502. (setq scope (org-agenda-files t)))
  13503. ((eq scope 'agenda-with-archives)
  13504. (setq scope (org-agenda-files t))
  13505. (setq scope (org-add-archive-files scope)))
  13506. ((eq scope 'file)
  13507. (setq scope (and buffer-file-name (list buffer-file-name))))
  13508. ((eq scope 'file-with-archives)
  13509. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13510. (org-agenda-prepare-buffers scope)
  13511. (dolist (file scope)
  13512. (with-current-buffer (org-find-base-buffer-visiting file)
  13513. (org-with-wide-buffer
  13514. (goto-char (point-min))
  13515. (setq res
  13516. (append
  13517. res
  13518. (org-scan-tags
  13519. func matcher org--matcher-tags-todo-only)))))))))
  13520. res)))
  13521. ;;; Properties API
  13522. (defconst org-special-properties
  13523. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13524. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13525. "The special properties valid in Org mode.
  13526. These are properties that are not defined in the property drawer,
  13527. but in some other way.")
  13528. (defconst org-default-properties
  13529. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13530. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13531. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13532. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13533. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13534. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13535. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13536. "Some properties that are used by Org mode for various purposes.
  13537. Being in this list makes sure that they are offered for completion.")
  13538. (defun org--valid-property-p (property)
  13539. "Non nil when string PROPERTY is a valid property name."
  13540. (not
  13541. (or (equal property "")
  13542. (string-match-p "\\s-" property))))
  13543. (defun org--update-property-plist (key val props)
  13544. "Associate KEY to VAL in alist PROPS.
  13545. Modifications are made by side-effect. Return new alist."
  13546. (let* ((appending (string= (substring key -1) "+"))
  13547. (key (if appending (substring key 0 -1) key))
  13548. (old (assoc-string key props t)))
  13549. (if (not old) (cons (cons key val) props)
  13550. (setcdr old (if appending (concat (cdr old) " " val) val))
  13551. props)))
  13552. (defun org-get-property-block (&optional beg force)
  13553. "Return the (beg . end) range of the body of the property drawer.
  13554. BEG is the beginning of the current subtree, or of the part
  13555. before the first headline. If it is not given, it will be found.
  13556. If the drawer does not exist, create it if FORCE is non-nil, or
  13557. return nil."
  13558. (org-with-wide-buffer
  13559. (when beg (goto-char beg))
  13560. (unless (org-before-first-heading-p)
  13561. (let ((beg (cond (beg)
  13562. ((or (not (featurep 'org-inlinetask))
  13563. (org-inlinetask-in-task-p))
  13564. (org-back-to-heading t))
  13565. (t (org-with-limited-levels (org-back-to-heading t))))))
  13566. (forward-line)
  13567. (when (looking-at-p org-planning-line-re) (forward-line))
  13568. (cond ((looking-at org-property-drawer-re)
  13569. (forward-line)
  13570. (cons (point) (progn (goto-char (match-end 0))
  13571. (line-beginning-position))))
  13572. (force
  13573. (goto-char beg)
  13574. (org-insert-property-drawer)
  13575. (let ((pos (save-excursion (search-forward ":END:")
  13576. (line-beginning-position))))
  13577. (cons pos pos))))))))
  13578. (defun org-at-property-p ()
  13579. "Non-nil when point is inside a property drawer.
  13580. See `org-property-re' for match data, if applicable."
  13581. (save-excursion
  13582. (beginning-of-line)
  13583. (and (looking-at org-property-re)
  13584. (let ((property-drawer (save-match-data (org-get-property-block))))
  13585. (and property-drawer
  13586. (>= (point) (car property-drawer))
  13587. (< (point) (cdr property-drawer)))))))
  13588. (defun org-property-action ()
  13589. "Do an action on properties."
  13590. (interactive)
  13591. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13592. (let ((c (read-char-exclusive)))
  13593. (cl-case c
  13594. (?s (call-interactively #'org-set-property))
  13595. (?d (call-interactively #'org-delete-property))
  13596. (?D (call-interactively #'org-delete-property-globally))
  13597. (?c (call-interactively #'org-compute-property-at-point))
  13598. (otherwise (user-error "No such property action %c" c)))))
  13599. (defun org-inc-effort ()
  13600. "Increment the value of the effort property in the current entry."
  13601. (interactive)
  13602. (org-set-effort t))
  13603. (defvar org-clock-effort) ; Defined in org-clock.el.
  13604. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13605. (defun org-set-effort (&optional increment value)
  13606. "Set the effort property of the current entry.
  13607. If INCREMENT is non-nil, set the property to the next allowed
  13608. value. Otherwise, if optional argument VALUE is provided, use
  13609. it. Eventually, prompt for the new value if none of the previous
  13610. variables is set."
  13611. (interactive "P")
  13612. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13613. (current (org-entry-get nil org-effort-property))
  13614. (value
  13615. (cond
  13616. (increment
  13617. (unless allowed (user-error "Allowed effort values are not set"))
  13618. (or (cl-caadr (member (list current) allowed))
  13619. (user-error "Unknown value %S among allowed values" current)))
  13620. (value
  13621. (if (stringp value) value
  13622. (error "Invalid effort value: %S" value)))
  13623. (t
  13624. (let ((must-match
  13625. (and allowed
  13626. (not (get-text-property 0 'org-unrestricted
  13627. (caar allowed))))))
  13628. (completing-read "Effort: " allowed nil must-match))))))
  13629. (unless (equal current value)
  13630. (org-entry-put nil org-effort-property value))
  13631. (org-refresh-property '((effort . identity)
  13632. (effort-minutes . org-duration-to-minutes))
  13633. value)
  13634. (when (equal (org-get-heading t t t t)
  13635. (bound-and-true-p org-clock-current-task))
  13636. (setq org-clock-effort (org-get-at-bol 'effort))
  13637. (org-clock-update-mode-line))
  13638. (message "%s is now %s" org-effort-property value)))
  13639. (defun org-entry-properties (&optional pom which)
  13640. "Get all properties of the current entry.
  13641. When POM is a buffer position, get all properties from the entry
  13642. there instead.
  13643. This includes the TODO keyword, the tags, time strings for
  13644. deadline, scheduled, and clocking, and any additional properties
  13645. defined in the entry.
  13646. If WHICH is nil or `all', get all properties. If WHICH is
  13647. `special' or `standard', only get that subclass. If WHICH is
  13648. a string, only get that property.
  13649. Return value is an alist. Keys are properties, as upcased
  13650. strings."
  13651. (org-with-point-at pom
  13652. (when (and (derived-mode-p 'org-mode)
  13653. (ignore-errors (org-back-to-heading t)))
  13654. (catch 'exit
  13655. (let* ((beg (point))
  13656. (specific (and (stringp which) (upcase which)))
  13657. (which (cond ((not specific) which)
  13658. ((member specific org-special-properties) 'special)
  13659. (t 'standard)))
  13660. props)
  13661. ;; Get the special properties, like TODO and TAGS.
  13662. (when (memq which '(nil all special))
  13663. (when (or (not specific) (string= specific "CLOCKSUM"))
  13664. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13665. (when clocksum
  13666. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13667. props)))
  13668. (when specific (throw 'exit props)))
  13669. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13670. (let ((clocksumt (get-text-property (point)
  13671. :org-clock-minutes-today)))
  13672. (when clocksumt
  13673. (push (cons "CLOCKSUM_T"
  13674. (org-duration-from-minutes clocksumt))
  13675. props)))
  13676. (when specific (throw 'exit props)))
  13677. (when (or (not specific) (string= specific "ITEM"))
  13678. (let ((case-fold-search nil))
  13679. (when (looking-at org-complex-heading-regexp)
  13680. (push (cons "ITEM"
  13681. (let ((title (match-string-no-properties 4)))
  13682. (if (org-string-nw-p title)
  13683. (org-remove-tabs title)
  13684. "")))
  13685. props)))
  13686. (when specific (throw 'exit props)))
  13687. (when (or (not specific) (string= specific "TODO"))
  13688. (let ((case-fold-search nil))
  13689. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13690. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13691. (when specific (throw 'exit props)))
  13692. (when (or (not specific) (string= specific "PRIORITY"))
  13693. (push (cons "PRIORITY"
  13694. (if (looking-at org-priority-regexp)
  13695. (match-string-no-properties 2)
  13696. (char-to-string org-default-priority)))
  13697. props)
  13698. (when specific (throw 'exit props)))
  13699. (when (or (not specific) (string= specific "FILE"))
  13700. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13701. props)
  13702. (when specific (throw 'exit props)))
  13703. (when (or (not specific) (string= specific "TAGS"))
  13704. (let ((tags (org-get-tags nil t)))
  13705. (when tags
  13706. (push (cons "TAGS" (org-make-tag-string tags))
  13707. props)))
  13708. (when specific (throw 'exit props)))
  13709. (when (or (not specific) (string= specific "ALLTAGS"))
  13710. (let ((tags (org-get-tags)))
  13711. (when tags
  13712. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13713. props)))
  13714. (when specific (throw 'exit props)))
  13715. (when (or (not specific) (string= specific "BLOCKED"))
  13716. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13717. (when specific (throw 'exit props)))
  13718. (when (or (not specific)
  13719. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13720. (forward-line)
  13721. (when (looking-at-p org-planning-line-re)
  13722. (end-of-line)
  13723. (let ((bol (line-beginning-position))
  13724. ;; Backward compatibility: time keywords used to
  13725. ;; be configurable (before 8.3). Make sure we
  13726. ;; get the correct keyword.
  13727. (key-assoc `(("CLOSED" . ,org-closed-string)
  13728. ("DEADLINE" . ,org-deadline-string)
  13729. ("SCHEDULED" . ,org-scheduled-string))))
  13730. (dolist (pair (if specific (list (assoc specific key-assoc))
  13731. key-assoc))
  13732. (save-excursion
  13733. (when (search-backward (cdr pair) bol t)
  13734. (goto-char (match-end 0))
  13735. (skip-chars-forward " \t")
  13736. (and (looking-at org-ts-regexp-both)
  13737. (push (cons (car pair)
  13738. (match-string-no-properties 0))
  13739. props)))))))
  13740. (when specific (throw 'exit props)))
  13741. (when (or (not specific)
  13742. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13743. (let ((find-ts
  13744. (lambda (end ts)
  13745. ;; Fix next time-stamp before END. TS is the
  13746. ;; list of time-stamps found so far.
  13747. (let ((ts ts)
  13748. (regexp (cond
  13749. ((string= specific "TIMESTAMP")
  13750. org-ts-regexp)
  13751. ((string= specific "TIMESTAMP_IA")
  13752. org-ts-regexp-inactive)
  13753. ((assoc "TIMESTAMP_IA" ts)
  13754. org-ts-regexp)
  13755. ((assoc "TIMESTAMP" ts)
  13756. org-ts-regexp-inactive)
  13757. (t org-ts-regexp-both))))
  13758. (catch 'next
  13759. (while (re-search-forward regexp end t)
  13760. (backward-char)
  13761. (let ((object (org-element-context)))
  13762. ;; Accept to match timestamps in node
  13763. ;; properties, too.
  13764. (when (memq (org-element-type object)
  13765. '(node-property timestamp))
  13766. (let ((type
  13767. (org-element-property :type object)))
  13768. (cond
  13769. ((and (memq type '(active active-range))
  13770. (not (equal specific "TIMESTAMP_IA")))
  13771. (unless (assoc "TIMESTAMP" ts)
  13772. (push (cons "TIMESTAMP"
  13773. (org-element-property
  13774. :raw-value object))
  13775. ts)
  13776. (when specific (throw 'exit ts))))
  13777. ((and (memq type '(inactive inactive-range))
  13778. (not (string= specific "TIMESTAMP")))
  13779. (unless (assoc "TIMESTAMP_IA" ts)
  13780. (push (cons "TIMESTAMP_IA"
  13781. (org-element-property
  13782. :raw-value object))
  13783. ts)
  13784. (when specific (throw 'exit ts))))))
  13785. ;; Both timestamp types are found,
  13786. ;; move to next part.
  13787. (when (= (length ts) 2) (throw 'next ts)))))
  13788. ts)))))
  13789. (goto-char beg)
  13790. ;; First look for timestamps within headline.
  13791. (let ((ts (funcall find-ts (line-end-position) nil)))
  13792. (if (= (length ts) 2) (setq props (nconc ts props))
  13793. ;; Then find timestamps in the section, skipping
  13794. ;; planning line.
  13795. (let ((end (save-excursion (outline-next-heading))))
  13796. (forward-line)
  13797. (when (looking-at-p org-planning-line-re) (forward-line))
  13798. (setq props (nconc (funcall find-ts end ts) props))))))))
  13799. ;; Get the standard properties, like :PROP:.
  13800. (when (memq which '(nil all standard))
  13801. ;; If we are looking after a specific property, delegate
  13802. ;; to `org-entry-get', which is faster. However, make an
  13803. ;; exception for "CATEGORY", since it can be also set
  13804. ;; through keywords (i.e. #+CATEGORY).
  13805. (if (and specific (not (equal specific "CATEGORY")))
  13806. (let ((value (org-entry-get beg specific nil t)))
  13807. (throw 'exit (and value (list (cons specific value)))))
  13808. (let ((range (org-get-property-block beg)))
  13809. (when range
  13810. (let ((end (cdr range)) seen-base)
  13811. (goto-char (car range))
  13812. ;; Unlike to `org--update-property-plist', we
  13813. ;; handle the case where base values is found
  13814. ;; after its extension. We also forbid standard
  13815. ;; properties to be named as special properties.
  13816. (while (re-search-forward org-property-re end t)
  13817. (let* ((key (upcase (match-string-no-properties 2)))
  13818. (extendp (string-match-p "\\+\\'" key))
  13819. (key-base (if extendp (substring key 0 -1) key))
  13820. (value (match-string-no-properties 3)))
  13821. (cond
  13822. ((member-ignore-case key-base org-special-properties))
  13823. (extendp
  13824. (setq props
  13825. (org--update-property-plist key value props)))
  13826. ((member key seen-base))
  13827. (t (push key seen-base)
  13828. (let ((p (assoc-string key props t)))
  13829. (if p (setcdr p (concat value " " (cdr p)))
  13830. (push (cons key value) props))))))))))))
  13831. (unless (assoc "CATEGORY" props)
  13832. (push (cons "CATEGORY" (org-get-category beg)) props)
  13833. (when (string= specific "CATEGORY") (throw 'exit props)))
  13834. ;; Return value.
  13835. props)))))
  13836. (defun org--property-local-values (property literal-nil)
  13837. "Return value for PROPERTY in current entry.
  13838. Value is a list whose car is the base value for PROPERTY and cdr
  13839. a list of accumulated values. Return nil if neither is found in
  13840. the entry. Also return nil when PROPERTY is set to \"nil\",
  13841. unless LITERAL-NIL is non-nil."
  13842. (let ((range (org-get-property-block)))
  13843. (when range
  13844. (goto-char (car range))
  13845. (let* ((case-fold-search t)
  13846. (end (cdr range))
  13847. (value
  13848. ;; Base value.
  13849. (save-excursion
  13850. (let ((v (and (re-search-forward
  13851. (org-re-property property nil t) end t)
  13852. (match-string-no-properties 3))))
  13853. (list (if literal-nil v (org-not-nil v)))))))
  13854. ;; Find additional values.
  13855. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13856. (while (re-search-forward property+ end t)
  13857. (push (match-string-no-properties 3) value)))
  13858. ;; Return final values.
  13859. (and (not (equal value '(nil))) (nreverse value))))))
  13860. (defun org--property-global-value (property literal-nil)
  13861. "Return value for PROPERTY in current buffer.
  13862. Return value is a string. Return nil if property is not set
  13863. globally. Also return nil when PROPERTY is set to \"nil\",
  13864. unless LITERAL-NIL is non-nil."
  13865. (let ((global
  13866. (cdr (or (assoc-string property org-file-properties t)
  13867. (assoc-string property org-global-properties t)
  13868. (assoc-string property org-global-properties-fixed t)))))
  13869. (if literal-nil global (org-not-nil global))))
  13870. (defun org-entry-get (pom property &optional inherit literal-nil)
  13871. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13872. If INHERIT is non-nil and the entry does not have the property,
  13873. then also check higher levels of the hierarchy. If INHERIT is
  13874. the symbol `selective', use inheritance only if the setting in
  13875. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13876. If the property is present but empty, the return value is the
  13877. empty string. If the property is not present at all, nil is
  13878. returned. In any other case, return the value as a string.
  13879. Search is case-insensitive.
  13880. If LITERAL-NIL is set, return the string value \"nil\" as
  13881. a string, do not interpret it as the list atom nil. This is used
  13882. for inheritance when a \"nil\" value can supersede a non-nil
  13883. value higher up the hierarchy."
  13884. (org-with-point-at pom
  13885. (cond
  13886. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13887. ;; We need a special property. Use `org-entry-properties' to
  13888. ;; retrieve it, but specify the wanted property.
  13889. (cdr (assoc-string property (org-entry-properties nil property))))
  13890. ((and inherit
  13891. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13892. (org-entry-get-with-inheritance property literal-nil))
  13893. (t
  13894. (let* ((local (org--property-local-values property literal-nil))
  13895. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13896. (if literal-nil value (org-not-nil value)))))))
  13897. (defun org-property-or-variable-value (var &optional inherit)
  13898. "Check if there is a property fixing the value of VAR.
  13899. If yes, return this value. If not, return the current value of the variable."
  13900. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13901. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13902. (read prop)
  13903. (symbol-value var))))
  13904. (defun org-entry-delete (pom property)
  13905. "Delete PROPERTY from entry at point-or-marker POM.
  13906. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13907. non-nil when a property was removed."
  13908. (org-with-point-at pom
  13909. (pcase (org-get-property-block)
  13910. (`(,begin . ,origin)
  13911. (let* ((end (copy-marker origin))
  13912. (re (org-re-property
  13913. (concat (regexp-quote property) "\\+?") t t)))
  13914. (goto-char begin)
  13915. (while (re-search-forward re end t)
  13916. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13917. ;; If drawer is empty, remove it altogether.
  13918. (when (= begin end)
  13919. (delete-region (line-beginning-position 0)
  13920. (line-beginning-position 2)))
  13921. ;; Return non-nil if some property was removed.
  13922. (prog1 (/= end origin) (set-marker end nil))))
  13923. (_ nil))))
  13924. ;; Multi-values properties are properties that contain multiple values
  13925. ;; These values are assumed to be single words, separated by whitespace.
  13926. (defun org-entry-add-to-multivalued-property (pom property value)
  13927. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13928. (let* ((old (org-entry-get pom property))
  13929. (values (and old (split-string old))))
  13930. (setq value (org-entry-protect-space value))
  13931. (unless (member value values)
  13932. (setq values (append values (list value)))
  13933. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13934. (defun org-entry-remove-from-multivalued-property (pom property value)
  13935. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13936. (let* ((old (org-entry-get pom property))
  13937. (values (and old (split-string old))))
  13938. (setq value (org-entry-protect-space value))
  13939. (when (member value values)
  13940. (setq values (delete value values))
  13941. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13942. (defun org-entry-member-in-multivalued-property (pom property value)
  13943. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13944. (let* ((old (org-entry-get pom property))
  13945. (values (and old (split-string old))))
  13946. (setq value (org-entry-protect-space value))
  13947. (member value values)))
  13948. (defun org-entry-get-multivalued-property (pom property)
  13949. "Return a list of values in a multivalued property."
  13950. (let* ((value (org-entry-get pom property))
  13951. (values (and value (split-string value))))
  13952. (mapcar #'org-entry-restore-space values)))
  13953. (defun org-entry-put-multivalued-property (pom property &rest values)
  13954. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13955. VALUES should be a list of strings. Spaces will be protected."
  13956. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13957. (let* ((value (org-entry-get pom property))
  13958. (values (and value (split-string value))))
  13959. (mapcar #'org-entry-restore-space values)))
  13960. (defun org-entry-protect-space (s)
  13961. "Protect spaces and newline in string S."
  13962. (while (string-match " " s)
  13963. (setq s (replace-match "%20" t t s)))
  13964. (while (string-match "\n" s)
  13965. (setq s (replace-match "%0A" t t s)))
  13966. s)
  13967. (defun org-entry-restore-space (s)
  13968. "Restore spaces and newline in string S."
  13969. (while (string-match "%20" s)
  13970. (setq s (replace-match " " t t s)))
  13971. (while (string-match "%0A" s)
  13972. (setq s (replace-match "\n" t t s)))
  13973. s)
  13974. (defvar org-entry-property-inherited-from (make-marker)
  13975. "Marker pointing to the entry from where a property was inherited.
  13976. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13977. location of the entry where the inheritance search matched. If there was
  13978. no match, the marker will point nowhere.
  13979. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13980. is set.")
  13981. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13982. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13983. The search will stop at the first ancestor which has the property defined.
  13984. If the value found is \"nil\", return nil to show that the property
  13985. should be considered as undefined (this is the meaning of nil here).
  13986. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13987. (move-marker org-entry-property-inherited-from nil)
  13988. (org-with-wide-buffer
  13989. (let (value)
  13990. (catch 'exit
  13991. (while t
  13992. (let ((v (org--property-local-values property literal-nil)))
  13993. (when v
  13994. (setq value
  13995. (concat (mapconcat #'identity (delq nil v) " ")
  13996. (and value " ")
  13997. value)))
  13998. (cond
  13999. ((car v)
  14000. (org-back-to-heading t)
  14001. (move-marker org-entry-property-inherited-from (point))
  14002. (throw 'exit nil))
  14003. ((org-up-heading-safe))
  14004. (t
  14005. (let ((global (org--property-global-value property literal-nil)))
  14006. (cond ((not global))
  14007. (value (setq value (concat global " " value)))
  14008. (t (setq value global))))
  14009. (throw 'exit nil))))))
  14010. (if literal-nil value (org-not-nil value)))))
  14011. (defvar org-property-changed-functions nil
  14012. "Hook called when the value of a property has changed.
  14013. Each hook function should accept two arguments, the name of the property
  14014. and the new value.")
  14015. (defun org-entry-put (pom property value)
  14016. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14017. If the value is nil, it is converted to the empty string. If it
  14018. is not a string, an error is raised. Also raise an error on
  14019. invalid property names.
  14020. PROPERTY can be any regular property (see
  14021. `org-special-properties'). It can also be \"TODO\",
  14022. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14023. For the last two properties, VALUE may have any of the special
  14024. values \"earlier\" and \"later\". The function then increases or
  14025. decreases scheduled or deadline date by one day."
  14026. (cond ((null value) (setq value ""))
  14027. ((not (stringp value)) (error "Properties values should be strings"))
  14028. ((not (org--valid-property-p property))
  14029. (user-error "Invalid property name: \"%s\"" property)))
  14030. (org-with-point-at pom
  14031. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14032. (org-back-to-heading t)
  14033. (org-with-limited-levels (org-back-to-heading t)))
  14034. (let ((beg (point)))
  14035. (cond
  14036. ((equal property "TODO")
  14037. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14038. ((not (member value org-todo-keywords-1))
  14039. (user-error "\"%s\" is not a valid TODO state" value)))
  14040. (org-todo value)
  14041. (org-align-tags))
  14042. ((equal property "PRIORITY")
  14043. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14044. (org-align-tags))
  14045. ((equal property "SCHEDULED")
  14046. (forward-line)
  14047. (if (and (looking-at-p org-planning-line-re)
  14048. (re-search-forward
  14049. org-scheduled-time-regexp (line-end-position) t))
  14050. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14051. ((string= value "later") (org-timestamp-change 1 'day))
  14052. ((string= value "") (org-schedule '(4)))
  14053. (t (org-schedule nil value)))
  14054. (if (member value '("earlier" "later" ""))
  14055. (call-interactively #'org-schedule)
  14056. (org-schedule nil value))))
  14057. ((equal property "DEADLINE")
  14058. (forward-line)
  14059. (if (and (looking-at-p org-planning-line-re)
  14060. (re-search-forward
  14061. org-deadline-time-regexp (line-end-position) t))
  14062. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14063. ((string= value "later") (org-timestamp-change 1 'day))
  14064. ((string= value "") (org-deadline '(4)))
  14065. (t (org-deadline nil value)))
  14066. (if (member value '("earlier" "later" ""))
  14067. (call-interactively #'org-deadline)
  14068. (org-deadline nil value))))
  14069. ((member property org-special-properties)
  14070. (error "The %s property cannot be set with `org-entry-put'" property))
  14071. (t
  14072. (let* ((range (org-get-property-block beg 'force))
  14073. (end (cdr range))
  14074. (case-fold-search t))
  14075. (goto-char (car range))
  14076. (if (re-search-forward (org-re-property property nil t) end t)
  14077. (progn (delete-region (match-beginning 0) (match-end 0))
  14078. (goto-char (match-beginning 0)))
  14079. (goto-char end)
  14080. (insert "\n")
  14081. (backward-char))
  14082. (insert ":" property ":")
  14083. (when value (insert " " value))
  14084. (org-indent-line)))))
  14085. (run-hook-with-args 'org-property-changed-functions property value)))
  14086. (defun org-buffer-property-keys (&optional specials defaults columns)
  14087. "Get all property keys in the current buffer.
  14088. When SPECIALS is non-nil, also list the special properties that
  14089. reflect things like tags and TODO state.
  14090. When DEFAULTS is non-nil, also include properties that has
  14091. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14092. DESCRIPTION, LOCATION, and LOGGING and others.
  14093. When COLUMNS in non-nil, also include property names given in
  14094. COLUMN formats in the current buffer."
  14095. (let ((case-fold-search t)
  14096. (props (append
  14097. (and specials org-special-properties)
  14098. (and defaults (cons org-effort-property org-default-properties))
  14099. nil)))
  14100. (org-with-wide-buffer
  14101. (goto-char (point-min))
  14102. (while (re-search-forward org-property-start-re nil t)
  14103. (catch :skip
  14104. (let ((range (org-get-property-block)))
  14105. (unless range (throw :skip nil))
  14106. (goto-char (car range))
  14107. (let ((begin (car range))
  14108. (end (cdr range)))
  14109. ;; Make sure that found property block is not located
  14110. ;; before current point, as it would generate an infloop.
  14111. ;; It can happen, for example, in the following
  14112. ;; situation:
  14113. ;;
  14114. ;; * Headline
  14115. ;; :PROPERTIES:
  14116. ;; ...
  14117. ;; :END:
  14118. ;; *************** Inlinetask
  14119. ;; #+BEGIN_EXAMPLE
  14120. ;; :PROPERTIES:
  14121. ;; #+END_EXAMPLE
  14122. ;;
  14123. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14124. (while (< (point) end)
  14125. (let ((p (progn (looking-at org-property-re)
  14126. (match-string-no-properties 2))))
  14127. ;; Only add true property name, not extension symbol.
  14128. (push (if (not (string-match-p "\\+\\'" p)) p
  14129. (substring p 0 -1))
  14130. props))
  14131. (forward-line))))
  14132. (outline-next-heading)))
  14133. (when columns
  14134. (goto-char (point-min))
  14135. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14136. (let ((element (org-element-at-point)))
  14137. (when (memq (org-element-type element) '(keyword node-property))
  14138. (let ((value (org-element-property :value element))
  14139. (start 0))
  14140. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14141. \\(?:{[^}]+}\\)?"
  14142. value start)
  14143. (setq start (match-end 0))
  14144. (let ((p (match-string-no-properties 1 value)))
  14145. (unless (member-ignore-case p org-special-properties)
  14146. (push p props))))))))))
  14147. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14148. (defun org-property-values (key)
  14149. "List all non-nil values of property KEY in current buffer."
  14150. (org-with-wide-buffer
  14151. (goto-char (point-min))
  14152. (let ((case-fold-search t)
  14153. (re (org-re-property key))
  14154. values)
  14155. (while (re-search-forward re nil t)
  14156. (push (org-entry-get (point) key) values))
  14157. (delete-dups values))))
  14158. (defun org-insert-property-drawer ()
  14159. "Insert a property drawer into the current entry."
  14160. (org-with-wide-buffer
  14161. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14162. (org-back-to-heading t)
  14163. (org-with-limited-levels (org-back-to-heading t)))
  14164. (forward-line)
  14165. (when (looking-at-p org-planning-line-re) (forward-line))
  14166. (unless (looking-at-p org-property-drawer-re)
  14167. ;; Make sure we start editing a line from current entry, not from
  14168. ;; next one. It prevents extending text properties or overlays
  14169. ;; belonging to the latter.
  14170. (when (bolp) (backward-char))
  14171. (let ((begin (1+ (point)))
  14172. (inhibit-read-only t))
  14173. (insert "\n:PROPERTIES:\n:END:")
  14174. (when (eobp) (insert "\n"))
  14175. (org-indent-region begin (point))))))
  14176. (defun org-insert-drawer (&optional arg drawer)
  14177. "Insert a drawer at point.
  14178. When optional argument ARG is non-nil, insert a property drawer.
  14179. Optional argument DRAWER, when non-nil, is a string representing
  14180. drawer's name. Otherwise, the user is prompted for a name.
  14181. If a region is active, insert the drawer around that region
  14182. instead.
  14183. Point is left between drawer's boundaries."
  14184. (interactive "P")
  14185. (let* ((drawer (if arg "PROPERTIES"
  14186. (or drawer (read-from-minibuffer "Drawer: ")))))
  14187. (cond
  14188. ;; With C-u, fall back on `org-insert-property-drawer'
  14189. (arg (org-insert-property-drawer))
  14190. ;; Check validity of suggested drawer's name.
  14191. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14192. (user-error "Invalid drawer name"))
  14193. ;; With an active region, insert a drawer at point.
  14194. ((not (org-region-active-p))
  14195. (progn
  14196. (unless (bolp) (insert "\n"))
  14197. (insert (format ":%s:\n\n:END:\n" drawer))
  14198. (forward-line -2)))
  14199. ;; Otherwise, insert the drawer at point
  14200. (t
  14201. (let ((rbeg (region-beginning))
  14202. (rend (copy-marker (region-end))))
  14203. (unwind-protect
  14204. (progn
  14205. (goto-char rbeg)
  14206. (beginning-of-line)
  14207. (when (save-excursion
  14208. (re-search-forward org-outline-regexp-bol rend t))
  14209. (user-error "Drawers cannot contain headlines"))
  14210. ;; Position point at the beginning of the first
  14211. ;; non-blank line in region. Insert drawer's opening
  14212. ;; there, then indent it.
  14213. (org-skip-whitespace)
  14214. (beginning-of-line)
  14215. (insert ":" drawer ":\n")
  14216. (forward-line -1)
  14217. (indent-for-tab-command)
  14218. ;; Move point to the beginning of the first blank line
  14219. ;; after the last non-blank line in region. Insert
  14220. ;; drawer's closing, then indent it.
  14221. (goto-char rend)
  14222. (skip-chars-backward " \r\t\n")
  14223. (insert "\n:END:")
  14224. (deactivate-mark t)
  14225. (indent-for-tab-command)
  14226. (unless (eolp) (insert "\n")))
  14227. ;; Clear marker, whatever the outcome of insertion is.
  14228. (set-marker rend nil)))))))
  14229. (defvar org-property-set-functions-alist nil
  14230. "Property set function alist.
  14231. Each entry should have the following format:
  14232. (PROPERTY . READ-FUNCTION)
  14233. The read function will be called with the same argument as
  14234. `org-completing-read'.")
  14235. (defun org-set-property-function (property)
  14236. "Get the function that should be used to set PROPERTY.
  14237. This is computed according to `org-property-set-functions-alist'."
  14238. (or (cdr (assoc property org-property-set-functions-alist))
  14239. 'org-completing-read))
  14240. (defun org-read-property-value (property &optional pom)
  14241. "Read value for PROPERTY, as a string.
  14242. When optional argument POM is non-nil, completion uses additional
  14243. information, i.e., allowed or existing values at point or marker
  14244. POM."
  14245. (let* ((completion-ignore-case t)
  14246. (allowed
  14247. (or (org-property-get-allowed-values nil property 'table)
  14248. (and pom (org-property-get-allowed-values pom property 'table))))
  14249. (current (org-entry-get nil property))
  14250. (prompt (format "%s value%s: "
  14251. property
  14252. (if (org-string-nw-p current)
  14253. (format " [%s]" current)
  14254. "")))
  14255. (set-function (org-set-property-function property)))
  14256. (org-trim
  14257. (if allowed
  14258. (funcall set-function
  14259. prompt allowed nil
  14260. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  14261. (let ((all (mapcar #'list
  14262. (append (org-property-values property)
  14263. (and pom
  14264. (org-with-point-at pom
  14265. (org-property-values property)))))))
  14266. (funcall set-function prompt all nil nil "" nil current))))))
  14267. (defvar org-last-set-property nil)
  14268. (defvar org-last-set-property-value nil)
  14269. (defun org-read-property-name ()
  14270. "Read a property name."
  14271. (let ((completion-ignore-case t)
  14272. (default-prop (or (and (org-at-property-p)
  14273. (match-string-no-properties 2))
  14274. org-last-set-property)))
  14275. (org-completing-read
  14276. (concat "Property"
  14277. (if default-prop (concat " [" default-prop "]") "")
  14278. ": ")
  14279. (mapcar #'list (org-buffer-property-keys nil t t))
  14280. nil nil nil nil default-prop)))
  14281. (defun org-set-property-and-value (use-last)
  14282. "Allow to set [PROPERTY]: [value] direction from prompt.
  14283. When use-default, don't even ask, just use the last
  14284. \"[PROPERTY]: [value]\" string from the history."
  14285. (interactive "P")
  14286. (let* ((completion-ignore-case t)
  14287. (pv (or (and use-last org-last-set-property-value)
  14288. (org-completing-read
  14289. "Enter a \"[Property]: [value]\" pair: "
  14290. nil nil nil nil nil
  14291. org-last-set-property-value)))
  14292. prop val)
  14293. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14294. (setq prop (match-string 1 pv)
  14295. val (match-string 2 pv))
  14296. (org-set-property prop val))))
  14297. (defun org-set-property (property value)
  14298. "In the current entry, set PROPERTY to VALUE.
  14299. When called interactively, this will prompt for a property name, offering
  14300. completion on existing and default properties. And then it will prompt
  14301. for a value, offering completion either on allowed values (via an inherited
  14302. xxx_ALL property) or on existing values in other instances of this property
  14303. in the current file.
  14304. Throw an error when trying to set a property with an invalid name."
  14305. (interactive (list nil nil))
  14306. (let ((property (or property (org-read-property-name))))
  14307. ;; `org-entry-put' also makes the following check, but this one
  14308. ;; avoids polluting `org-last-set-property' and
  14309. ;; `org-last-set-property-value' needlessly.
  14310. (unless (org--valid-property-p property)
  14311. (user-error "Invalid property name: \"%s\"" property))
  14312. (let ((value (or value (org-read-property-value property)))
  14313. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14314. (setq org-last-set-property property)
  14315. (setq org-last-set-property-value (concat property ": " value))
  14316. ;; Possibly postprocess the inserted value:
  14317. (when fn (setq value (funcall fn value)))
  14318. (unless (equal (org-entry-get nil property) value)
  14319. (org-entry-put nil property value)))))
  14320. (defun org-find-property (property &optional value)
  14321. "Find first entry in buffer that sets PROPERTY.
  14322. When optional argument VALUE is non-nil, only consider an entry
  14323. if it contains PROPERTY set to this value. If PROPERTY should be
  14324. explicitly set to nil, use string \"nil\" for VALUE.
  14325. Return position where the entry begins, or nil if there is no
  14326. such entry. If narrowing is in effect, only search the visible
  14327. part of the buffer."
  14328. (save-excursion
  14329. (goto-char (point-min))
  14330. (let ((case-fold-search t)
  14331. (re (org-re-property property nil (not value) value)))
  14332. (catch 'exit
  14333. (while (re-search-forward re nil t)
  14334. (when (if value (org-at-property-p)
  14335. (org-entry-get (point) property nil t))
  14336. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14337. (defun org-delete-property (property)
  14338. "In the current entry, delete PROPERTY."
  14339. (interactive
  14340. (let* ((completion-ignore-case t)
  14341. (cat (org-entry-get (point) "CATEGORY"))
  14342. (props0 (org-entry-properties nil 'standard))
  14343. (props (if cat props0
  14344. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14345. (prop (if (< 1 (length props))
  14346. (completing-read "Property: " props nil t)
  14347. (caar props))))
  14348. (list prop)))
  14349. (if (not property)
  14350. (message "No property to delete in this entry")
  14351. (org-entry-delete nil property)
  14352. (message "Property \"%s\" deleted" property)))
  14353. (defun org-delete-property-globally (property)
  14354. "Remove PROPERTY globally, from all entries.
  14355. This function ignores narrowing, if any."
  14356. (interactive
  14357. (let* ((completion-ignore-case t)
  14358. (prop (completing-read
  14359. "Globally remove property: "
  14360. (mapcar #'list (org-buffer-property-keys)))))
  14361. (list prop)))
  14362. (org-with-wide-buffer
  14363. (goto-char (point-min))
  14364. (let ((count 0)
  14365. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14366. (while (re-search-forward re nil t)
  14367. (when (org-entry-delete (point) property) (cl-incf count)))
  14368. (message "Property \"%s\" removed from %d entries" property count))))
  14369. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14370. (defun org-compute-property-at-point ()
  14371. "Compute the property at point.
  14372. This looks for an enclosing column format, extracts the operator and
  14373. then applies it to the property in the column format's scope."
  14374. (interactive)
  14375. (unless (org-at-property-p)
  14376. (user-error "Not at a property"))
  14377. (let ((prop (match-string-no-properties 2)))
  14378. (org-columns-get-format-and-top-level)
  14379. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14380. (user-error "No operator defined for property %s" prop))
  14381. (org-columns-compute prop)))
  14382. (defvar org-property-allowed-value-functions nil
  14383. "Hook for functions supplying allowed values for a specific property.
  14384. The functions must take a single argument, the name of the property, and
  14385. return a flat list of allowed values. If \":ETC\" is one of
  14386. the values, this means that these values are intended as defaults for
  14387. completion, but that other values should be allowed too.
  14388. The functions must return nil if they are not responsible for this
  14389. property.")
  14390. (defun org-property-get-allowed-values (pom property &optional table)
  14391. "Get allowed values for the property PROPERTY.
  14392. When TABLE is non-nil, return an alist that can directly be used for
  14393. completion."
  14394. (let (vals)
  14395. (cond
  14396. ((equal property "TODO")
  14397. (setq vals (org-with-point-at pom
  14398. (append org-todo-keywords-1 '("")))))
  14399. ((equal property "PRIORITY")
  14400. (let ((n org-lowest-priority))
  14401. (while (>= n org-highest-priority)
  14402. (push (char-to-string n) vals)
  14403. (setq n (1- n)))))
  14404. ((equal property "CATEGORY"))
  14405. ((member property org-special-properties))
  14406. ((setq vals (run-hook-with-args-until-success
  14407. 'org-property-allowed-value-functions property)))
  14408. (t
  14409. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14410. (when (and vals (string-match "\\S-" vals))
  14411. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14412. (setq vals (mapcar (lambda (x)
  14413. (cond ((stringp x) x)
  14414. ((numberp x) (number-to-string x))
  14415. ((symbolp x) (symbol-name x))
  14416. (t "???")))
  14417. vals)))))
  14418. (when (member ":ETC" vals)
  14419. (setq vals (remove ":ETC" vals))
  14420. (org-add-props (car vals) '(org-unrestricted t)))
  14421. (if table (mapcar 'list vals) vals)))
  14422. (defun org-property-previous-allowed-value (&optional _previous)
  14423. "Switch to the next allowed value for this property."
  14424. (interactive)
  14425. (org-property-next-allowed-value t))
  14426. (defun org-property-next-allowed-value (&optional previous)
  14427. "Switch to the next allowed value for this property."
  14428. (interactive)
  14429. (unless (org-at-property-p)
  14430. (user-error "Not at a property"))
  14431. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14432. (key (match-string 2))
  14433. (value (match-string 3))
  14434. (allowed (or (org-property-get-allowed-values (point) key)
  14435. (and (member value '("[ ]" "[-]" "[X]"))
  14436. '("[ ]" "[X]"))))
  14437. (heading (save-match-data (nth 4 (org-heading-components))))
  14438. nval)
  14439. (unless allowed
  14440. (user-error "Allowed values for this property have not been defined"))
  14441. (when previous (setq allowed (reverse allowed)))
  14442. (when (member value allowed)
  14443. (setq nval (car (cdr (member value allowed)))))
  14444. (setq nval (or nval (car allowed)))
  14445. (when (equal nval value)
  14446. (user-error "Only one allowed value for this property"))
  14447. (org-at-property-p)
  14448. (replace-match (concat " :" key ": " nval) t t)
  14449. (org-indent-line)
  14450. (beginning-of-line 1)
  14451. (skip-chars-forward " \t")
  14452. (when (equal prop org-effort-property)
  14453. (org-refresh-property
  14454. '((effort . identity)
  14455. (effort-minutes . org-duration-to-minutes))
  14456. nval)
  14457. (when (string= org-clock-current-task heading)
  14458. (setq org-clock-effort nval)
  14459. (org-clock-update-mode-line)))
  14460. (run-hook-with-args 'org-property-changed-functions key nval)))
  14461. (defun org-find-olp (path &optional this-buffer)
  14462. "Return a marker pointing to the entry at outline path OLP.
  14463. If anything goes wrong, throw an error.
  14464. You can wrap this call to catch the error like this:
  14465. (condition-case msg
  14466. (org-mobile-locate-entry (match-string 4))
  14467. (error (nth 1 msg)))
  14468. The return value will then be either a string with the error message,
  14469. or a marker if everything is OK.
  14470. If THIS-BUFFER is set, the outline path does not contain a file,
  14471. only headings."
  14472. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14473. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14474. (level 1)
  14475. (lmin 1)
  14476. (lmax 1)
  14477. end found flevel)
  14478. (unless buffer (error "File not found :%s" file))
  14479. (with-current-buffer buffer
  14480. (unless (derived-mode-p 'org-mode)
  14481. (error "Buffer %s needs to be in Org mode" buffer))
  14482. (org-with-wide-buffer
  14483. (goto-char (point-min))
  14484. (dolist (heading path)
  14485. (let ((re (format org-complex-heading-regexp-format
  14486. (regexp-quote heading)))
  14487. (cnt 0))
  14488. (while (re-search-forward re end t)
  14489. (setq level (- (match-end 1) (match-beginning 1)))
  14490. (when (and (>= level lmin) (<= level lmax))
  14491. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14492. (when (= cnt 0)
  14493. (error "Heading not found on level %d: %s" lmax heading))
  14494. (when (> cnt 1)
  14495. (error "Heading not unique on level %d: %s" lmax heading))
  14496. (goto-char found)
  14497. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14498. (setq end (save-excursion (org-end-of-subtree t t)))))
  14499. (when (org-at-heading-p)
  14500. (point-marker))))))
  14501. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14502. "Find node HEADING in BUFFER.
  14503. Return a marker to the heading if it was found, or nil if not.
  14504. If POS-ONLY is set, return just the position instead of a marker.
  14505. The heading text must match exact, but it may have a TODO keyword,
  14506. a priority cookie and tags in the standard locations."
  14507. (with-current-buffer (or buffer (current-buffer))
  14508. (org-with-wide-buffer
  14509. (goto-char (point-min))
  14510. (let (case-fold-search)
  14511. (when (re-search-forward
  14512. (format org-complex-heading-regexp-format
  14513. (regexp-quote heading)) nil t)
  14514. (if pos-only
  14515. (match-beginning 0)
  14516. (move-marker (make-marker) (match-beginning 0))))))))
  14517. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14518. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14519. When the target headline is found, return a marker to this location."
  14520. (let ((files (directory-files (or dir default-directory)
  14521. t "\\`[^.#].*\\.org\\'"))
  14522. visiting m buffer)
  14523. (catch 'found
  14524. (dolist (file files)
  14525. (message "trying %s" file)
  14526. (setq visiting (org-find-base-buffer-visiting file))
  14527. (setq buffer (or visiting (find-file-noselect file)))
  14528. (setq m (org-find-exact-headline-in-buffer
  14529. heading buffer))
  14530. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14531. (and m (throw 'found m))))))
  14532. (defun org-find-entry-with-id (ident)
  14533. "Locate the entry that contains the ID property with exact value IDENT.
  14534. IDENT can be a string, a symbol or a number, this function will search for
  14535. the string representation of it.
  14536. Return the position where this entry starts, or nil if there is no such entry."
  14537. (interactive "sID: ")
  14538. (let ((id (cond
  14539. ((stringp ident) ident)
  14540. ((symbolp ident) (symbol-name ident))
  14541. ((numberp ident) (number-to-string ident))
  14542. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14543. (org-with-wide-buffer (org-find-property "ID" id))))
  14544. ;;;; Timestamps
  14545. (defvar org-last-changed-timestamp nil)
  14546. (defvar org-last-inserted-timestamp nil
  14547. "The last time stamp inserted with `org-insert-time-stamp'.")
  14548. (defun org-time-stamp (arg &optional inactive)
  14549. "Prompt for a date/time and insert a time stamp.
  14550. If the user specifies a time like HH:MM or if this command is
  14551. called with at least one prefix argument, the time stamp contains
  14552. the date and the time. Otherwise, only the date is included.
  14553. All parts of a date not specified by the user are filled in from
  14554. the timestamp at point, if any, or the current date/time
  14555. otherwise.
  14556. If there is already a timestamp at the cursor, it is replaced.
  14557. With two universal prefix arguments, insert an active timestamp
  14558. with the current time without prompting the user.
  14559. When called from lisp, the timestamp is inactive if INACTIVE is
  14560. non-nil."
  14561. (interactive "P")
  14562. (let* ((ts (cond
  14563. ((org-at-date-range-p t)
  14564. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14565. ((org-at-timestamp-p 'lax) (match-string 0))))
  14566. ;; Default time is either the timestamp at point or today.
  14567. ;; When entering a range, only the range start is considered.
  14568. (default-time (if (not ts) (current-time)
  14569. (apply #'encode-time (org-parse-time-string ts))))
  14570. (default-input (and ts (org-get-compact-tod ts)))
  14571. (repeater (and ts
  14572. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14573. (match-string 0 ts)))
  14574. org-time-was-given
  14575. org-end-time-was-given
  14576. (time
  14577. (and (if (equal arg '(16)) (current-time)
  14578. ;; Preserve `this-command' and `last-command'.
  14579. (let ((this-command this-command)
  14580. (last-command last-command))
  14581. (org-read-date
  14582. arg 'totime nil nil default-time default-input
  14583. inactive))))))
  14584. (cond
  14585. ((and ts
  14586. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14587. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14588. (insert "--")
  14589. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14590. (ts
  14591. ;; Make sure we're on a timestamp. When in the middle of a date
  14592. ;; range, move arbitrarily to range end.
  14593. (unless (org-at-timestamp-p 'lax)
  14594. (skip-chars-forward "-")
  14595. (org-at-timestamp-p 'lax))
  14596. (replace-match "")
  14597. (setq org-last-changed-timestamp
  14598. (org-insert-time-stamp
  14599. time (or org-time-was-given arg)
  14600. inactive nil nil (list org-end-time-was-given)))
  14601. (when repeater
  14602. (backward-char)
  14603. (insert " " repeater)
  14604. (setq org-last-changed-timestamp
  14605. (concat (substring org-last-inserted-timestamp 0 -1)
  14606. " " repeater ">")))
  14607. (message "Timestamp updated"))
  14608. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14609. (t (org-insert-time-stamp
  14610. time (or org-time-was-given arg) inactive nil nil
  14611. (list org-end-time-was-given))))))
  14612. ;; FIXME: can we use this for something else, like computing time differences?
  14613. (defun org-get-compact-tod (s)
  14614. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14615. (let* ((t1 (match-string 1 s))
  14616. (h1 (string-to-number (match-string 2 s)))
  14617. (m1 (string-to-number (match-string 3 s)))
  14618. (t2 (and (match-end 4) (match-string 5 s)))
  14619. (h2 (and t2 (string-to-number (match-string 6 s))))
  14620. (m2 (and t2 (string-to-number (match-string 7 s))))
  14621. dh dm)
  14622. (if (not t2)
  14623. t1
  14624. (setq dh (- h2 h1) dm (- m2 m1))
  14625. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14626. (concat t1 "+" (number-to-string dh)
  14627. (and (/= 0 dm) (format ":%02d" dm)))))))
  14628. (defun org-time-stamp-inactive (&optional arg)
  14629. "Insert an inactive time stamp.
  14630. An inactive time stamp is enclosed in square brackets instead of angle
  14631. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14632. does not link to the calendar and cannot be changed with the S-cursor keys.
  14633. So these are more for recording a certain time/date.
  14634. If the user specifies a time like HH:MM or if this command is called with
  14635. at least one prefix argument, the time stamp contains the date and the time.
  14636. Otherwise, only the date is included.
  14637. When called with two universal prefix arguments, insert an active time stamp
  14638. with the current time without prompting the user."
  14639. (interactive "P")
  14640. (org-time-stamp arg 'inactive))
  14641. (defvar org-date-ovl (make-overlay 1 1))
  14642. (overlay-put org-date-ovl 'face 'org-date-selected)
  14643. (delete-overlay org-date-ovl)
  14644. (defvar org-ans1) ; dynamically scoped parameter
  14645. (defvar org-ans2) ; dynamically scoped parameter
  14646. (defvar org-plain-time-of-day-regexp) ; defined below
  14647. (defvar org-overriding-default-time nil) ; dynamically scoped
  14648. (defvar org-read-date-overlay nil)
  14649. (defvar org-dcst nil) ; dynamically scoped
  14650. (defvar org-read-date-history nil)
  14651. (defvar org-read-date-final-answer nil)
  14652. (defvar org-read-date-analyze-futurep nil)
  14653. (defvar org-read-date-analyze-forced-year nil)
  14654. (defvar org-read-date-inactive)
  14655. (defvar org-read-date-minibuffer-local-map
  14656. (let* ((map (make-sparse-keymap)))
  14657. (set-keymap-parent map minibuffer-local-map)
  14658. (org-defkey map (kbd ".")
  14659. (lambda () (interactive)
  14660. ;; Are we at the beginning of the prompt?
  14661. (if (looking-back "^[^:]+: "
  14662. (let ((inhibit-field-text-motion t))
  14663. (line-beginning-position)))
  14664. (org-eval-in-calendar '(calendar-goto-today))
  14665. (insert "."))))
  14666. (org-defkey map (kbd "C-.")
  14667. (lambda () (interactive)
  14668. (org-eval-in-calendar '(calendar-goto-today))))
  14669. (org-defkey map (kbd "M-S-<left>")
  14670. (lambda () (interactive)
  14671. (org-eval-in-calendar '(calendar-backward-month 1))))
  14672. (org-defkey map (kbd "ESC S-<left>")
  14673. (lambda () (interactive)
  14674. (org-eval-in-calendar '(calendar-backward-month 1))))
  14675. (org-defkey map (kbd "M-S-<right>")
  14676. (lambda () (interactive)
  14677. (org-eval-in-calendar '(calendar-forward-month 1))))
  14678. (org-defkey map (kbd "ESC S-<right>")
  14679. (lambda () (interactive)
  14680. (org-eval-in-calendar '(calendar-forward-month 1))))
  14681. (org-defkey map (kbd "M-S-<up>")
  14682. (lambda () (interactive)
  14683. (org-eval-in-calendar '(calendar-backward-year 1))))
  14684. (org-defkey map (kbd "ESC S-<up>")
  14685. (lambda () (interactive)
  14686. (org-eval-in-calendar '(calendar-backward-year 1))))
  14687. (org-defkey map (kbd "M-S-<down>")
  14688. (lambda () (interactive)
  14689. (org-eval-in-calendar '(calendar-forward-year 1))))
  14690. (org-defkey map (kbd "ESC S-<down>")
  14691. (lambda () (interactive)
  14692. (org-eval-in-calendar '(calendar-forward-year 1))))
  14693. (org-defkey map (kbd "S-<up>")
  14694. (lambda () (interactive)
  14695. (org-eval-in-calendar '(calendar-backward-week 1))))
  14696. (org-defkey map (kbd "S-<down>")
  14697. (lambda () (interactive)
  14698. (org-eval-in-calendar '(calendar-forward-week 1))))
  14699. (org-defkey map (kbd "S-<left>")
  14700. (lambda () (interactive)
  14701. (org-eval-in-calendar '(calendar-backward-day 1))))
  14702. (org-defkey map (kbd "S-<right>")
  14703. (lambda () (interactive)
  14704. (org-eval-in-calendar '(calendar-forward-day 1))))
  14705. (org-defkey map (kbd "!")
  14706. (lambda () (interactive)
  14707. (org-eval-in-calendar '(diary-view-entries))
  14708. (message "")))
  14709. (org-defkey map (kbd ">")
  14710. (lambda () (interactive)
  14711. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14712. (org-defkey map (kbd "<")
  14713. (lambda () (interactive)
  14714. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14715. (org-defkey map (kbd "C-v")
  14716. (lambda () (interactive)
  14717. (org-eval-in-calendar
  14718. '(calendar-scroll-left-three-months 1))))
  14719. (org-defkey map (kbd "M-v")
  14720. (lambda () (interactive)
  14721. (org-eval-in-calendar
  14722. '(calendar-scroll-right-three-months 1))))
  14723. map)
  14724. "Keymap for minibuffer commands when using `org-read-date'.")
  14725. (defvar org-def)
  14726. (defvar org-defdecode)
  14727. (defvar org-with-time)
  14728. (defvar calendar-setup) ; Dynamically scoped.
  14729. (defun org-read-date (&optional with-time to-time from-string prompt
  14730. default-time default-input inactive)
  14731. "Read a date, possibly a time, and make things smooth for the user.
  14732. The prompt will suggest to enter an ISO date, but you can also enter anything
  14733. which will at least partially be understood by `parse-time-string'.
  14734. Unrecognized parts of the date will default to the current day, month, year,
  14735. hour and minute. If this command is called to replace a timestamp at point,
  14736. or to enter the second timestamp of a range, the default time is taken
  14737. from the existing stamp. Furthermore, the command prefers the future,
  14738. so if you are giving a date where the year is not given, and the day-month
  14739. combination is already past in the current year, it will assume you
  14740. mean next year. For details, see the manual. A few examples:
  14741. 3-2-5 --> 2003-02-05
  14742. feb 15 --> currentyear-02-15
  14743. 2/15 --> currentyear-02-15
  14744. sep 12 9 --> 2009-09-12
  14745. 12:45 --> today 12:45
  14746. 22 sept 0:34 --> currentyear-09-22 0:34
  14747. 12 --> currentyear-currentmonth-12
  14748. Fri --> nearest Friday after today
  14749. -Tue --> last Tuesday
  14750. etc.
  14751. Furthermore you can specify a relative date by giving, as the *first* thing
  14752. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14753. change in days weeks, months, years.
  14754. With a single plus or minus, the date is relative to today. With a double
  14755. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14756. +4d --> four days from today
  14757. +4 --> same as above
  14758. +2w --> two weeks from today
  14759. ++5 --> five days from default date
  14760. The function understands only English month and weekday abbreviations.
  14761. While prompting, a calendar is popped up - you can also select the
  14762. date with the mouse (button 1). The calendar shows a period of three
  14763. months. To scroll it to other months, use the keys `>' and `<'.
  14764. If you don't like the calendar, turn it off with
  14765. (setq org-read-date-popup-calendar nil)
  14766. With optional argument TO-TIME, the date will immediately be converted
  14767. to an internal time.
  14768. With an optional argument WITH-TIME, the prompt will suggest to
  14769. also insert a time. Note that when WITH-TIME is not set, you can
  14770. still enter a time, and this function will inform the calling routine
  14771. about this change. The calling routine may then choose to change the
  14772. format used to insert the time stamp into the buffer to include the time.
  14773. With optional argument FROM-STRING, read from this string instead from
  14774. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14775. the time/date that is used for everything that is not specified by the
  14776. user."
  14777. (require 'parse-time)
  14778. (let* ((org-with-time with-time)
  14779. (org-time-stamp-rounding-minutes
  14780. (if (equal org-with-time '(16))
  14781. '(0 0)
  14782. org-time-stamp-rounding-minutes))
  14783. (org-dcst org-display-custom-times)
  14784. (ct (org-current-time))
  14785. (org-def (or org-overriding-default-time default-time ct))
  14786. (org-defdecode (decode-time org-def))
  14787. (cur-frame (selected-frame))
  14788. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14789. (calendar-setup
  14790. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14791. (calendar-move-hook nil)
  14792. (calendar-view-diary-initially-flag nil)
  14793. (calendar-view-holidays-initially-flag nil)
  14794. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14795. ;; Rationalize `org-def' and `org-defdecode', if required.
  14796. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14797. (setf (nth 2 org-defdecode) -1)
  14798. (setf (nth 1 org-defdecode) 59)
  14799. (setq org-def (apply #'encode-time org-defdecode))
  14800. (setq org-defdecode (decode-time org-def)))
  14801. (let* ((timestr (format-time-string
  14802. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14803. org-def))
  14804. (prompt (concat (if prompt (concat prompt " ") "")
  14805. (format "Date+time [%s]: " timestr))))
  14806. (cond
  14807. (from-string (setq ans from-string))
  14808. (org-read-date-popup-calendar
  14809. (save-excursion
  14810. (save-window-excursion
  14811. (calendar)
  14812. (when (eq calendar-setup 'calendar-only)
  14813. (setq cal-frame
  14814. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14815. (select-frame cal-frame))
  14816. (org-eval-in-calendar '(setq cursor-type nil) t)
  14817. (unwind-protect
  14818. (progn
  14819. (calendar-forward-day (- (time-to-days org-def)
  14820. (calendar-absolute-from-gregorian
  14821. (calendar-current-date))))
  14822. (org-eval-in-calendar nil t)
  14823. (let* ((old-map (current-local-map))
  14824. (map (copy-keymap calendar-mode-map))
  14825. (minibuffer-local-map
  14826. (copy-keymap org-read-date-minibuffer-local-map)))
  14827. (org-defkey map (kbd "RET") 'org-calendar-select)
  14828. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14829. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14830. (unwind-protect
  14831. (progn
  14832. (use-local-map map)
  14833. (setq org-read-date-inactive inactive)
  14834. (add-hook 'post-command-hook 'org-read-date-display)
  14835. (setq org-ans0
  14836. (read-string prompt
  14837. default-input
  14838. 'org-read-date-history
  14839. nil))
  14840. ;; org-ans0: from prompt
  14841. ;; org-ans1: from mouse click
  14842. ;; org-ans2: from calendar motion
  14843. (setq ans
  14844. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14845. (remove-hook 'post-command-hook 'org-read-date-display)
  14846. (use-local-map old-map)
  14847. (when org-read-date-overlay
  14848. (delete-overlay org-read-date-overlay)
  14849. (setq org-read-date-overlay nil)))))
  14850. (bury-buffer "*Calendar*")
  14851. (when cal-frame
  14852. (delete-frame cal-frame)
  14853. (select-frame-set-input-focus cur-frame))))))
  14854. (t ; Naked prompt only
  14855. (unwind-protect
  14856. (setq ans (read-string prompt default-input
  14857. 'org-read-date-history timestr))
  14858. (when org-read-date-overlay
  14859. (delete-overlay org-read-date-overlay)
  14860. (setq org-read-date-overlay nil))))))
  14861. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14862. (when org-read-date-analyze-forced-year
  14863. (message "Year was forced into %s"
  14864. (if org-read-date-force-compatible-dates
  14865. "compatible range (1970-2037)"
  14866. "range representable on this machine"))
  14867. (ding))
  14868. ;; One round trip to get rid of 34th of August and stuff like that....
  14869. (setq final (decode-time (apply 'encode-time final)))
  14870. (setq org-read-date-final-answer ans)
  14871. (if to-time
  14872. (apply 'encode-time final)
  14873. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14874. (format "%04d-%02d-%02d %02d:%02d"
  14875. (nth 5 final) (nth 4 final) (nth 3 final)
  14876. (nth 2 final) (nth 1 final))
  14877. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14878. (defun org-read-date-display ()
  14879. "Display the current date prompt interpretation in the minibuffer."
  14880. (when org-read-date-display-live
  14881. (when org-read-date-overlay
  14882. (delete-overlay org-read-date-overlay))
  14883. (when (minibufferp (current-buffer))
  14884. (save-excursion
  14885. (end-of-line 1)
  14886. (while (not (equal (buffer-substring
  14887. (max (point-min) (- (point) 4)) (point))
  14888. " "))
  14889. (insert " ")))
  14890. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14891. " " (or org-ans1 org-ans2)))
  14892. (org-end-time-was-given nil)
  14893. (f (org-read-date-analyze ans org-def org-defdecode))
  14894. (fmts (if org-dcst
  14895. org-time-stamp-custom-formats
  14896. org-time-stamp-formats))
  14897. (fmt (if (or org-with-time
  14898. (and (boundp 'org-time-was-given) org-time-was-given))
  14899. (cdr fmts)
  14900. (car fmts)))
  14901. (txt (format-time-string fmt (apply 'encode-time f)))
  14902. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14903. (txt (concat "=> " txt)))
  14904. (when (and org-end-time-was-given
  14905. (string-match org-plain-time-of-day-regexp txt))
  14906. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14907. org-end-time-was-given
  14908. (substring txt (match-end 0)))))
  14909. (when org-read-date-analyze-futurep
  14910. (setq txt (concat txt " (=>F)")))
  14911. (setq org-read-date-overlay
  14912. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14913. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14914. (defun org-read-date-analyze (ans def defdecode)
  14915. "Analyze the combined answer of the date prompt."
  14916. ;; FIXME: cleanup and comment
  14917. (let ((org-def def)
  14918. (org-defdecode defdecode)
  14919. (nowdecode (decode-time))
  14920. delta deltan deltaw deltadef year month day
  14921. hour minute second wday pm h2 m2 tl wday1
  14922. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14923. (setq org-read-date-analyze-futurep nil
  14924. org-read-date-analyze-forced-year nil)
  14925. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14926. (setq ans "+0"))
  14927. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14928. (setq ans (replace-match "" t t ans)
  14929. deltan (car delta)
  14930. deltaw (nth 1 delta)
  14931. deltadef (nth 2 delta)))
  14932. ;; Check if there is an iso week date in there. If yes, store the
  14933. ;; info and postpone interpreting it until the rest of the parsing
  14934. ;; is done.
  14935. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14936. (setq iso-year (when (match-end 1)
  14937. (org-small-year-to-year
  14938. (string-to-number (match-string 1 ans))))
  14939. iso-weekday (when (match-end 3)
  14940. (string-to-number (match-string 3 ans)))
  14941. iso-week (string-to-number (match-string 2 ans)))
  14942. (setq ans (replace-match "" t t ans)))
  14943. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14944. (when (string-match
  14945. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14946. (setq year (if (match-end 2)
  14947. (string-to-number (match-string 2 ans))
  14948. (progn (setq kill-year t)
  14949. (string-to-number (format-time-string "%Y"))))
  14950. month (string-to-number (match-string 3 ans))
  14951. day (string-to-number (match-string 4 ans)))
  14952. (setq year (org-small-year-to-year year))
  14953. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14954. t nil ans)))
  14955. ;; Help matching dotted european dates
  14956. (when (string-match
  14957. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14958. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14959. (setq kill-year t)
  14960. (string-to-number (format-time-string "%Y")))
  14961. day (string-to-number (match-string 1 ans))
  14962. month (string-to-number (match-string 2 ans))
  14963. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14964. t nil ans)))
  14965. ;; Help matching american dates, like 5/30 or 5/30/7
  14966. (when (string-match
  14967. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14968. (setq year (if (match-end 4)
  14969. (string-to-number (match-string 4 ans))
  14970. (progn (setq kill-year t)
  14971. (string-to-number (format-time-string "%Y"))))
  14972. month (string-to-number (match-string 1 ans))
  14973. day (string-to-number (match-string 2 ans)))
  14974. (setq year (org-small-year-to-year year))
  14975. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14976. t nil ans)))
  14977. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14978. ;; If there is a time with am/pm, and *no* time without it, we convert
  14979. ;; so that matching will be successful.
  14980. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14981. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14982. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14983. (setq hour (string-to-number (match-string 1 ans))
  14984. minute (if (match-end 3)
  14985. (string-to-number (match-string 3 ans))
  14986. 0)
  14987. pm (equal ?p
  14988. (string-to-char (downcase (match-string 4 ans)))))
  14989. (if (and (= hour 12) (not pm))
  14990. (setq hour 0)
  14991. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14992. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14993. t t ans))))
  14994. ;; Check if a time range is given as a duration
  14995. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14996. (setq hour (string-to-number (match-string 1 ans))
  14997. h2 (+ hour (string-to-number (match-string 3 ans)))
  14998. minute (string-to-number (match-string 2 ans))
  14999. m2 (+ minute (if (match-end 5) (string-to-number
  15000. (match-string 5 ans))0)))
  15001. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15002. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15003. t t ans)))
  15004. ;; Check if there is a time range
  15005. (when (boundp 'org-end-time-was-given)
  15006. (setq org-time-was-given nil)
  15007. (when (and (string-match org-plain-time-of-day-regexp ans)
  15008. (match-end 8))
  15009. (setq org-end-time-was-given (match-string 8 ans))
  15010. (setq ans (concat (substring ans 0 (match-beginning 7))
  15011. (substring ans (match-end 7))))))
  15012. (setq tl (parse-time-string ans)
  15013. day (or (nth 3 tl) (nth 3 org-defdecode))
  15014. month
  15015. (cond ((nth 4 tl))
  15016. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15017. ;; Day was specified. Make sure DAY+MONTH
  15018. ;; combination happens in the future.
  15019. ((nth 3 tl)
  15020. (setq futurep t)
  15021. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15022. (nth 4 nowdecode)))
  15023. (t (nth 4 org-defdecode)))
  15024. year
  15025. (cond ((and (not kill-year) (nth 5 tl)))
  15026. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15027. ;; Month was guessed in the future and is at least
  15028. ;; equal to NOWDECODE's. Fix year accordingly.
  15029. (futurep
  15030. (if (or (> month (nth 4 nowdecode))
  15031. (>= day (nth 3 nowdecode)))
  15032. (nth 5 nowdecode)
  15033. (1+ (nth 5 nowdecode))))
  15034. ;; Month was specified. Make sure MONTH+YEAR
  15035. ;; combination happens in the future.
  15036. ((nth 4 tl)
  15037. (setq futurep t)
  15038. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15039. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15040. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15041. (t (nth 5 nowdecode))))
  15042. (t (nth 5 org-defdecode)))
  15043. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15044. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15045. second (or (nth 0 tl) 0)
  15046. wday (nth 6 tl))
  15047. (when (and (eq org-read-date-prefer-future 'time)
  15048. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15049. (equal day (nth 3 nowdecode))
  15050. (equal month (nth 4 nowdecode))
  15051. (equal year (nth 5 nowdecode))
  15052. (nth 2 tl)
  15053. (or (< (nth 2 tl) (nth 2 nowdecode))
  15054. (and (= (nth 2 tl) (nth 2 nowdecode))
  15055. (nth 1 tl)
  15056. (< (nth 1 tl) (nth 1 nowdecode)))))
  15057. (setq day (1+ day)
  15058. futurep t))
  15059. ;; Special date definitions below
  15060. (cond
  15061. (iso-week
  15062. ;; There was an iso week
  15063. (require 'cal-iso)
  15064. (setq futurep nil)
  15065. (setq year (or iso-year year)
  15066. day (or iso-weekday wday 1)
  15067. wday nil ; to make sure that the trigger below does not match
  15068. iso-date (calendar-gregorian-from-absolute
  15069. (calendar-iso-to-absolute
  15070. (list iso-week day year))))
  15071. ; FIXME: Should we also push ISO weeks into the future?
  15072. ; (when (and org-read-date-prefer-future
  15073. ; (not iso-year)
  15074. ; (< (calendar-absolute-from-gregorian iso-date)
  15075. ; (time-to-days nil)))
  15076. ; (setq year (1+ year)
  15077. ; iso-date (calendar-gregorian-from-absolute
  15078. ; (calendar-iso-to-absolute
  15079. ; (list iso-week day year)))))
  15080. (setq month (car iso-date)
  15081. year (nth 2 iso-date)
  15082. day (nth 1 iso-date)))
  15083. (deltan
  15084. (setq futurep nil)
  15085. (unless deltadef
  15086. (let ((now (decode-time)))
  15087. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15088. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15089. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15090. ((equal deltaw "m") (setq month (+ month deltan)))
  15091. ((equal deltaw "y") (setq year (+ year deltan)))))
  15092. ((and wday (not (nth 3 tl)))
  15093. ;; Weekday was given, but no day, so pick that day in the week
  15094. ;; on or after the derived date.
  15095. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15096. (unless (equal wday wday1)
  15097. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15098. (when (and (boundp 'org-time-was-given)
  15099. (nth 2 tl))
  15100. (setq org-time-was-given t))
  15101. (when (< year 100) (setq year (+ 2000 year)))
  15102. ;; Check of the date is representable
  15103. (if org-read-date-force-compatible-dates
  15104. (progn
  15105. (when (< year 1970)
  15106. (setq year 1970 org-read-date-analyze-forced-year t))
  15107. (when (> year 2037)
  15108. (setq year 2037 org-read-date-analyze-forced-year t)))
  15109. (condition-case nil
  15110. (ignore (encode-time second minute hour day month year))
  15111. (error
  15112. (setq year (nth 5 org-defdecode))
  15113. (setq org-read-date-analyze-forced-year t))))
  15114. (setq org-read-date-analyze-futurep futurep)
  15115. (list second minute hour day month year)))
  15116. (defvar parse-time-weekdays)
  15117. (defun org-read-date-get-relative (s today default)
  15118. "Check string S for special relative date string.
  15119. TODAY and DEFAULT are internal times, for today and for a default.
  15120. Return shift list (N what def-flag)
  15121. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15122. N is the number of WHATs to shift.
  15123. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15124. the DEFAULT date rather than TODAY."
  15125. (require 'parse-time)
  15126. (when (and
  15127. (string-match
  15128. (concat
  15129. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15130. "\\([0-9]+\\)?"
  15131. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15132. "\\([ \t]\\|$\\)") s)
  15133. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15134. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15135. (string-to-char (substring (match-string 1 s) -1))
  15136. ?+))
  15137. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15138. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15139. (what (if (match-end 3) (match-string 3 s) "d"))
  15140. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15141. (date (if rel default today))
  15142. (wday (nth 6 (decode-time date)))
  15143. delta)
  15144. (if wday1
  15145. (progn
  15146. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15147. (when (= delta 0) (setq delta 7))
  15148. (when (= dir ?-)
  15149. (setq delta (- delta 7))
  15150. (when (= delta 0) (setq delta -7)))
  15151. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15152. (list delta "d" rel))
  15153. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15154. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15155. "Turn a user-specified date into the internal representation.
  15156. The internal representation needed by the calendar is (month day year).
  15157. This is a wrapper to handle the brain-dead convention in calendar that
  15158. user function argument order change dependent on argument order."
  15159. (pcase calendar-date-style
  15160. (`american (list arg1 arg2 arg3))
  15161. (`european (list arg2 arg1 arg3))
  15162. (`iso (list arg2 arg3 arg1))))
  15163. (defun org-eval-in-calendar (form &optional keepdate)
  15164. "Eval FORM in the calendar window and return to current window.
  15165. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15166. (let ((sf (selected-frame))
  15167. (sw (selected-window)))
  15168. (select-window (get-buffer-window "*Calendar*" t))
  15169. (eval form)
  15170. (when (and (not keepdate) (calendar-cursor-to-date))
  15171. (let* ((date (calendar-cursor-to-date))
  15172. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15173. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15174. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15175. (select-window sw)
  15176. (select-frame-set-input-focus sf)))
  15177. (defun org-calendar-select ()
  15178. "Return to `org-read-date' with the date currently selected.
  15179. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15180. (interactive)
  15181. (when (calendar-cursor-to-date)
  15182. (let* ((date (calendar-cursor-to-date))
  15183. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15184. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15185. (when (active-minibuffer-window) (exit-minibuffer))))
  15186. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15187. "Insert a date stamp for the date given by the internal TIME.
  15188. See `format-time-string' for the format of TIME.
  15189. WITH-HM means use the stamp format that includes the time of the day.
  15190. INACTIVE means use square brackets instead of angular ones, so that the
  15191. stamp will not contribute to the agenda.
  15192. PRE and POST are optional strings to be inserted before and after the
  15193. stamp.
  15194. The command returns the inserted time stamp."
  15195. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15196. stamp)
  15197. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15198. (insert-before-markers (or pre ""))
  15199. (when (listp extra)
  15200. (setq extra (car extra))
  15201. (if (and (stringp extra)
  15202. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15203. (setq extra (format "-%02d:%02d"
  15204. (string-to-number (match-string 1 extra))
  15205. (string-to-number (match-string 2 extra))))
  15206. (setq extra nil)))
  15207. (when extra
  15208. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15209. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15210. (insert-before-markers (or post ""))
  15211. (setq org-last-inserted-timestamp stamp)))
  15212. (defun org-toggle-time-stamp-overlays ()
  15213. "Toggle the use of custom time stamp formats."
  15214. (interactive)
  15215. (setq org-display-custom-times (not org-display-custom-times))
  15216. (unless org-display-custom-times
  15217. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15218. (while (setq p (next-single-property-change p 'display))
  15219. (when (and (get-text-property p 'display)
  15220. (eq (get-text-property p 'face) 'org-date))
  15221. (remove-text-properties
  15222. p (setq p (next-single-property-change p 'display))
  15223. '(display t))))
  15224. (set-buffer-modified-p bmp)))
  15225. (org-restart-font-lock)
  15226. (setq org-table-may-need-update t)
  15227. (if org-display-custom-times
  15228. (message "Time stamps are overlaid with custom format")
  15229. (message "Time stamp overlays removed")))
  15230. (defun org-display-custom-time (beg end)
  15231. "Overlay modified time stamp format over timestamp between BEG and END."
  15232. (let* ((ts (buffer-substring beg end))
  15233. t1 with-hm tf time str (off 0))
  15234. (save-match-data
  15235. (setq t1 (org-parse-time-string ts t))
  15236. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15237. (setq off (- (match-end 0) (match-beginning 0)))))
  15238. (setq end (- end off))
  15239. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15240. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15241. time (org-fix-decoded-time t1)
  15242. str (org-add-props
  15243. (format-time-string
  15244. (substring tf 1 -1) (apply 'encode-time time))
  15245. nil 'mouse-face 'highlight))
  15246. (put-text-property beg end 'display str)))
  15247. (defun org-fix-decoded-time (time)
  15248. "Set 0 instead of nil for the first 6 elements of time.
  15249. Don't touch the rest."
  15250. (let ((n 0))
  15251. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15252. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15253. "Difference between TIMESTAMP-STRING and now in days.
  15254. If SECONDS is non-nil, return the difference in seconds."
  15255. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15256. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15257. (funcall fdiff (current-time)))))
  15258. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15259. "Is the time in TIMESTAMP-STRING close to the current date?"
  15260. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15261. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15262. (not (org-entry-is-done-p))))
  15263. (defun org-get-wdays (ts &optional delay zero-delay)
  15264. "Get the deadline lead time appropriate for timestring TS.
  15265. When DELAY is non-nil, get the delay time for scheduled items
  15266. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15267. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15268. don't try to find the delay cookie in the scheduled timestamp."
  15269. (let ((tv (if delay org-scheduled-delay-days
  15270. org-deadline-warning-days)))
  15271. (cond
  15272. ((or (and delay (< tv 0))
  15273. (and delay zero-delay (<= tv 0))
  15274. (and (not delay) (<= tv 0)))
  15275. ;; Enforce this value no matter what
  15276. (- tv))
  15277. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15278. ;; lead time is specified.
  15279. (floor (* (string-to-number (match-string 1 ts))
  15280. (cdr (assoc (match-string 2 ts)
  15281. '(("d" . 1) ("w" . 7)
  15282. ("m" . 30.4) ("y" . 365.25)
  15283. ("h" . 0.041667)))))))
  15284. ;; go for the default.
  15285. (t tv))))
  15286. (defun org-calendar-select-mouse (ev)
  15287. "Return to `org-read-date' with the date currently selected.
  15288. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15289. (interactive "e")
  15290. (mouse-set-point ev)
  15291. (when (calendar-cursor-to-date)
  15292. (let* ((date (calendar-cursor-to-date))
  15293. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15294. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15295. (when (active-minibuffer-window) (exit-minibuffer))))
  15296. (defun org-check-deadlines (ndays)
  15297. "Check if there are any deadlines due or past due.
  15298. A deadline is considered due if it happens within `org-deadline-warning-days'
  15299. days from today's date. If the deadline appears in an entry marked DONE,
  15300. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15301. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15302. are shown."
  15303. (interactive "P")
  15304. (let* ((org-warn-days
  15305. (cond
  15306. ((equal ndays '(4)) 100000)
  15307. (ndays (prefix-numeric-value ndays))
  15308. (t (abs org-deadline-warning-days))))
  15309. (case-fold-search nil)
  15310. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15311. (callback
  15312. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15313. (message "%d deadlines past-due or due within %d days"
  15314. (org-occur regexp nil callback)
  15315. org-warn-days)))
  15316. (defsubst org-re-timestamp (type)
  15317. "Return a regexp for timestamp TYPE.
  15318. Allowed values for TYPE are:
  15319. all: all timestamps
  15320. active: only active timestamps (<...>)
  15321. inactive: only inactive timestamps ([...])
  15322. scheduled: only scheduled timestamps
  15323. deadline: only deadline timestamps
  15324. closed: only closed time-stamps
  15325. When TYPE is nil, fall back on returning a regexp that matches
  15326. both scheduled and deadline timestamps."
  15327. (cl-case type
  15328. (all org-ts-regexp-both)
  15329. (active org-ts-regexp)
  15330. (inactive org-ts-regexp-inactive)
  15331. (scheduled org-scheduled-time-regexp)
  15332. (deadline org-deadline-time-regexp)
  15333. (closed org-closed-time-regexp)
  15334. (otherwise
  15335. (concat "\\<"
  15336. (regexp-opt (list org-deadline-string org-scheduled-string))
  15337. " *<\\([^>]+\\)>"))))
  15338. (defun org-check-before-date (d)
  15339. "Check if there are deadlines or scheduled entries before date D."
  15340. (interactive (list (org-read-date)))
  15341. (let* ((case-fold-search nil)
  15342. (regexp (org-re-timestamp org-ts-type))
  15343. (ts-type org-ts-type)
  15344. (callback
  15345. (lambda ()
  15346. (let ((match (match-string 1)))
  15347. (and (if (memq ts-type '(active inactive all))
  15348. (eq (org-element-type (save-excursion
  15349. (backward-char)
  15350. (org-element-context)))
  15351. 'timestamp)
  15352. (org-at-planning-p))
  15353. (time-less-p
  15354. (org-time-string-to-time match)
  15355. (org-time-string-to-time d)))))))
  15356. (message "%d entries before %s"
  15357. (org-occur regexp nil callback)
  15358. d)))
  15359. (defun org-check-after-date (d)
  15360. "Check if there are deadlines or scheduled entries after date D."
  15361. (interactive (list (org-read-date)))
  15362. (let* ((case-fold-search nil)
  15363. (regexp (org-re-timestamp org-ts-type))
  15364. (ts-type org-ts-type)
  15365. (callback
  15366. (lambda ()
  15367. (let ((match (match-string 1)))
  15368. (and (if (memq ts-type '(active inactive all))
  15369. (eq (org-element-type (save-excursion
  15370. (backward-char)
  15371. (org-element-context)))
  15372. 'timestamp)
  15373. (org-at-planning-p))
  15374. (not (time-less-p
  15375. (org-time-string-to-time match)
  15376. (org-time-string-to-time d))))))))
  15377. (message "%d entries after %s"
  15378. (org-occur regexp nil callback)
  15379. d)))
  15380. (defun org-check-dates-range (start-date end-date)
  15381. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15382. (interactive (list (org-read-date nil nil nil "Range starts")
  15383. (org-read-date nil nil nil "Range end")))
  15384. (let ((case-fold-search nil)
  15385. (regexp (org-re-timestamp org-ts-type))
  15386. (callback
  15387. (let ((type org-ts-type))
  15388. (lambda ()
  15389. (let ((match (match-string 1)))
  15390. (and
  15391. (if (memq type '(active inactive all))
  15392. (eq (org-element-type (save-excursion
  15393. (backward-char)
  15394. (org-element-context)))
  15395. 'timestamp)
  15396. (org-at-planning-p))
  15397. (not (time-less-p
  15398. (org-time-string-to-time match)
  15399. (org-time-string-to-time start-date)))
  15400. (time-less-p
  15401. (org-time-string-to-time match)
  15402. (org-time-string-to-time end-date))))))))
  15403. (message "%d entries between %s and %s"
  15404. (org-occur regexp nil callback) start-date end-date)))
  15405. (defun org-evaluate-time-range (&optional to-buffer)
  15406. "Evaluate a time range by computing the difference between start and end.
  15407. Normally the result is just printed in the echo area, but with prefix arg
  15408. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15409. If the time range is actually in a table, the result is inserted into the
  15410. next column.
  15411. For time difference computation, a year is assumed to be exactly 365
  15412. days in order to avoid rounding problems."
  15413. (interactive "P")
  15414. (or
  15415. (org-clock-update-time-maybe)
  15416. (save-excursion
  15417. (unless (org-at-date-range-p t)
  15418. (goto-char (point-at-bol))
  15419. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15420. (unless (org-at-date-range-p t)
  15421. (user-error "Not at a time-stamp range, and none found in current line")))
  15422. (let* ((ts1 (match-string 1))
  15423. (ts2 (match-string 2))
  15424. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15425. (match-end (match-end 0))
  15426. (time1 (org-time-string-to-time ts1))
  15427. (time2 (org-time-string-to-time ts2))
  15428. (t1 (float-time time1))
  15429. (t2 (float-time time2))
  15430. (diff (abs (- t2 t1)))
  15431. (negative (< (- t2 t1) 0))
  15432. ;; (ys (floor (* 365 24 60 60)))
  15433. (ds (* 24 60 60))
  15434. (hs (* 60 60))
  15435. (fy "%dy %dd %02d:%02d")
  15436. (fy1 "%dy %dd")
  15437. (fd "%dd %02d:%02d")
  15438. (fd1 "%dd")
  15439. (fh "%02d:%02d")
  15440. y d h m align)
  15441. (if havetime
  15442. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15443. y 0
  15444. d (floor (/ diff ds)) diff (mod diff ds)
  15445. h (floor (/ diff hs)) diff (mod diff hs)
  15446. m (floor (/ diff 60)))
  15447. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15448. y 0
  15449. d (floor (+ (/ diff ds) 0.5))
  15450. h 0 m 0))
  15451. (if (not to-buffer)
  15452. (message "%s" (org-make-tdiff-string y d h m))
  15453. (if (org-at-table-p)
  15454. (progn
  15455. (goto-char match-end)
  15456. (setq align t)
  15457. (and (looking-at " *|") (goto-char (match-end 0))))
  15458. (goto-char match-end))
  15459. (when (looking-at
  15460. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15461. (replace-match ""))
  15462. (when negative (insert " -"))
  15463. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15464. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15465. (insert " " (format fh h m))))
  15466. (when align (org-table-align))
  15467. (message "Time difference inserted")))))
  15468. (defun org-make-tdiff-string (y d h m)
  15469. (let ((fmt "")
  15470. (l nil))
  15471. (when (> y 0)
  15472. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15473. (push y l))
  15474. (when (> d 0)
  15475. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15476. (push d l))
  15477. (when (> h 0)
  15478. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15479. (push h l))
  15480. (when (> m 0)
  15481. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15482. (push m l))
  15483. (apply 'format fmt (nreverse l))))
  15484. (defun org-time-string-to-time (s)
  15485. "Convert timestamp string S into internal time."
  15486. (apply #'encode-time (org-parse-time-string s)))
  15487. (defun org-time-string-to-seconds (s)
  15488. "Convert a timestamp string S into a number of seconds."
  15489. (float-time (org-time-string-to-time s)))
  15490. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15491. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15492. "Convert time stamp S to an absolute day number.
  15493. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15494. stamp, get the closest date to DAYNR. If PREFER is
  15495. `past' (respectively `future') return a date past (respectively
  15496. after) or equal to DAYNR.
  15497. POS is the location of time stamp S, as a buffer position in
  15498. BUFFER.
  15499. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15500. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15501. signaled."
  15502. (cond
  15503. ((string-match "\\`%%\\((.*)\\)" s)
  15504. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15505. ;; only able to match individual dates. If it fails, raise an
  15506. ;; error.
  15507. (if (and daynr
  15508. (org-diary-sexp-entry
  15509. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15510. daynr
  15511. (signal 'org-diary-sexp-no-match (list s))))
  15512. (daynr (org-closest-date s daynr prefer))
  15513. (t (time-to-days
  15514. (condition-case errdata
  15515. (apply #'encode-time (org-parse-time-string s))
  15516. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15517. s
  15518. (if (not (and buffer pos)) ""
  15519. (format-message " at %d in buffer `%s'" pos buffer))
  15520. (cdr errdata))))))))
  15521. (defun org-days-to-iso-week (days)
  15522. "Return the iso week number."
  15523. (require 'cal-iso)
  15524. (car (calendar-iso-from-absolute days)))
  15525. (defun org-small-year-to-year (year)
  15526. "Convert 2-digit years into 4-digit years.
  15527. YEAR is expanded into one of the 30 next years, if possible, or
  15528. into a past one. Any year larger than 99 is returned unchanged."
  15529. (if (>= year 100) year
  15530. (let* ((current (string-to-number (format-time-string "%Y")))
  15531. (century (/ current 100))
  15532. (offset (- year (% current 100))))
  15533. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15534. ((> offset -70) (+ (* century 100) year))
  15535. (t (+ (* (1+ century) 100) year))))))
  15536. (defun org-time-from-absolute (d)
  15537. "Return the time corresponding to date D.
  15538. D may be an absolute day number, or a calendar-type list (month day year)."
  15539. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15540. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15541. (defvar org-agenda-current-date)
  15542. (defun org-calendar-holiday ()
  15543. "List of holidays, for Diary display in Org mode."
  15544. (require 'holidays)
  15545. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15546. (and hl (mapconcat #'identity hl "; "))))
  15547. (defun org-diary-sexp-entry (sexp entry d)
  15548. "Process a SEXP diary ENTRY for date D."
  15549. (require 'diary-lib)
  15550. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15551. ;; dynamically.
  15552. (let* ((sexp `(let ((entry ,entry)
  15553. (date ',d))
  15554. ,(car (read-from-string sexp))))
  15555. (result (if calendar-debug-sexp (eval sexp)
  15556. (condition-case nil
  15557. (eval sexp)
  15558. (error
  15559. (beep)
  15560. (message "Bad sexp at line %d in %s: %s"
  15561. (org-current-line)
  15562. (buffer-file-name) sexp)
  15563. (sleep-for 2))))))
  15564. (cond ((stringp result) (split-string result "; "))
  15565. ((and (consp result)
  15566. (not (consp (cdr result)))
  15567. (stringp (cdr result))) (cdr result))
  15568. ((and (consp result)
  15569. (stringp (car result))) result)
  15570. (result entry))))
  15571. (defun org-diary-to-ical-string (frombuf)
  15572. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15573. This uses the icalendar.el library."
  15574. (let* ((tmpdir temporary-file-directory)
  15575. (tmpfile (make-temp-name
  15576. (expand-file-name "orgics" tmpdir)))
  15577. buf rtn b e)
  15578. (with-current-buffer frombuf
  15579. (icalendar-export-region (point-min) (point-max) tmpfile)
  15580. (setq buf (find-buffer-visiting tmpfile))
  15581. (set-buffer buf)
  15582. (goto-char (point-min))
  15583. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15584. (setq b (match-beginning 0)))
  15585. (goto-char (point-max))
  15586. (when (re-search-backward "^END:VEVENT" nil t)
  15587. (setq e (match-end 0)))
  15588. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15589. (kill-buffer buf)
  15590. (delete-file tmpfile)
  15591. rtn))
  15592. (defun org-closest-date (start current prefer)
  15593. "Return closest date to CURRENT starting from START.
  15594. CURRENT and START are both time stamps.
  15595. When PREFER is `past', return a date that is either CURRENT or
  15596. past. When PREFER is `future', return a date that is either
  15597. CURRENT or future.
  15598. Only time stamps with a repeater are modified. Any other time
  15599. stamp stay unchanged. In any case, return value is an absolute
  15600. day number."
  15601. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15602. ;; No repeater. Do not shift time stamp.
  15603. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15604. (let ((value (string-to-number (match-string 1 start)))
  15605. (type (match-string 2 start)))
  15606. (if (= 0 value)
  15607. ;; Repeater with a 0-value is considered as void.
  15608. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15609. (let* ((base (org-date-to-gregorian start))
  15610. (target (org-date-to-gregorian current))
  15611. (sday (calendar-absolute-from-gregorian base))
  15612. (cday (calendar-absolute-from-gregorian target))
  15613. n1 n2)
  15614. ;; If START is already past CURRENT, just return START.
  15615. (if (<= cday sday) sday
  15616. ;; Compute closest date before (N1) and closest date past
  15617. ;; (N2) CURRENT.
  15618. (pcase type
  15619. ("h"
  15620. (let ((missing-hours
  15621. (mod (+ (- (* 24 (- cday sday))
  15622. (nth 2 (org-parse-time-string start)))
  15623. org-extend-today-until)
  15624. value)))
  15625. (setf n1 (if (= missing-hours 0) cday
  15626. (- cday (1+ (/ missing-hours 24)))))
  15627. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15628. ((or "d" "w")
  15629. (let ((value (if (equal type "w") (* 7 value) value)))
  15630. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15631. (setf n2 (+ n1 value))))
  15632. ("m"
  15633. (let* ((add-months
  15634. (lambda (d n)
  15635. ;; Add N months to gregorian date D, i.e.,
  15636. ;; a list (MONTH DAY YEAR). Return a valid
  15637. ;; gregorian date.
  15638. (let ((m (+ (nth 0 d) n)))
  15639. (list (mod m 12)
  15640. (nth 1 d)
  15641. (+ (/ m 12) (nth 2 d))))))
  15642. (months ; Complete months to TARGET.
  15643. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15644. (- (nth 0 target) (nth 0 base))
  15645. ;; If START's day is greater than
  15646. ;; TARGET's, remove incomplete month.
  15647. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15648. value)
  15649. value))
  15650. (before (funcall add-months base months)))
  15651. (setf n1 (calendar-absolute-from-gregorian before))
  15652. (setf n2
  15653. (calendar-absolute-from-gregorian
  15654. (funcall add-months before value)))))
  15655. (_
  15656. (let* ((d (nth 1 base))
  15657. (m (nth 0 base))
  15658. (y (nth 2 base))
  15659. (years ; Complete years to TARGET.
  15660. (* (/ (- (nth 2 target)
  15661. y
  15662. ;; If START's month and day are
  15663. ;; greater than TARGET's, remove
  15664. ;; incomplete year.
  15665. (if (or (> (nth 0 target) m)
  15666. (and (= (nth 0 target) m)
  15667. (> (nth 1 target) d)))
  15668. 0
  15669. 1))
  15670. value)
  15671. value))
  15672. (before (list m d (+ y years))))
  15673. (setf n1 (calendar-absolute-from-gregorian before))
  15674. (setf n2 (calendar-absolute-from-gregorian
  15675. (list m d (+ (nth 2 before) value)))))))
  15676. ;; Handle PREFER parameter, if any.
  15677. (cond
  15678. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15679. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15680. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15681. (defun org-date-to-gregorian (d)
  15682. "Turn any specification of date D into a Gregorian date for the calendar."
  15683. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15684. ((and (listp d) (= (length d) 3)) d)
  15685. ((stringp d)
  15686. (let ((d (org-parse-time-string d)))
  15687. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15688. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15689. (defun org-timestamp-up (&optional arg)
  15690. "Increase the date item at the cursor by one.
  15691. If the cursor is on the year, change the year. If it is on the month,
  15692. the day or the time, change that. If the cursor is on the enclosing
  15693. bracket, change the timestamp type.
  15694. With prefix ARG, change by that many units."
  15695. (interactive "p")
  15696. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15697. (defun org-timestamp-down (&optional arg)
  15698. "Decrease the date item at the cursor by one.
  15699. If the cursor is on the year, change the year. If it is on the month,
  15700. the day or the time, change that. If the cursor is on the enclosing
  15701. bracket, change the timestamp type.
  15702. With prefix ARG, change by that many units."
  15703. (interactive "p")
  15704. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15705. (defun org-timestamp-up-day (&optional arg)
  15706. "Increase the date in the time stamp by one day.
  15707. With prefix ARG, change that many days."
  15708. (interactive "p")
  15709. (if (and (not (org-at-timestamp-p 'lax))
  15710. (org-at-heading-p))
  15711. (org-todo 'up)
  15712. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15713. (defun org-timestamp-down-day (&optional arg)
  15714. "Decrease the date in the time stamp by one day.
  15715. With prefix ARG, change that many days."
  15716. (interactive "p")
  15717. (if (and (not (org-at-timestamp-p 'lax))
  15718. (org-at-heading-p))
  15719. (org-todo 'down)
  15720. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15721. (defun org-at-timestamp-p (&optional extended)
  15722. "Non-nil if point is inside a timestamp.
  15723. By default, the function only consider syntactically valid active
  15724. timestamps. However, the caller may have a broader definition
  15725. for timestamps. As a consequence, optional argument EXTENDED can
  15726. be set to the following values
  15727. `inactive'
  15728. Include also syntactically valid inactive timestamps.
  15729. `agenda'
  15730. Include timestamps allowed in Agenda, i.e., those in
  15731. properties drawers, planning lines and clock lines.
  15732. `lax'
  15733. Ignore context. The function matches any part of the
  15734. document looking like a timestamp. This includes comments,
  15735. example blocks...
  15736. For backward-compatibility with Org 9.0, every other non-nil
  15737. value is equivalent to `inactive'.
  15738. When at a timestamp, return the position of the point as a symbol
  15739. among `bracket', `after', `year', `month', `hour', `minute',
  15740. `day' or a number of character from the last know part of the
  15741. time stamp.
  15742. When matching, the match groups are the following:
  15743. group 1: year
  15744. group 2: month
  15745. group 3: day number
  15746. group 4: day name
  15747. group 5: hours, if any
  15748. group 6: minutes, if any"
  15749. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15750. (pos (point))
  15751. (match?
  15752. (let ((boundaries (org-in-regexp regexp)))
  15753. (save-match-data
  15754. (cond ((null boundaries) nil)
  15755. ((eq extended 'lax) t)
  15756. (t
  15757. (or (and (eq extended 'agenda)
  15758. (or (org-at-planning-p)
  15759. (org-at-property-p)
  15760. (and (bound-and-true-p
  15761. org-agenda-include-inactive-timestamps)
  15762. (org-at-clock-log-p))))
  15763. (eq 'timestamp
  15764. (save-excursion
  15765. (when (= pos (cdr boundaries)) (forward-char -1))
  15766. (org-element-type (org-element-context)))))))))))
  15767. (cond
  15768. ((not match?) nil)
  15769. ((= pos (match-beginning 0)) 'bracket)
  15770. ;; Distinguish location right before the closing bracket from
  15771. ;; right after it.
  15772. ((= pos (1- (match-end 0))) 'bracket)
  15773. ((= pos (match-end 0)) 'after)
  15774. ((org-pos-in-match-range pos 2) 'year)
  15775. ((org-pos-in-match-range pos 3) 'month)
  15776. ((org-pos-in-match-range pos 7) 'hour)
  15777. ((org-pos-in-match-range pos 8) 'minute)
  15778. ((or (org-pos-in-match-range pos 4)
  15779. (org-pos-in-match-range pos 5)) 'day)
  15780. ((and (> pos (or (match-end 8) (match-end 5)))
  15781. (< pos (match-end 0)))
  15782. (- pos (or (match-end 8) (match-end 5))))
  15783. (t 'day))))
  15784. (defun org-toggle-timestamp-type ()
  15785. "Toggle the type (<active> or [inactive]) of a time stamp."
  15786. (interactive)
  15787. (when (org-at-timestamp-p 'lax)
  15788. (let ((beg (match-beginning 0)) (end (match-end 0))
  15789. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15790. (save-excursion
  15791. (goto-char beg)
  15792. (while (re-search-forward "[][<>]" end t)
  15793. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15794. t t)))
  15795. (message "Timestamp is now %sactive"
  15796. (if (equal (char-after beg) ?<) "" "in")))))
  15797. (defun org-at-clock-log-p ()
  15798. "Non-nil if point is on a clock log line."
  15799. (and (org-match-line org-clock-line-re)
  15800. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15801. (defvar org-clock-history) ; defined in org-clock.el
  15802. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15803. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15804. "Change the date in the time stamp at point.
  15805. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15806. `year', `minute', `second'. If WHAT is not given, the cursor position
  15807. in the timestamp determines what will be changed.
  15808. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15809. (let ((origin (point))
  15810. (timestamp? (org-at-timestamp-p 'lax))
  15811. origin-cat
  15812. with-hm inactive
  15813. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15814. extra rem
  15815. ts time time0 fixnext clrgx)
  15816. (unless timestamp? (user-error "Not at a timestamp"))
  15817. (if (and (not what) (eq timestamp? 'bracket))
  15818. (org-toggle-timestamp-type)
  15819. ;; Point isn't on brackets. Remember the part of the time-stamp
  15820. ;; the point was in. Indeed, size of time-stamps may change,
  15821. ;; but point must be kept in the same category nonetheless.
  15822. (setq origin-cat timestamp?)
  15823. (when (and (not what) (not (eq timestamp? 'day))
  15824. org-display-custom-times
  15825. (get-text-property (point) 'display)
  15826. (not (get-text-property (1- (point)) 'display)))
  15827. (setq timestamp? 'day))
  15828. (setq timestamp? (or what timestamp?)
  15829. inactive (= (char-after (match-beginning 0)) ?\[)
  15830. ts (match-string 0))
  15831. (replace-match "")
  15832. (when (string-match
  15833. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15834. ts)
  15835. (setq extra (match-string 1 ts))
  15836. (when suppress-tmp-delay
  15837. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15838. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15839. (setq with-hm t))
  15840. (setq time0 (org-parse-time-string ts))
  15841. (when (and updown
  15842. (eq timestamp? 'minute)
  15843. (not current-prefix-arg))
  15844. ;; This looks like s-up and s-down. Change by one rounding step.
  15845. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15846. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15847. (setcar (cdr time0) (+ (nth 1 time0)
  15848. (if (> n 0) (- rem) (- dm rem))))))
  15849. (setq time
  15850. (apply #'encode-time
  15851. (or (car time0) 0)
  15852. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15853. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15854. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15855. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15856. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15857. (nthcdr 6 time0)))
  15858. (when (and (memq timestamp? '(hour minute))
  15859. extra
  15860. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15861. (setq extra (org-modify-ts-extra
  15862. extra
  15863. (if (eq timestamp? 'hour) 2 5)
  15864. n dm)))
  15865. (when (integerp timestamp?)
  15866. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15867. (when (eq what 'calendar)
  15868. (let ((cal-date (org-get-date-from-calendar)))
  15869. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15870. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15871. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15872. (setcar time0 (or (car time0) 0))
  15873. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15874. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15875. (setq time (apply 'encode-time time0))))
  15876. ;; Insert the new time-stamp, and ensure point stays in the same
  15877. ;; category as before (i.e. not after the last position in that
  15878. ;; category).
  15879. (let ((pos (point)))
  15880. ;; Stay before inserted string. `save-excursion' is of no use.
  15881. (setq org-last-changed-timestamp
  15882. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15883. (goto-char pos))
  15884. (save-match-data
  15885. (looking-at org-ts-regexp3)
  15886. (goto-char
  15887. (pcase origin-cat
  15888. ;; `day' category ends before `hour' if any, or at the end
  15889. ;; of the day name.
  15890. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15891. (`hour (min (match-end 7) origin))
  15892. (`minute (min (1- (match-end 8)) origin))
  15893. ((pred integerp) (min (1- (match-end 0)) origin))
  15894. ;; Point was right after the time-stamp. However, the
  15895. ;; time-stamp length might have changed, so refer to
  15896. ;; (match-end 0) instead.
  15897. (`after (match-end 0))
  15898. ;; `year' and `month' have both fixed size: point couldn't
  15899. ;; have moved into another part.
  15900. (_ origin))))
  15901. ;; Update clock if on a CLOCK line.
  15902. (org-clock-update-time-maybe)
  15903. ;; Maybe adjust the closest clock in `org-clock-history'
  15904. (when org-clock-adjust-closest
  15905. (if (not (and (org-at-clock-log-p)
  15906. (< 1 (length (delq nil (mapcar 'marker-position
  15907. org-clock-history))))))
  15908. (message "No clock to adjust")
  15909. (cond ((save-excursion ; fix previous clock?
  15910. (re-search-backward org-ts-regexp0 nil t)
  15911. (looking-back (concat org-clock-string " \\[")
  15912. (line-beginning-position)))
  15913. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15914. ((save-excursion ; fix next clock?
  15915. (re-search-backward org-ts-regexp0 nil t)
  15916. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15917. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15918. (save-window-excursion
  15919. ;; Find closest clock to point, adjust the previous/next one in history
  15920. (let* ((p (save-excursion (org-back-to-heading t)))
  15921. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15922. (clfixnth
  15923. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15924. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15925. (if (not clfixpos)
  15926. (message "No clock to adjust")
  15927. (save-excursion
  15928. (org-goto-marker-or-bmk clfixpos)
  15929. (org-show-subtree)
  15930. (when (re-search-forward clrgx nil t)
  15931. (goto-char (match-beginning 1))
  15932. (let (org-clock-adjust-closest)
  15933. (org-timestamp-change n timestamp? updown))
  15934. (message "Clock adjusted in %s for heading: %s"
  15935. (file-name-nondirectory (buffer-file-name))
  15936. (org-get-heading t t)))))))))
  15937. ;; Try to recenter the calendar window, if any.
  15938. (when (and org-calendar-follow-timestamp-change
  15939. (get-buffer-window "*Calendar*" t)
  15940. (memq timestamp? '(day month year)))
  15941. (org-recenter-calendar (time-to-days time))))))
  15942. (defun org-modify-ts-extra (s pos n dm)
  15943. "Change the different parts of the lead-time and repeat fields in timestamp."
  15944. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15945. ng h m new rem)
  15946. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15947. (cond
  15948. ((or (org-pos-in-match-range pos 2)
  15949. (org-pos-in-match-range pos 3))
  15950. (setq m (string-to-number (match-string 3 s))
  15951. h (string-to-number (match-string 2 s)))
  15952. (if (org-pos-in-match-range pos 2)
  15953. (setq h (+ h n))
  15954. (setq n (* dm (with-no-warnings (cl-signum n))))
  15955. (unless (= 0 (setq rem (% m dm)))
  15956. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15957. (setq m (+ m n)))
  15958. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15959. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15960. (setq h (mod h 24))
  15961. (setq ng 1 new (format "-%02d:%02d" h m)))
  15962. ((org-pos-in-match-range pos 6)
  15963. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15964. ((org-pos-in-match-range pos 5)
  15965. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15966. ((org-pos-in-match-range pos 9)
  15967. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15968. ((org-pos-in-match-range pos 8)
  15969. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15970. (when ng
  15971. (setq s (concat
  15972. (substring s 0 (match-beginning ng))
  15973. new
  15974. (substring s (match-end ng))))))
  15975. s))
  15976. (defun org-recenter-calendar (d)
  15977. "If the calendar is visible, recenter it to date D."
  15978. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15979. (when cwin
  15980. (let ((calendar-move-hook nil))
  15981. (with-selected-window cwin
  15982. (calendar-goto-date
  15983. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15984. (defun org-goto-calendar (&optional arg)
  15985. "Go to the Emacs calendar at the current date.
  15986. If there is a time stamp in the current line, go to that date.
  15987. A prefix ARG can be used to force the current date."
  15988. (interactive "P")
  15989. (let ((calendar-move-hook nil)
  15990. (calendar-view-holidays-initially-flag nil)
  15991. (calendar-view-diary-initially-flag nil)
  15992. diff)
  15993. (when (or (org-at-timestamp-p 'lax)
  15994. (org-match-line (concat ".*" org-ts-regexp)))
  15995. (let ((d1 (time-to-days nil))
  15996. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15997. (setq diff (- d2 d1))))
  15998. (calendar)
  15999. (calendar-goto-today)
  16000. (when (and diff (not arg)) (calendar-forward-day diff))))
  16001. (defun org-get-date-from-calendar ()
  16002. "Return a list (month day year) of date at point in calendar."
  16003. (with-current-buffer "*Calendar*"
  16004. (save-match-data
  16005. (calendar-cursor-to-date))))
  16006. (defun org-date-from-calendar ()
  16007. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16008. If there is already a time stamp at the cursor position, update it."
  16009. (interactive)
  16010. (if (org-at-timestamp-p 'lax)
  16011. (org-timestamp-change 0 'calendar)
  16012. (let ((cal-date (org-get-date-from-calendar)))
  16013. (org-insert-time-stamp
  16014. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16015. (defcustom org-image-actual-width t
  16016. "Should we use the actual width of images when inlining them?
  16017. When set to t, always use the image width.
  16018. When set to a number, use imagemagick (when available) to set
  16019. the image's width to this value.
  16020. When set to a number in a list, try to get the width from any
  16021. #+ATTR.* keyword if it matches a width specification like
  16022. #+ATTR_HTML: :width 300px
  16023. and fall back on that number if none is found.
  16024. When set to nil, try to get the width from an #+ATTR.* keyword
  16025. and fall back on the original width if none is found.
  16026. This requires Emacs >= 24.1, build with imagemagick support."
  16027. :group 'org-appearance
  16028. :version "24.4"
  16029. :package-version '(Org . "8.0")
  16030. :type '(choice
  16031. (const :tag "Use the image width" t)
  16032. (integer :tag "Use a number of pixels")
  16033. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16034. (const :tag "Use #+ATTR* or don't resize" nil)))
  16035. (defcustom org-agenda-inhibit-startup nil
  16036. "Inhibit startup when preparing agenda buffers.
  16037. When this variable is t, the initialization of the Org agenda
  16038. buffers is inhibited: e.g. the visibility state is not set, the
  16039. tables are not re-aligned, etc."
  16040. :type 'boolean
  16041. :version "24.3"
  16042. :group 'org-agenda)
  16043. (defcustom org-agenda-ignore-properties nil
  16044. "Avoid updating text properties when building the agenda.
  16045. Properties are used to prepare buffers for effort estimates,
  16046. appointments, statistics and subtree-local categories.
  16047. If you don't use these in the agenda, you can add them to this
  16048. list and agenda building will be a bit faster.
  16049. The value is a list, with zero or more of the symbols `effort', `appt',
  16050. `stats' or `category'."
  16051. :type '(set :greedy t
  16052. (const effort)
  16053. (const appt)
  16054. (const stats)
  16055. (const category))
  16056. :version "26.1"
  16057. :package-version '(Org . "8.3")
  16058. :group 'org-agenda)
  16059. ;;;; Files
  16060. (defun org-save-all-org-buffers ()
  16061. "Save all Org buffers without user confirmation."
  16062. (interactive)
  16063. (message "Saving all Org buffers...")
  16064. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16065. (when (featurep 'org-id) (org-id-locations-save))
  16066. (message "Saving all Org buffers... done"))
  16067. (defun org-revert-all-org-buffers ()
  16068. "Revert all Org buffers.
  16069. Prompt for confirmation when there are unsaved changes.
  16070. Be sure you know what you are doing before letting this function
  16071. overwrite your changes.
  16072. This function is useful in a setup where one tracks Org files
  16073. with a version control system, to revert on one machine after pulling
  16074. changes from another. I believe the procedure must be like this:
  16075. 1. M-x org-save-all-org-buffers
  16076. 2. Pull changes from the other machine, resolve conflicts
  16077. 3. M-x org-revert-all-org-buffers"
  16078. (interactive)
  16079. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16080. (user-error "Abort"))
  16081. (save-excursion
  16082. (save-window-excursion
  16083. (dolist (b (buffer-list))
  16084. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16085. (with-current-buffer b buffer-file-name))
  16086. (pop-to-buffer-same-window b)
  16087. (revert-buffer t 'no-confirm)))
  16088. (when (and (featurep 'org-id) org-id-track-globally)
  16089. (org-id-locations-load)))))
  16090. ;;;; Agenda files
  16091. ;;;###autoload
  16092. (defun org-switchb (&optional arg)
  16093. "Switch between Org buffers.
  16094. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16095. With `\\[universal-argument] \\[universal-argument]' \
  16096. prefix, restrict available buffers to agenda files."
  16097. (interactive "P")
  16098. (let ((blist (org-buffer-list
  16099. (cond ((equal arg '(4)) 'files)
  16100. ((equal arg '(16)) 'agenda)))))
  16101. (pop-to-buffer-same-window
  16102. (completing-read "Org buffer: "
  16103. (mapcar #'list (mapcar #'buffer-name blist))
  16104. nil t))))
  16105. (defun org-buffer-list (&optional predicate exclude-tmp)
  16106. "Return a list of Org buffers.
  16107. PREDICATE can be `export', `files' or `agenda'.
  16108. export restrict the list to Export buffers.
  16109. files restrict the list to buffers visiting Org files.
  16110. agenda restrict the list to buffers visiting agenda files.
  16111. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16112. (let* ((bfn nil)
  16113. (agenda-files (and (eq predicate 'agenda)
  16114. (mapcar 'file-truename (org-agenda-files t))))
  16115. (filter
  16116. (cond
  16117. ((eq predicate 'files)
  16118. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16119. ((eq predicate 'export)
  16120. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16121. ((eq predicate 'agenda)
  16122. (lambda (b)
  16123. (with-current-buffer b
  16124. (and (derived-mode-p 'org-mode)
  16125. (setq bfn (buffer-file-name b))
  16126. (member (file-truename bfn) agenda-files)))))
  16127. (t (lambda (b) (with-current-buffer b
  16128. (or (derived-mode-p 'org-mode)
  16129. (string-match "\\*Org .*Export"
  16130. (buffer-name b)))))))))
  16131. (delq nil
  16132. (mapcar
  16133. (lambda(b)
  16134. (if (and (funcall filter b)
  16135. (or (not exclude-tmp)
  16136. (not (string-match "tmp" (buffer-name b)))))
  16137. b
  16138. nil))
  16139. (buffer-list)))))
  16140. (defun org-agenda-files (&optional unrestricted archives)
  16141. "Get the list of agenda files.
  16142. Optional UNRESTRICTED means return the full list even if a restriction
  16143. is currently in place.
  16144. When ARCHIVES is t, include all archive files that are really being
  16145. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16146. `org-agenda-archives-mode' is t."
  16147. (let ((files
  16148. (cond
  16149. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16150. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16151. ((listp org-agenda-files) org-agenda-files)
  16152. (t (error "Invalid value of `org-agenda-files'")))))
  16153. (setq files (apply 'append
  16154. (mapcar (lambda (f)
  16155. (if (file-directory-p f)
  16156. (directory-files
  16157. f t org-agenda-file-regexp)
  16158. (list f)))
  16159. files)))
  16160. (when org-agenda-skip-unavailable-files
  16161. (setq files (delq nil
  16162. (mapcar (function
  16163. (lambda (file)
  16164. (and (file-readable-p file) file)))
  16165. files))))
  16166. (when (or (eq archives t)
  16167. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16168. (setq files (org-add-archive-files files)))
  16169. files))
  16170. (defun org-agenda-file-p (&optional file)
  16171. "Return non-nil, if FILE is an agenda file.
  16172. If FILE is omitted, use the file associated with the current
  16173. buffer."
  16174. (let ((fname (or file (buffer-file-name))))
  16175. (and fname
  16176. (member (file-truename fname)
  16177. (mapcar #'file-truename (org-agenda-files t))))))
  16178. (defun org-edit-agenda-file-list ()
  16179. "Edit the list of agenda files.
  16180. Depending on setup, this either uses customize to edit the variable
  16181. `org-agenda-files', or it visits the file that is holding the list. In the
  16182. latter case, the buffer is set up in a way that saving it automatically kills
  16183. the buffer and restores the previous window configuration."
  16184. (interactive)
  16185. (if (stringp org-agenda-files)
  16186. (let ((cw (current-window-configuration)))
  16187. (find-file org-agenda-files)
  16188. (setq-local org-window-configuration cw)
  16189. (add-hook 'after-save-hook
  16190. (lambda ()
  16191. (set-window-configuration
  16192. (prog1 org-window-configuration
  16193. (kill-buffer (current-buffer))))
  16194. (org-install-agenda-files-menu)
  16195. (message "New agenda file list installed"))
  16196. nil 'local)
  16197. (message "%s" (substitute-command-keys
  16198. "Edit list and finish with \\[save-buffer]")))
  16199. (customize-variable 'org-agenda-files)))
  16200. (defun org-store-new-agenda-file-list (list)
  16201. "Set new value for the agenda file list and save it correctly."
  16202. (if (stringp org-agenda-files)
  16203. (let ((fe (org-read-agenda-file-list t)) b u)
  16204. (while (setq b (find-buffer-visiting org-agenda-files))
  16205. (kill-buffer b))
  16206. (with-temp-file org-agenda-files
  16207. (insert
  16208. (mapconcat
  16209. (lambda (f) ;; Keep un-expanded entries.
  16210. (if (setq u (assoc f fe))
  16211. (cdr u)
  16212. f))
  16213. list "\n")
  16214. "\n")))
  16215. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16216. (org-insert-mode-line-in-empty-file nil))
  16217. (setq org-agenda-files list)
  16218. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16219. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16220. "Read the list of agenda files from a file.
  16221. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16222. filenames, used by `org-store-new-agenda-file-list' to write back
  16223. un-expanded file names."
  16224. (when (file-directory-p org-agenda-files)
  16225. (error "`org-agenda-files' cannot be a single directory"))
  16226. (when (stringp org-agenda-files)
  16227. (with-temp-buffer
  16228. (insert-file-contents org-agenda-files)
  16229. (mapcar
  16230. (lambda (f)
  16231. (let ((e (expand-file-name (substitute-in-file-name f)
  16232. org-directory)))
  16233. (if pair-with-expansion
  16234. (cons e f)
  16235. e)))
  16236. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16237. ;;;###autoload
  16238. (defun org-cycle-agenda-files ()
  16239. "Cycle through the files in `org-agenda-files'.
  16240. If the current buffer visits an agenda file, find the next one in the list.
  16241. If the current buffer does not, find the first agenda file."
  16242. (interactive)
  16243. (let* ((fs (or (org-agenda-files t)
  16244. (user-error "No agenda files")))
  16245. (files (copy-sequence fs))
  16246. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16247. file)
  16248. (when tcf
  16249. (while (and (setq file (pop files))
  16250. (not (equal (file-truename file) tcf)))))
  16251. (find-file (car (or files fs)))
  16252. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16253. (defun org-agenda-file-to-front (&optional to-end)
  16254. "Move/add the current file to the top of the agenda file list.
  16255. If the file is not present in the list, it is added to the front. If it is
  16256. present, it is moved there. With optional argument TO-END, add/move to the
  16257. end of the list."
  16258. (interactive "P")
  16259. (let ((org-agenda-skip-unavailable-files nil)
  16260. (file-alist (mapcar (lambda (x)
  16261. (cons (file-truename x) x))
  16262. (org-agenda-files t)))
  16263. (ctf (file-truename
  16264. (or buffer-file-name
  16265. (user-error "Please save the current buffer to a file"))))
  16266. x had)
  16267. (setq x (assoc ctf file-alist) had x)
  16268. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16269. (if to-end
  16270. (setq file-alist (append (delq x file-alist) (list x)))
  16271. (setq file-alist (cons x (delq x file-alist))))
  16272. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16273. (org-install-agenda-files-menu)
  16274. (message "File %s to %s of agenda file list"
  16275. (if had "moved" "added") (if to-end "end" "front"))))
  16276. (defun org-remove-file (&optional file)
  16277. "Remove current file from the list of files in variable `org-agenda-files'.
  16278. These are the files which are being checked for agenda entries.
  16279. Optional argument FILE means use this file instead of the current."
  16280. (interactive)
  16281. (let* ((org-agenda-skip-unavailable-files nil)
  16282. (file (or file buffer-file-name
  16283. (user-error "Current buffer does not visit a file")))
  16284. (true-file (file-truename file))
  16285. (afile (abbreviate-file-name file))
  16286. (files (delq nil (mapcar
  16287. (lambda (x)
  16288. (unless (equal true-file
  16289. (file-truename x))
  16290. x))
  16291. (org-agenda-files t)))))
  16292. (if (not (= (length files) (length (org-agenda-files t))))
  16293. (progn
  16294. (org-store-new-agenda-file-list files)
  16295. (org-install-agenda-files-menu)
  16296. (message "Removed from Org Agenda list: %s" afile))
  16297. (message "File was not in list: %s (not removed)" afile))))
  16298. (defun org-file-menu-entry (file)
  16299. (vector file (list 'find-file file) t))
  16300. (defun org-check-agenda-file (file)
  16301. "Make sure FILE exists. If not, ask user what to do."
  16302. (unless (file-exists-p file)
  16303. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16304. (abbreviate-file-name file))
  16305. (let ((r (downcase (read-char-exclusive))))
  16306. (cond
  16307. ((equal r ?r)
  16308. (org-remove-file file)
  16309. (throw 'nextfile t))
  16310. (t (user-error "Abort"))))))
  16311. (defun org-get-agenda-file-buffer (file)
  16312. "Get an agenda buffer visiting FILE.
  16313. If the buffer needs to be created, add it to the list of buffers
  16314. which might be released later."
  16315. (let ((buf (org-find-base-buffer-visiting file)))
  16316. (if buf
  16317. buf ; just return it
  16318. ;; Make a new buffer and remember it
  16319. (setq buf (find-file-noselect file))
  16320. (when buf (push buf org-agenda-new-buffers))
  16321. buf)))
  16322. (defun org-release-buffers (blist)
  16323. "Release all buffers in list, asking the user for confirmation when needed.
  16324. When a buffer is unmodified, it is just killed. When modified, it is saved
  16325. \(if the user agrees) and then killed."
  16326. (let (file)
  16327. (dolist (buf blist)
  16328. (setq file (buffer-file-name buf))
  16329. (when (and (buffer-modified-p buf)
  16330. file
  16331. (y-or-n-p (format "Save file %s? " file)))
  16332. (with-current-buffer buf (save-buffer)))
  16333. (kill-buffer buf))))
  16334. (defun org-agenda-prepare-buffers (files)
  16335. "Create buffers for all agenda files, protect archived trees and comments."
  16336. (interactive)
  16337. (let ((pa '(:org-archived t))
  16338. (pc '(:org-comment t))
  16339. (pall '(:org-archived t :org-comment t))
  16340. (inhibit-read-only t)
  16341. (org-inhibit-startup org-agenda-inhibit-startup)
  16342. (rea (org-make-tag-string (list org-archive-tag)))
  16343. re pos)
  16344. (setq org-tag-alist-for-agenda nil
  16345. org-tag-groups-alist-for-agenda nil)
  16346. (save-excursion
  16347. (save-restriction
  16348. (dolist (file files)
  16349. (catch 'nextfile
  16350. (if (bufferp file)
  16351. (set-buffer file)
  16352. (org-check-agenda-file file)
  16353. (set-buffer (org-get-agenda-file-buffer file)))
  16354. (widen)
  16355. (org-set-regexps-and-options 'tags-only)
  16356. (setq pos (point))
  16357. (or (memq 'category org-agenda-ignore-properties)
  16358. (org-refresh-category-properties))
  16359. (or (memq 'stats org-agenda-ignore-properties)
  16360. (org-refresh-stats-properties))
  16361. (or (memq 'effort org-agenda-ignore-properties)
  16362. (org-refresh-effort-properties))
  16363. (or (memq 'appt org-agenda-ignore-properties)
  16364. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16365. (setq org-todo-keywords-for-agenda
  16366. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16367. (setq org-done-keywords-for-agenda
  16368. (append org-done-keywords-for-agenda org-done-keywords))
  16369. (setq org-todo-keyword-alist-for-agenda
  16370. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16371. (setq org-tag-alist-for-agenda
  16372. (org--tag-add-to-alist
  16373. org-tag-alist-for-agenda
  16374. org-current-tag-alist))
  16375. ;; Merge current file's tag groups into global
  16376. ;; `org-tag-groups-alist-for-agenda'.
  16377. (when org-group-tags
  16378. (dolist (alist org-tag-groups-alist)
  16379. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16380. (if old
  16381. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16382. (push alist org-tag-groups-alist-for-agenda)))))
  16383. (with-silent-modifications
  16384. (save-excursion
  16385. (remove-text-properties (point-min) (point-max) pall)
  16386. (when org-agenda-skip-archived-trees
  16387. (goto-char (point-min))
  16388. (while (re-search-forward rea nil t)
  16389. (when (org-at-heading-p t)
  16390. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16391. (goto-char (point-min))
  16392. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16393. (while (re-search-forward re nil t)
  16394. (when (save-match-data (org-in-commented-heading-p t))
  16395. (add-text-properties
  16396. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16397. (goto-char pos)))))
  16398. (setq org-todo-keywords-for-agenda
  16399. (org-uniquify org-todo-keywords-for-agenda))
  16400. (setq org-todo-keyword-alist-for-agenda
  16401. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16402. ;;;; CDLaTeX minor mode
  16403. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16404. "Keymap for the minor `org-cdlatex-mode'.")
  16405. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16406. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16407. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16408. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16409. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16410. (defvar org-cdlatex-texmathp-advice-is-done nil
  16411. "Flag remembering if we have applied the advice to texmathp already.")
  16412. (define-minor-mode org-cdlatex-mode
  16413. "Toggle the minor `org-cdlatex-mode'.
  16414. This mode supports entering LaTeX environment and math in LaTeX fragments
  16415. in Org mode.
  16416. \\{org-cdlatex-mode-map}"
  16417. nil " OCDL" nil
  16418. (when org-cdlatex-mode
  16419. (require 'cdlatex)
  16420. (run-hooks 'cdlatex-mode-hook)
  16421. (cdlatex-compute-tables))
  16422. (unless org-cdlatex-texmathp-advice-is-done
  16423. (setq org-cdlatex-texmathp-advice-is-done t)
  16424. (defadvice texmathp (around org-math-always-on activate)
  16425. "Always return t in Org buffers.
  16426. This is because we want to insert math symbols without dollars even outside
  16427. the LaTeX math segments. If Org mode thinks that point is actually inside
  16428. an embedded LaTeX fragment, let `texmathp' do its job.
  16429. `\\[org-cdlatex-mode-map]'"
  16430. (interactive)
  16431. (let (p)
  16432. (cond
  16433. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16434. ((eq this-command 'cdlatex-math-symbol)
  16435. (setq ad-return-value t
  16436. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16437. (t
  16438. (let ((p (org-inside-LaTeX-fragment-p)))
  16439. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16440. (setq ad-return-value t
  16441. texmathp-why '("Org mode embedded math" . 0))
  16442. (when p ad-do-it)))))))))
  16443. (defun turn-on-org-cdlatex ()
  16444. "Unconditionally turn on `org-cdlatex-mode'."
  16445. (org-cdlatex-mode 1))
  16446. (defun org-try-cdlatex-tab ()
  16447. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16448. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16449. - inside a LaTeX fragment, or
  16450. - after the first word in a line, where an abbreviation expansion could
  16451. insert a LaTeX environment."
  16452. (when org-cdlatex-mode
  16453. (cond
  16454. ;; Before any word on the line: No expansion possible.
  16455. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16456. ;; Just after first word on the line: Expand it. Make sure it
  16457. ;; cannot happen on headlines, though.
  16458. ((save-excursion
  16459. (skip-chars-backward "a-zA-Z0-9*")
  16460. (skip-chars-backward " \t")
  16461. (and (bolp) (not (org-at-heading-p))))
  16462. (cdlatex-tab) t)
  16463. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16464. (defun org-cdlatex-underscore-caret (&optional _arg)
  16465. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16466. Revert to the normal definition outside of these fragments."
  16467. (interactive "P")
  16468. (if (org-inside-LaTeX-fragment-p)
  16469. (call-interactively 'cdlatex-sub-superscript)
  16470. (let (org-cdlatex-mode)
  16471. (call-interactively (key-binding (vector last-input-event))))))
  16472. (defun org-cdlatex-math-modify (&optional _arg)
  16473. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16474. Revert to the normal definition outside of these fragments."
  16475. (interactive "P")
  16476. (if (org-inside-LaTeX-fragment-p)
  16477. (call-interactively 'cdlatex-math-modify)
  16478. (let (org-cdlatex-mode)
  16479. (call-interactively (key-binding (vector last-input-event))))))
  16480. (defun org-cdlatex-environment-indent (&optional environment item)
  16481. "Execute `cdlatex-environment' and indent the inserted environment.
  16482. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16483. The inserted environment is indented to current indentation
  16484. unless point is at the beginning of the line, in which the
  16485. environment remains unintended."
  16486. (interactive)
  16487. ;; cdlatex-environment always return nil. Therefore, capture output
  16488. ;; first and determine if an environment was selected.
  16489. (let* ((beg (point-marker))
  16490. (end (copy-marker (point) t))
  16491. (inserted (progn
  16492. (ignore-errors (cdlatex-environment environment item))
  16493. (< beg end)))
  16494. ;; Figure out how many lines to move forward after the
  16495. ;; environment has been inserted.
  16496. (lines (when inserted
  16497. (save-excursion
  16498. (- (cl-loop while (< beg (point))
  16499. with x = 0
  16500. do (forward-line -1)
  16501. (cl-incf x)
  16502. finally return x)
  16503. (if (progn (goto-char beg)
  16504. (and (progn (skip-chars-forward " \t") (eolp))
  16505. (progn (skip-chars-backward " \t") (bolp))))
  16506. 1 0)))))
  16507. (env (org-trim (delete-and-extract-region beg end))))
  16508. (when inserted
  16509. ;; Get indentation of next line unless at column 0.
  16510. (let ((ind (if (bolp) 0
  16511. (save-excursion
  16512. (org-return-indent)
  16513. (prog1 (current-indentation)
  16514. (when (progn (skip-chars-forward " \t") (eolp))
  16515. (delete-region beg (point)))))))
  16516. (bol (progn (skip-chars-backward " \t") (bolp))))
  16517. ;; Insert a newline before environment unless at column zero
  16518. ;; to "escape" the current line. Insert a newline if
  16519. ;; something is one the same line as \end{ENVIRONMENT}.
  16520. (insert
  16521. (concat (unless bol "\n") env
  16522. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16523. (unless (zerop ind)
  16524. (save-excursion
  16525. (goto-char beg)
  16526. (while (< (point) end)
  16527. (unless (eolp) (indent-line-to ind))
  16528. (forward-line))))
  16529. (goto-char beg)
  16530. (forward-line lines)
  16531. (indent-line-to ind)))
  16532. (set-marker beg nil)
  16533. (set-marker end nil)))
  16534. ;;;; LaTeX fragments
  16535. (defun org-inside-LaTeX-fragment-p ()
  16536. "Test if point is inside a LaTeX fragment.
  16537. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16538. sequence appearing also before point.
  16539. Even though the matchers for math are configurable, this function assumes
  16540. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16541. delimiters are skipped when they have been removed by customization.
  16542. The return value is nil, or a cons cell with the delimiter and the
  16543. position of this delimiter.
  16544. This function does a reasonably good job, but can locally be fooled by
  16545. for example currency specifications. For example it will assume being in
  16546. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16547. fragments that are properly closed, but during editing, we have to live
  16548. with the uncertainty caused by missing closing delimiters. This function
  16549. looks only before point, not after."
  16550. (catch 'exit
  16551. (let ((pos (point))
  16552. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16553. (lim (save-excursion (org-backward-paragraph) (point)))
  16554. dd-on str (start 0) m re)
  16555. (goto-char pos)
  16556. (when dodollar
  16557. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16558. re (nth 1 (assoc "$" org-latex-regexps)))
  16559. (while (string-match re str start)
  16560. (cond
  16561. ((= (match-end 0) (length str))
  16562. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16563. ((= (match-end 0) (- (length str) 5))
  16564. (throw 'exit nil))
  16565. (t (setq start (match-end 0))))))
  16566. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16567. (goto-char pos)
  16568. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16569. (and (match-beginning 2) (throw 'exit nil))
  16570. ;; count $$
  16571. (while (re-search-backward "\\$\\$" lim t)
  16572. (setq dd-on (not dd-on)))
  16573. (goto-char pos)
  16574. (when dd-on (cons "$$" m))))))
  16575. (defun org-inside-latex-macro-p ()
  16576. "Is point inside a LaTeX macro or its arguments?"
  16577. (save-match-data
  16578. (org-in-regexp
  16579. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16580. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16581. "Build an overlay between BEG and END using IMAGE file.
  16582. Argument IMAGETYPE is the extension of the displayed image,
  16583. as a string. It defaults to \"png\"."
  16584. (let ((ov (make-overlay beg end))
  16585. (imagetype (or (intern imagetype) 'png)))
  16586. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16587. (overlay-put ov 'evaporate t)
  16588. (overlay-put ov
  16589. 'modification-hooks
  16590. (list (lambda (o _flag _beg _end &optional _l)
  16591. (delete-overlay o))))
  16592. (overlay-put ov
  16593. 'display
  16594. (list 'image :type imagetype :file image :ascent 'center))))
  16595. (defun org--list-latex-overlays (&optional beg end)
  16596. "List all Org LaTeX overlays in current buffer.
  16597. Limit to overlays between BEG and END when those are provided."
  16598. (cl-remove-if-not
  16599. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16600. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16601. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16602. "Remove all overlays with LaTeX fragment images in current buffer.
  16603. When optional arguments BEG and END are non-nil, remove all
  16604. overlays between them instead. Return a non-nil value when some
  16605. overlays were removed, nil otherwise."
  16606. (let ((overlays (org--list-latex-overlays beg end)))
  16607. (mapc #'delete-overlay overlays)
  16608. overlays))
  16609. (defun org-toggle-latex-fragment (&optional arg)
  16610. "Preview the LaTeX fragment at point, or all locally or globally.
  16611. If the cursor is on a LaTeX fragment, create the image and overlay
  16612. it over the source code, if there is none. Remove it otherwise.
  16613. If there is no fragment at point, display all fragments in the
  16614. current section.
  16615. With prefix ARG, preview or clear image for all fragments in the
  16616. current subtree or in the whole buffer when used before the first
  16617. headline. With a prefix ARG `\\[universal-argument] \
  16618. \\[universal-argument]' preview or clear images
  16619. for all fragments in the buffer."
  16620. (interactive "P")
  16621. (when (display-graphic-p)
  16622. (catch 'exit
  16623. (save-excursion
  16624. (let (beg end msg)
  16625. (cond
  16626. ((or (equal arg '(16))
  16627. (and (equal arg '(4))
  16628. (org-with-limited-levels (org-before-first-heading-p))))
  16629. (if (org-remove-latex-fragment-image-overlays)
  16630. (progn (message "LaTeX fragments images removed from buffer")
  16631. (throw 'exit nil))
  16632. (setq msg "Creating images for buffer...")))
  16633. ((equal arg '(4))
  16634. (org-with-limited-levels (org-back-to-heading t))
  16635. (setq beg (point))
  16636. (setq end (progn (org-end-of-subtree t) (point)))
  16637. (if (org-remove-latex-fragment-image-overlays beg end)
  16638. (progn
  16639. (message "LaTeX fragment images removed from subtree")
  16640. (throw 'exit nil))
  16641. (setq msg "Creating images for subtree...")))
  16642. ((let ((datum (org-element-context)))
  16643. (when (memq (org-element-type datum)
  16644. '(latex-environment latex-fragment))
  16645. (setq beg (org-element-property :begin datum))
  16646. (setq end (org-element-property :end datum))
  16647. (if (org-remove-latex-fragment-image-overlays beg end)
  16648. (progn (message "LaTeX fragment image removed")
  16649. (throw 'exit nil))
  16650. (setq msg "Creating image...")))))
  16651. (t
  16652. (org-with-limited-levels
  16653. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16654. (outline-previous-heading)
  16655. (point)))
  16656. (setq end (progn (outline-next-heading) (point)))
  16657. (if (org-remove-latex-fragment-image-overlays beg end)
  16658. (progn
  16659. (message "LaTeX fragment images removed from section")
  16660. (throw 'exit nil))
  16661. (setq msg "Creating images for section...")))))
  16662. (let ((file (buffer-file-name (buffer-base-buffer))))
  16663. (org-format-latex
  16664. (concat org-preview-latex-image-directory "org-ltximg")
  16665. beg end
  16666. ;; Emacs cannot overlay images from remote hosts. Create
  16667. ;; it in `temporary-file-directory' instead.
  16668. (if (or (not file) (file-remote-p file))
  16669. temporary-file-directory
  16670. default-directory)
  16671. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16672. (message (concat msg "done")))))))
  16673. (defun org-format-latex
  16674. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16675. "Replace LaTeX fragments with links to an image.
  16676. The function takes care of creating the replacement image.
  16677. Only consider fragments between BEG and END when those are
  16678. provided.
  16679. When optional argument OVERLAYS is non-nil, display the image on
  16680. top of the fragment instead of replacing it.
  16681. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16682. Some of the options can be changed using the variable
  16683. `org-format-latex-options', which see."
  16684. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16685. (unless (eq processing-type 'verbatim)
  16686. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16687. (cnt 0)
  16688. checkdir-flag)
  16689. (goto-char (or beg (point-min)))
  16690. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16691. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16692. (overlay-recenter (or end (point-max))))
  16693. (while (re-search-forward math-regexp end t)
  16694. (unless (and overlays
  16695. (eq (get-char-property (point) 'org-overlay-type)
  16696. 'org-latex-overlay))
  16697. (let* ((context (org-element-context))
  16698. (type (org-element-type context)))
  16699. (when (memq type '(latex-environment latex-fragment))
  16700. (let ((block-type (eq type 'latex-environment))
  16701. (value (org-element-property :value context))
  16702. (beg (org-element-property :begin context))
  16703. (end (save-excursion
  16704. (goto-char (org-element-property :end context))
  16705. (skip-chars-backward " \r\t\n")
  16706. (point))))
  16707. (cond
  16708. ((eq processing-type 'mathjax)
  16709. ;; Prepare for MathJax processing.
  16710. (if (not (string-match "\\`\\$\\$?" value))
  16711. (goto-char end)
  16712. (delete-region beg end)
  16713. (if (string= (match-string 0 value) "$$")
  16714. (insert "\\[" (substring value 2 -2) "\\]")
  16715. (insert "\\(" (substring value 1 -1) "\\)"))))
  16716. ((assq processing-type org-preview-latex-process-alist)
  16717. ;; Process to an image.
  16718. (cl-incf cnt)
  16719. (goto-char beg)
  16720. (let* ((processing-info
  16721. (cdr (assq processing-type org-preview-latex-process-alist)))
  16722. (face (face-at-point))
  16723. ;; Get the colors from the face at point.
  16724. (fg
  16725. (let ((color (plist-get org-format-latex-options
  16726. :foreground)))
  16727. (if (and forbuffer (eq color 'auto))
  16728. (face-attribute face :foreground nil 'default)
  16729. color)))
  16730. (bg
  16731. (let ((color (plist-get org-format-latex-options
  16732. :background)))
  16733. (if (and forbuffer (eq color 'auto))
  16734. (face-attribute face :background nil 'default)
  16735. color)))
  16736. (hash (sha1 (prin1-to-string
  16737. (list org-format-latex-header
  16738. org-latex-default-packages-alist
  16739. org-latex-packages-alist
  16740. org-format-latex-options
  16741. forbuffer value fg bg))))
  16742. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16743. (absprefix (expand-file-name prefix dir))
  16744. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16745. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16746. (sep (and block-type "\n\n"))
  16747. (link (concat sep "[[file:" linkfile "]]" sep))
  16748. (options
  16749. (org-combine-plists
  16750. org-format-latex-options
  16751. `(:foreground ,fg :background ,bg))))
  16752. (when msg (message msg cnt))
  16753. (unless checkdir-flag ; Ensure the directory exists.
  16754. (setq checkdir-flag t)
  16755. (let ((todir (file-name-directory absprefix)))
  16756. (unless (file-directory-p todir)
  16757. (make-directory todir t))))
  16758. (unless (file-exists-p movefile)
  16759. (org-create-formula-image
  16760. value movefile options forbuffer processing-type))
  16761. (if overlays
  16762. (progn
  16763. (dolist (o (overlays-in beg end))
  16764. (when (eq (overlay-get o 'org-overlay-type)
  16765. 'org-latex-overlay)
  16766. (delete-overlay o)))
  16767. (org--format-latex-make-overlay beg end movefile imagetype)
  16768. (goto-char end))
  16769. (delete-region beg end)
  16770. (insert
  16771. (org-add-props link
  16772. (list 'org-latex-src
  16773. (replace-regexp-in-string "\"" "" value)
  16774. 'org-latex-src-embed-type
  16775. (if block-type 'paragraph 'character)))))))
  16776. ((eq processing-type 'mathml)
  16777. ;; Process to MathML.
  16778. (unless (org-format-latex-mathml-available-p)
  16779. (user-error "LaTeX to MathML converter not configured"))
  16780. (cl-incf cnt)
  16781. (when msg (message msg cnt))
  16782. (goto-char beg)
  16783. (delete-region beg end)
  16784. (insert (org-format-latex-as-mathml
  16785. value block-type prefix dir)))
  16786. (t
  16787. (error "Unknown conversion process %s for LaTeX fragments"
  16788. processing-type)))))))))))
  16789. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16790. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16791. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16792. sucessful, return the portion between \"<math...> </math>\"
  16793. elements otherwise return nil. When MATHML-FILE is specified,
  16794. write the results in to that file. When invoked as an
  16795. interactive command, prompt for LATEX-FRAG, with initial value
  16796. set to the current active region and echo the results for user
  16797. inspection."
  16798. (interactive (list (let ((frag (when (org-region-active-p)
  16799. (buffer-substring-no-properties
  16800. (region-beginning) (region-end)))))
  16801. (read-string "LaTeX Fragment: " frag nil frag))))
  16802. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16803. (let* ((tmp-in-file
  16804. (let ((file (file-relative-name
  16805. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16806. (write-region latex-frag nil file)
  16807. file))
  16808. (tmp-out-file (file-relative-name
  16809. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16810. (cmd (format-spec
  16811. org-latex-to-mathml-convert-command
  16812. `((?j . ,(and org-latex-to-mathml-jar-file
  16813. (shell-quote-argument
  16814. (expand-file-name
  16815. org-latex-to-mathml-jar-file))))
  16816. (?I . ,(shell-quote-argument tmp-in-file))
  16817. (?i . ,latex-frag)
  16818. (?o . ,(shell-quote-argument tmp-out-file)))))
  16819. mathml shell-command-output)
  16820. (when (called-interactively-p 'any)
  16821. (unless (org-format-latex-mathml-available-p)
  16822. (user-error "LaTeX to MathML converter not configured")))
  16823. (message "Running %s" cmd)
  16824. (setq shell-command-output (shell-command-to-string cmd))
  16825. (setq mathml
  16826. (when (file-readable-p tmp-out-file)
  16827. (with-current-buffer (find-file-noselect tmp-out-file t)
  16828. (goto-char (point-min))
  16829. (when (re-search-forward
  16830. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16831. (regexp-quote
  16832. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16833. nil t)
  16834. (prog1 (match-string 0) (kill-buffer))))))
  16835. (cond
  16836. (mathml
  16837. (setq mathml
  16838. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16839. (when mathml-file
  16840. (write-region mathml nil mathml-file))
  16841. (when (called-interactively-p 'any)
  16842. (message mathml)))
  16843. ((message "LaTeX to MathML conversion failed")
  16844. (message shell-command-output)))
  16845. (delete-file tmp-in-file)
  16846. (when (file-exists-p tmp-out-file)
  16847. (delete-file tmp-out-file))
  16848. mathml))
  16849. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16850. prefix &optional dir)
  16851. "Use `org-create-math-formula' but check local cache first."
  16852. (let* ((absprefix (expand-file-name prefix dir))
  16853. (print-length nil) (print-level nil)
  16854. (formula-id (concat
  16855. "formula-"
  16856. (sha1
  16857. (prin1-to-string
  16858. (list latex-frag
  16859. org-latex-to-mathml-convert-command)))))
  16860. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16861. (formula-cache-dir (file-name-directory formula-cache)))
  16862. (unless (file-directory-p formula-cache-dir)
  16863. (make-directory formula-cache-dir t))
  16864. (unless (file-exists-p formula-cache)
  16865. (org-create-math-formula latex-frag formula-cache))
  16866. (if (file-exists-p formula-cache)
  16867. ;; Successful conversion. Return the link to MathML file.
  16868. (org-add-props
  16869. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16870. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16871. 'org-latex-src-embed-type (if latex-frag-type
  16872. 'paragraph 'character)))
  16873. ;; Failed conversion. Return the LaTeX fragment verbatim
  16874. latex-frag)))
  16875. (defun org--get-display-dpi ()
  16876. "Get the DPI of the display.
  16877. The function assumes that the display has the same pixel width in
  16878. the horizontal and vertical directions."
  16879. (if (display-graphic-p)
  16880. (round (/ (display-pixel-height)
  16881. (/ (display-mm-height) 25.4)))
  16882. (error "Attempt to calculate the dpi of a non-graphic display")))
  16883. (defun org-create-formula-image
  16884. (string tofile options buffer &optional processing-type)
  16885. "Create an image from LaTeX source using external processes.
  16886. The LaTeX STRING is saved to a temporary LaTeX file, then
  16887. converted to an image file by process PROCESSING-TYPE defined in
  16888. `org-preview-latex-process-alist'. A nil value defaults to
  16889. `org-preview-latex-default-process'.
  16890. The generated image file is eventually moved to TOFILE.
  16891. The OPTIONS argument controls the size, foreground color and
  16892. background color of the generated image.
  16893. When BUFFER non-nil, this function is used for LaTeX previewing.
  16894. Otherwise, it is used to deal with LaTeX snippets showed in
  16895. a HTML file."
  16896. (let* ((processing-type (or processing-type
  16897. org-preview-latex-default-process))
  16898. (processing-info
  16899. (cdr (assq processing-type org-preview-latex-process-alist)))
  16900. (programs (plist-get processing-info :programs))
  16901. (error-message (or (plist-get processing-info :message) ""))
  16902. (use-xcolor (plist-get processing-info :use-xcolor))
  16903. (image-input-type (plist-get processing-info :image-input-type))
  16904. (image-output-type (plist-get processing-info :image-output-type))
  16905. (post-clean (or (plist-get processing-info :post-clean)
  16906. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16907. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16908. (latex-header
  16909. (or (plist-get processing-info :latex-header)
  16910. (org-latex-make-preamble
  16911. (org-export-get-environment (org-export-get-backend 'latex))
  16912. org-format-latex-header
  16913. 'snippet)))
  16914. (latex-compiler (plist-get processing-info :latex-compiler))
  16915. (image-converter (plist-get processing-info :image-converter))
  16916. (tmpdir temporary-file-directory)
  16917. (texfilebase (make-temp-name
  16918. (expand-file-name "orgtex" tmpdir)))
  16919. (texfile (concat texfilebase ".tex"))
  16920. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16921. '(1.0 . 1.0)))
  16922. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16923. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16924. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16925. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16926. "Black"))
  16927. (bg (or (plist-get options (if buffer :background :html-background))
  16928. "Transparent"))
  16929. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16930. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16931. (dolist (program programs)
  16932. (org-check-external-command program error-message))
  16933. (if use-xcolor
  16934. (progn (if (eq fg 'default)
  16935. (setq fg (org-latex-color :foreground))
  16936. (setq fg (org-latex-color-format fg)))
  16937. (if (eq bg 'default)
  16938. (setq bg (org-latex-color :background))
  16939. (setq bg (org-latex-color-format
  16940. (if (string= bg "Transparent") "white" bg))))
  16941. (with-temp-file texfile
  16942. (insert latex-header)
  16943. (insert "\n\\begin{document}\n"
  16944. "\\definecolor{fg}{rgb}{" fg "}\n"
  16945. "\\definecolor{bg}{rgb}{" bg "}\n"
  16946. "\n\\pagecolor{bg}\n"
  16947. "\n{\\color{fg}\n"
  16948. string
  16949. "\n}\n"
  16950. "\n\\end{document}\n")))
  16951. (if (eq fg 'default)
  16952. (setq fg (org-dvipng-color :foreground))
  16953. (unless (string= fg "Transparent")
  16954. (setq fg (org-dvipng-color-format fg))))
  16955. (if (eq bg 'default)
  16956. (setq bg (org-dvipng-color :background))
  16957. (unless (string= bg "Transparent")
  16958. (setq bg (org-dvipng-color-format bg))))
  16959. (with-temp-file texfile
  16960. (insert latex-header)
  16961. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16962. (let* ((err-msg (format "Please adjust `%s' part of \
  16963. `org-preview-latex-process-alist'."
  16964. processing-type))
  16965. (image-input-file
  16966. (org-compile-file
  16967. texfile latex-compiler image-input-type err-msg log-buf))
  16968. (image-output-file
  16969. (org-compile-file
  16970. image-input-file image-converter image-output-type err-msg log-buf
  16971. `((?F . ,(shell-quote-argument fg))
  16972. (?B . ,(shell-quote-argument bg))
  16973. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16974. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16975. (copy-file image-output-file tofile 'replace)
  16976. (dolist (e post-clean)
  16977. (when (file-exists-p (concat texfilebase e))
  16978. (delete-file (concat texfilebase e))))
  16979. image-output-file)))
  16980. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16981. "Fill a LaTeX header template TPL.
  16982. In the template, the following place holders will be recognized:
  16983. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16984. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16985. [PACKAGES] \\usepackage statements for PKG
  16986. [NO-PACKAGES] do not include PKG
  16987. [EXTRA] the string EXTRA
  16988. [NO-EXTRA] do not include EXTRA
  16989. For backward compatibility, if both the positive and the negative place
  16990. holder is missing, the positive one (without the \"NO-\") will be
  16991. assumed to be present at the end of the template.
  16992. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16993. EXTRA is a string.
  16994. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16995. (let (rpl (end ""))
  16996. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16997. (setq rpl (if (or (match-end 1) (not def-pkg))
  16998. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16999. tpl (replace-match rpl t t tpl))
  17000. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17001. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17002. (setq rpl (if (or (match-end 1) (not pkg))
  17003. "" (org-latex-packages-to-string pkg snippets-p t))
  17004. tpl (replace-match rpl t t tpl))
  17005. (when pkg (setq end
  17006. (concat end "\n"
  17007. (org-latex-packages-to-string pkg snippets-p)))))
  17008. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17009. (setq rpl (if (or (match-end 1) (not extra))
  17010. "" (concat extra "\n"))
  17011. tpl (replace-match rpl t t tpl))
  17012. (when (and extra (string-match "\\S-" extra))
  17013. (setq end (concat end "\n" extra))))
  17014. (if (string-match "\\S-" end)
  17015. (concat tpl "\n" end)
  17016. tpl)))
  17017. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17018. "Turn an alist of packages into a string with the \\usepackage macros."
  17019. (setq pkg (mapconcat (lambda(p)
  17020. (cond
  17021. ((stringp p) p)
  17022. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17023. (format "%% Package %s omitted" (cadr p)))
  17024. ((equal "" (car p))
  17025. (format "\\usepackage{%s}" (cadr p)))
  17026. (t
  17027. (format "\\usepackage[%s]{%s}"
  17028. (car p) (cadr p)))))
  17029. pkg
  17030. "\n"))
  17031. (if newline (concat pkg "\n") pkg))
  17032. (defun org-dvipng-color (attr)
  17033. "Return a RGB color specification for dvipng."
  17034. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17035. (defun org-dvipng-color-format (color-name)
  17036. "Convert COLOR-NAME to a RGB color value for dvipng."
  17037. (apply #'format "rgb %s %s %s"
  17038. (mapcar 'org-normalize-color
  17039. (color-values color-name))))
  17040. (defun org-latex-color (attr)
  17041. "Return a RGB color for the LaTeX color package."
  17042. (org-latex-color-format (face-attribute 'default attr nil)))
  17043. (defun org-latex-color-format (color-name)
  17044. "Convert COLOR-NAME to a RGB color value."
  17045. (apply #'format "%s,%s,%s"
  17046. (mapcar 'org-normalize-color
  17047. (color-values color-name))))
  17048. (defun org-normalize-color (value)
  17049. "Return string to be used as color value for an RGB component."
  17050. (format "%g" (/ value 65535.0)))
  17051. ;; Image display
  17052. (defvar-local org-inline-image-overlays nil)
  17053. (defun org-toggle-inline-images (&optional include-linked)
  17054. "Toggle the display of inline images.
  17055. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17056. (interactive "P")
  17057. (if org-inline-image-overlays
  17058. (progn
  17059. (org-remove-inline-images)
  17060. (when (called-interactively-p 'interactive)
  17061. (message "Inline image display turned off")))
  17062. (org-display-inline-images include-linked)
  17063. (when (called-interactively-p 'interactive)
  17064. (message (if org-inline-image-overlays
  17065. (format "%d images displayed inline"
  17066. (length org-inline-image-overlays))
  17067. "No images to display inline")))))
  17068. (defun org-redisplay-inline-images ()
  17069. "Refresh the display of inline images."
  17070. (interactive)
  17071. (if (not org-inline-image-overlays)
  17072. (org-toggle-inline-images)
  17073. (org-toggle-inline-images)
  17074. (org-toggle-inline-images)))
  17075. ;; For without-x builds.
  17076. (declare-function image-refresh "image" (spec &optional frame))
  17077. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17078. "Display inline images.
  17079. An inline image is a link which follows either of these
  17080. conventions:
  17081. 1. Its path is a file with an extension matching return value
  17082. from `image-file-name-regexp' and it has no contents.
  17083. 2. Its description consists in a single link of the previous
  17084. type.
  17085. When optional argument INCLUDE-LINKED is non-nil, also links with
  17086. a text description part will be inlined. This can be nice for
  17087. a quick look at those images, but it does not reflect what
  17088. exported files will look like.
  17089. When optional argument REFRESH is non-nil, refresh existing
  17090. images between BEG and END. This will create new image displays
  17091. only if necessary. BEG and END default to the buffer
  17092. boundaries."
  17093. (interactive "P")
  17094. (when (display-graphic-p)
  17095. (unless refresh
  17096. (org-remove-inline-images)
  17097. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17098. (org-with-wide-buffer
  17099. (goto-char (or beg (point-min)))
  17100. (let* ((case-fold-search t)
  17101. (file-extension-re (image-file-name-regexp))
  17102. (link-abbrevs (mapcar #'car
  17103. (append org-link-abbrev-alist-local
  17104. org-link-abbrev-alist)))
  17105. ;; Check absolute, relative file names and explicit
  17106. ;; "file:" links. Also check link abbreviations since
  17107. ;; some might expand to "file" links.
  17108. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17109. (if (not link-abbrevs) ""
  17110. (format "\\|\\(?:%s:\\)"
  17111. (regexp-opt link-abbrevs))))))
  17112. (while (re-search-forward file-types-re end t)
  17113. (let ((link (save-match-data (org-element-context))))
  17114. ;; Check if we're at an inline image, i.e., an image file
  17115. ;; link without a description (unless INCLUDE-LINKED is
  17116. ;; non-nil).
  17117. (when (and (equal "file" (org-element-property :type link))
  17118. (or include-linked
  17119. (null (org-element-contents link)))
  17120. (string-match-p file-extension-re
  17121. (org-element-property :path link)))
  17122. (let ((file (expand-file-name
  17123. (org-link-unescape
  17124. (org-element-property :path link)))))
  17125. (when (file-exists-p file)
  17126. (let ((width
  17127. ;; Apply `org-image-actual-width' specifications.
  17128. (cond
  17129. ((not (image-type-available-p 'imagemagick)) nil)
  17130. ((eq org-image-actual-width t) nil)
  17131. ((listp org-image-actual-width)
  17132. (or
  17133. ;; First try to find a width among
  17134. ;; attributes associated to the paragraph
  17135. ;; containing link.
  17136. (let ((paragraph
  17137. (let ((e link))
  17138. (while (and (setq e (org-element-property
  17139. :parent e))
  17140. (not (eq (org-element-type e)
  17141. 'paragraph))))
  17142. e)))
  17143. (when paragraph
  17144. (save-excursion
  17145. (goto-char (org-element-property :begin paragraph))
  17146. (when
  17147. (re-search-forward
  17148. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17149. (org-element-property
  17150. :post-affiliated paragraph)
  17151. t)
  17152. (string-to-number (match-string 1))))))
  17153. ;; Otherwise, fall-back to provided number.
  17154. (car org-image-actual-width)))
  17155. ((numberp org-image-actual-width)
  17156. org-image-actual-width)))
  17157. (old (get-char-property-and-overlay
  17158. (org-element-property :begin link)
  17159. 'org-image-overlay)))
  17160. (if (and (car-safe old) refresh)
  17161. (image-refresh (overlay-get (cdr old) 'display))
  17162. (let ((image (create-image file
  17163. (and width 'imagemagick)
  17164. nil
  17165. :width width)))
  17166. (when image
  17167. (let ((ov (make-overlay
  17168. (org-element-property :begin link)
  17169. (progn
  17170. (goto-char
  17171. (org-element-property :end link))
  17172. (skip-chars-backward " \t")
  17173. (point)))))
  17174. (overlay-put ov 'display image)
  17175. (overlay-put ov 'face 'default)
  17176. (overlay-put ov 'org-image-overlay t)
  17177. (overlay-put
  17178. ov 'modification-hooks
  17179. (list 'org-display-inline-remove-overlay))
  17180. (push ov org-inline-image-overlays)))))))))))))))
  17181. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17182. "Remove inline-display overlay if a corresponding region is modified."
  17183. (let ((inhibit-modification-hooks t))
  17184. (when (and ov after)
  17185. (delete ov org-inline-image-overlays)
  17186. (delete-overlay ov))))
  17187. (defun org-remove-inline-images ()
  17188. "Remove inline display of images."
  17189. (interactive)
  17190. (mapc #'delete-overlay org-inline-image-overlays)
  17191. (setq org-inline-image-overlays nil))
  17192. ;;; Key bindings
  17193. (defun org-remap (map &rest commands)
  17194. "In MAP, remap the functions given in COMMANDS.
  17195. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17196. (let (new old)
  17197. (while commands
  17198. (setq old (pop commands) new (pop commands))
  17199. (org-defkey map (vector 'remap old) new))))
  17200. ;;;; Outline functions that can be remapped in Org
  17201. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17202. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17203. (define-key org-mode-map [remap outline-forward-same-level]
  17204. #'org-forward-heading-same-level)
  17205. (define-key org-mode-map [remap outline-backward-same-level]
  17206. #'org-backward-heading-same-level)
  17207. (define-key org-mode-map [remap outline-show-branches]
  17208. #'org-kill-note-or-show-branches)
  17209. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17210. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17211. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17212. (define-key org-mode-map [remap outline-next-visible-heading]
  17213. #'org-next-visible-heading)
  17214. (define-key org-mode-map [remap outline-previous-visible-heading]
  17215. #'org-previous-visible-heading)
  17216. (define-key org-mode-map [remap show-children] #'org-show-children)
  17217. ;;;; Make `C-c C-x' a prefix key
  17218. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17219. ;;;; TAB key with modifiers
  17220. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17221. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17222. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17223. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17224. (org-defkey org-mode-map (kbd "M-TAB") #'pcomplete)
  17225. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17226. (org-defkey org-mode-map (kbd "ESC TAB") #'pcomplete)
  17227. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17228. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17229. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17230. ;;;; RET key with modifiers
  17231. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17232. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17233. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17234. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17235. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17236. ;;;; Cursor keys with modifiers
  17237. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17238. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17239. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17240. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17241. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17242. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17243. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17244. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17245. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17246. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17247. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17248. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17249. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17250. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17251. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17252. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17253. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17254. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17255. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17256. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17257. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17258. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17259. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17260. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17261. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17262. ;;;; Babel keys
  17263. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17264. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17265. (define-key org-babel-map key def))
  17266. ;;;; Extra keys for TTY access.
  17267. ;; We only set them when really needed because otherwise the
  17268. ;; menus don't show the simple keys
  17269. (when (or org-use-extra-keys (not window-system))
  17270. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17271. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17272. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17273. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17274. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17275. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17276. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17277. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17278. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17279. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17280. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17281. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17282. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17283. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17284. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17285. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17286. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17287. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17288. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17289. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17290. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17291. ;;;; Narrow map
  17292. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17293. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17294. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17295. ;;;; Remap usual Emacs bindings
  17296. (org-remap org-mode-map
  17297. 'self-insert-command 'org-self-insert-command
  17298. 'delete-char 'org-delete-char
  17299. 'delete-backward-char 'org-delete-backward-char
  17300. 'kill-line 'org-kill-line
  17301. 'open-line 'org-open-line
  17302. 'yank 'org-yank
  17303. 'comment-dwim 'org-comment-dwim
  17304. 'move-beginning-of-line 'org-beginning-of-line
  17305. 'move-end-of-line 'org-end-of-line
  17306. 'forward-paragraph 'org-forward-paragraph
  17307. 'backward-paragraph 'org-backward-paragraph
  17308. 'backward-sentence 'org-backward-sentence
  17309. 'forward-sentence 'org-forward-sentence
  17310. 'fill-paragraph 'org-fill-paragraph
  17311. 'delete-indentation 'org-delete-indentation
  17312. 'transpose-words 'org-transpose-words)
  17313. ;;;; All the other keys
  17314. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17315. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17316. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17317. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17318. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17319. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17320. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17321. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17322. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17323. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17324. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17325. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17326. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17327. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17328. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17329. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17330. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17331. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17332. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17333. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17334. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17335. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17336. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17337. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17338. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17339. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17340. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17341. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17342. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17343. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17344. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17345. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17346. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17347. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17348. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17349. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17350. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17351. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17352. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17353. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17354. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17355. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17356. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17357. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17358. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17359. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17360. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17361. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17362. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17363. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17364. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17365. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17366. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17367. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17368. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17369. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17370. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17371. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17372. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17373. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17374. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17375. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17376. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17377. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17378. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17379. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17380. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17381. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17382. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17383. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17384. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17385. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17386. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17387. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17388. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17389. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17390. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17391. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17392. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17393. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17394. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17395. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17396. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17397. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17398. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17399. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17400. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17401. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17402. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17403. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17404. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17405. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17406. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17407. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17408. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17409. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17410. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17411. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17412. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17413. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17414. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17415. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17416. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17417. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17418. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17419. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17420. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17421. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17422. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17423. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17424. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17425. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17426. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17427. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17428. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17429. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17430. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17431. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17432. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17433. (org-defkey org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17434. (org-defkey org-mode-map (kbd "C-c C-x !") #'org-reload)
  17435. (org-defkey org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17436. (org-defkey org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17437. (org-defkey org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17438. (org-defkey org-mode-map (kbd "C-c C-x I") #'org-info-find-node)
  17439. ;;; Speed commands
  17440. (defconst org-speed-commands-default
  17441. '(
  17442. ("Outline Navigation")
  17443. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17444. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17445. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17446. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17447. ("F" . org-next-block)
  17448. ("B" . org-previous-block)
  17449. ("u" . (org-speed-move-safe 'outline-up-heading))
  17450. ("j" . org-goto)
  17451. ("g" . (org-refile t))
  17452. ("Outline Visibility")
  17453. ("c" . org-cycle)
  17454. ("C" . org-shifttab)
  17455. (" " . org-display-outline-path)
  17456. ("s" . org-toggle-narrow-to-subtree)
  17457. ("k" . org-cut-subtree)
  17458. ("=" . org-columns)
  17459. ("Outline Structure Editing")
  17460. ("U" . org-metaup)
  17461. ("D" . org-metadown)
  17462. ("r" . org-metaright)
  17463. ("l" . org-metaleft)
  17464. ("R" . org-shiftmetaright)
  17465. ("L" . org-shiftmetaleft)
  17466. ("i" . (progn (forward-char 1) (call-interactively
  17467. 'org-insert-heading-respect-content)))
  17468. ("^" . org-sort)
  17469. ("w" . org-refile)
  17470. ("a" . org-archive-subtree-default-with-confirmation)
  17471. ("@" . org-mark-subtree)
  17472. ("#" . org-toggle-comment)
  17473. ("Clock Commands")
  17474. ("I" . org-clock-in)
  17475. ("O" . org-clock-out)
  17476. ("Meta Data Editing")
  17477. ("t" . org-todo)
  17478. ("," . (org-priority))
  17479. ("0" . (org-priority ?\ ))
  17480. ("1" . (org-priority ?A))
  17481. ("2" . (org-priority ?B))
  17482. ("3" . (org-priority ?C))
  17483. (":" . org-set-tags-command)
  17484. ("e" . org-set-effort)
  17485. ("E" . org-inc-effort)
  17486. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17487. (org-entry-put (point) "APPT_WARNTIME" m)))
  17488. ("Agenda Views etc")
  17489. ("v" . org-agenda)
  17490. ("/" . org-sparse-tree)
  17491. ("Misc")
  17492. ("o" . org-open-at-point)
  17493. ("?" . org-speed-command-help)
  17494. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17495. (">" . (org-agenda-remove-restriction-lock))
  17496. )
  17497. "The default speed commands.")
  17498. (defun org-print-speed-command (e)
  17499. (if (> (length (car e)) 1)
  17500. (progn
  17501. (princ "\n")
  17502. (princ (car e))
  17503. (princ "\n")
  17504. (princ (make-string (length (car e)) ?-))
  17505. (princ "\n"))
  17506. (princ (car e))
  17507. (princ " ")
  17508. (if (symbolp (cdr e))
  17509. (princ (symbol-name (cdr e)))
  17510. (prin1 (cdr e)))
  17511. (princ "\n")))
  17512. (defun org-speed-command-help ()
  17513. "Show the available speed commands."
  17514. (interactive)
  17515. (if (not org-use-speed-commands)
  17516. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17517. (with-output-to-temp-buffer "*Help*"
  17518. (princ "User-defined Speed commands\n===========================\n")
  17519. (mapc #'org-print-speed-command org-speed-commands-user)
  17520. (princ "\n")
  17521. (princ "Built-in Speed commands\n=======================\n")
  17522. (mapc #'org-print-speed-command org-speed-commands-default))
  17523. (with-current-buffer "*Help*"
  17524. (setq truncate-lines t))))
  17525. (defun org-speed-move-safe (cmd)
  17526. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17527. If not, return to the original position and throw an error."
  17528. (interactive)
  17529. (let ((pos (point)))
  17530. (call-interactively cmd)
  17531. (unless (and (bolp) (org-at-heading-p))
  17532. (goto-char pos)
  17533. (error "Boundary reached while executing %s" cmd))))
  17534. (defvar org-self-insert-command-undo-counter 0)
  17535. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17536. (defvar org-speed-command nil)
  17537. (defun org-speed-command-activate (keys)
  17538. "Hook for activating single-letter speed commands.
  17539. `org-speed-commands-default' specifies a minimal command set.
  17540. Use `org-speed-commands-user' for further customization."
  17541. (when (or (and (bolp) (looking-at org-outline-regexp))
  17542. (and (functionp org-use-speed-commands)
  17543. (funcall org-use-speed-commands)))
  17544. (cdr (assoc keys (append org-speed-commands-user
  17545. org-speed-commands-default)))))
  17546. (defun org-babel-speed-command-activate (keys)
  17547. "Hook for activating single-letter code block commands."
  17548. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17549. (cdr (assoc keys org-babel-key-bindings))))
  17550. (defcustom org-speed-command-hook
  17551. '(org-speed-command-activate org-babel-speed-command-activate)
  17552. "Hook for activating speed commands at strategic locations.
  17553. Hook functions are called in sequence until a valid handler is
  17554. found.
  17555. Each hook takes a single argument, a user-pressed command key
  17556. which is also a `self-insert-command' from the global map.
  17557. Within the hook, examine the cursor position and the command key
  17558. and return nil or a valid handler as appropriate. Handler could
  17559. be one of an interactive command, a function, or a form.
  17560. Set `org-use-speed-commands' to non-nil value to enable this
  17561. hook. The default setting is `org-speed-command-activate'."
  17562. :group 'org-structure
  17563. :version "24.1"
  17564. :type 'hook)
  17565. (defun org-self-insert-command (N)
  17566. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17567. If the cursor is in a table looking at whitespace, the whitespace is
  17568. overwritten, and the table is not marked as requiring realignment."
  17569. (interactive "p")
  17570. (org-check-before-invisible-edit 'insert)
  17571. (cond
  17572. ((and org-use-speed-commands
  17573. (let ((kv (this-command-keys-vector)))
  17574. (setq org-speed-command
  17575. (run-hook-with-args-until-success
  17576. 'org-speed-command-hook
  17577. (make-string 1 (aref kv (1- (length kv))))))))
  17578. (cond
  17579. ((commandp org-speed-command)
  17580. (setq this-command org-speed-command)
  17581. (call-interactively org-speed-command))
  17582. ((functionp org-speed-command)
  17583. (funcall org-speed-command))
  17584. ((and org-speed-command (listp org-speed-command))
  17585. (eval org-speed-command))
  17586. (t (let (org-use-speed-commands)
  17587. (call-interactively 'org-self-insert-command)))))
  17588. ((and
  17589. (= N 1)
  17590. (not (org-region-active-p))
  17591. (org-at-table-p)
  17592. (progn
  17593. ;; Check if we blank the field, and if that triggers align.
  17594. (and (featurep 'org-table)
  17595. org-table-auto-blank-field
  17596. (memq last-command
  17597. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17598. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17599. ;; Got extra space, this field does not determine
  17600. ;; column width.
  17601. (let (org-table-may-need-update) (org-table-blank-field))
  17602. ;; No extra space, this field may determine column
  17603. ;; width.
  17604. (org-table-blank-field)))
  17605. t)
  17606. (looking-at "[^|\n]* |"))
  17607. ;; There is room for insertion without re-aligning the table.
  17608. (self-insert-command N)
  17609. (org-table-with-shrunk-field
  17610. (save-excursion
  17611. (skip-chars-forward "^|")
  17612. ;; Do not delete last space, which is
  17613. ;; `org-table-separator-space', but the regular space before
  17614. ;; it.
  17615. (delete-region (- (point) 2) (1- (point))))))
  17616. (t
  17617. (setq org-table-may-need-update t)
  17618. (self-insert-command N)
  17619. (org-fix-tags-on-the-fly)
  17620. (when org-self-insert-cluster-for-undo
  17621. (if (not (eq last-command 'org-self-insert-command))
  17622. (setq org-self-insert-command-undo-counter 1)
  17623. (if (>= org-self-insert-command-undo-counter 20)
  17624. (setq org-self-insert-command-undo-counter 1)
  17625. (and (> org-self-insert-command-undo-counter 0)
  17626. buffer-undo-list (listp buffer-undo-list)
  17627. (not (cadr buffer-undo-list)) ; remove nil entry
  17628. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17629. (setq org-self-insert-command-undo-counter
  17630. (1+ org-self-insert-command-undo-counter))))))))
  17631. (defun org-check-before-invisible-edit (kind)
  17632. "Check is editing if kind KIND would be dangerous with invisible text around.
  17633. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17634. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17635. (when (and org-catch-invisible-edits
  17636. (or (not (boundp 'visible-mode)) (not visible-mode))
  17637. (or (get-char-property (point) 'invisible)
  17638. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17639. ;; OK, we need to take a closer look. Do not consider
  17640. ;; invisibility obtained through text properties (e.g., link
  17641. ;; fontification), as it cannot be toggled.
  17642. (let* ((invisible-at-point
  17643. (pcase (get-char-property-and-overlay (point) 'invisible)
  17644. (`(,_ . ,(and (pred overlayp) o)) o)))
  17645. ;; Assume that point cannot land in the middle of an
  17646. ;; overlay, or between two overlays.
  17647. (invisible-before-point
  17648. (and (not invisible-at-point)
  17649. (not (bobp))
  17650. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17651. (`(,_ . ,(and (pred overlayp) o)) o))))
  17652. (border-and-ok-direction
  17653. (or
  17654. ;; Check if we are acting predictably before invisible
  17655. ;; text.
  17656. (and invisible-at-point
  17657. (memq kind '(insert delete-backward)))
  17658. ;; Check if we are acting predictably after invisible text
  17659. ;; This works not well, and I have turned it off. It seems
  17660. ;; better to always show and stop after invisible text.
  17661. ;; (and (not invisible-at-point) invisible-before-point
  17662. ;; (memq kind '(insert delete)))
  17663. )))
  17664. (when (or invisible-at-point invisible-before-point)
  17665. (when (eq org-catch-invisible-edits 'error)
  17666. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17667. (if (and org-custom-properties-overlays
  17668. (y-or-n-p "Display invisible properties in this buffer? "))
  17669. (org-toggle-custom-properties-visibility)
  17670. ;; Make the area visible
  17671. (save-excursion
  17672. (when invisible-before-point
  17673. (goto-char
  17674. (previous-single-char-property-change (point) 'invisible)))
  17675. ;; Remove whatever overlay is currently making yet-to-be
  17676. ;; edited text invisible. Also remove nested invisibility
  17677. ;; related overlays.
  17678. (delete-overlay (or invisible-at-point invisible-before-point))
  17679. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17680. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17681. (`(,_ . ,(and (pred overlayp) o))
  17682. (delete-overlay o)
  17683. t)))))
  17684. (cond
  17685. ((eq org-catch-invisible-edits 'show)
  17686. ;; That's it, we do the edit after showing
  17687. (message
  17688. "Unfolding invisible region around point before editing")
  17689. (sit-for 1))
  17690. ((and (eq org-catch-invisible-edits 'smart)
  17691. border-and-ok-direction)
  17692. (message "Unfolding invisible region around point before editing"))
  17693. (t
  17694. ;; Don't do the edit, make the user repeat it in full visibility
  17695. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17696. (defun org-fix-tags-on-the-fly ()
  17697. "Align tags in headline at point.
  17698. Unlike `org-align-tags', this function does nothing if point is
  17699. either not currently on a tagged headline or on a tag."
  17700. (when (and (org-match-line org-tag-line-re)
  17701. (< (point) (match-beginning 1)))
  17702. (org-align-tags)))
  17703. (defun org-delete-backward-char (N)
  17704. "Like `delete-backward-char', insert whitespace at field end in tables.
  17705. When deleting backwards, in tables this function will insert whitespace in
  17706. front of the next \"|\" separator, to keep the table aligned. The table will
  17707. still be marked for re-alignment if the field did fill the entire column,
  17708. because, in this case the deletion might narrow the column."
  17709. (interactive "p")
  17710. (save-match-data
  17711. (org-check-before-invisible-edit 'delete-backward)
  17712. (if (and (= N 1)
  17713. (not overwrite-mode)
  17714. (not (org-region-active-p))
  17715. (not (eq (char-before) ?|))
  17716. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17717. (looking-at-p ".*?|")
  17718. (org-at-table-p))
  17719. (progn (forward-char -1) (org-delete-char 1))
  17720. (backward-delete-char N)
  17721. (org-fix-tags-on-the-fly))))
  17722. (defun org-delete-char (N)
  17723. "Like `delete-char', but insert whitespace at field end in tables.
  17724. When deleting characters, in tables this function will insert whitespace in
  17725. front of the next \"|\" separator, to keep the table aligned. The table will
  17726. still be marked for re-alignment if the field did fill the entire column,
  17727. because, in this case the deletion might narrow the column."
  17728. (interactive "p")
  17729. (save-match-data
  17730. (org-check-before-invisible-edit 'delete)
  17731. (cond
  17732. ((or (/= N 1)
  17733. (eq (char-after) ?|)
  17734. (save-excursion (skip-chars-backward " \t") (bolp))
  17735. (not (org-at-table-p)))
  17736. (delete-char N)
  17737. (org-fix-tags-on-the-fly))
  17738. ((looking-at ".\\(.*?\\)|")
  17739. (let* ((update? org-table-may-need-update)
  17740. (noalign (looking-at-p ".*? |")))
  17741. (delete-char 1)
  17742. (org-table-with-shrunk-field
  17743. (save-excursion
  17744. ;; Last space is `org-table-separator-space', so insert
  17745. ;; a regular one before it instead.
  17746. (goto-char (- (match-end 0) 2))
  17747. (insert " ")))
  17748. ;; If there were two spaces at the end, this field does not
  17749. ;; determine the width of the column.
  17750. (when noalign (setq org-table-may-need-update update?))))
  17751. (t
  17752. (delete-char N)))))
  17753. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17754. (put 'org-self-insert-command 'delete-selection
  17755. (lambda ()
  17756. (not (run-hook-with-args-until-success
  17757. 'self-insert-uses-region-functions))))
  17758. (put 'orgtbl-self-insert-command 'delete-selection
  17759. (lambda ()
  17760. (not (run-hook-with-args-until-success
  17761. 'self-insert-uses-region-functions))))
  17762. (put 'org-delete-char 'delete-selection 'supersede)
  17763. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17764. (put 'org-yank 'delete-selection 'yank)
  17765. ;; Make `flyspell-mode' delay after some commands
  17766. (put 'org-self-insert-command 'flyspell-delayed t)
  17767. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17768. (put 'org-delete-char 'flyspell-delayed t)
  17769. (put 'org-delete-backward-char 'flyspell-delayed t)
  17770. ;; Make pabbrev-mode expand after Org mode commands
  17771. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17772. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17773. (defun org-transpose-words ()
  17774. "Transpose words for Org.
  17775. This uses the `org-mode-transpose-word-syntax-table' syntax
  17776. table, which interprets characters in `org-emphasis-alist' as
  17777. word constituents."
  17778. (interactive)
  17779. (with-syntax-table org-mode-transpose-word-syntax-table
  17780. (call-interactively 'transpose-words)))
  17781. (defvar org-ctrl-c-ctrl-c-hook nil
  17782. "Hook for functions attaching themselves to `C-c C-c'.
  17783. This can be used to add additional functionality to the C-c C-c
  17784. key which executes context-dependent commands. This hook is run
  17785. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17786. run after the last test.
  17787. Each function will be called with no arguments. The function
  17788. must check if the context is appropriate for it to act. If yes,
  17789. it should do its thing and then return a non-nil value. If the
  17790. context is wrong, just do nothing and return nil.")
  17791. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17792. "Hook for functions attaching themselves to `C-c C-c'.
  17793. This can be used to add additional functionality to the C-c C-c
  17794. key which executes context-dependent commands. This hook is run
  17795. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17796. before the first test.
  17797. Each function will be called with no arguments. The function
  17798. must check if the context is appropriate for it to act. If yes,
  17799. it should do its thing and then return a non-nil value. If the
  17800. context is wrong, just do nothing and return nil.")
  17801. (defvar org-tab-first-hook nil
  17802. "Hook for functions to attach themselves to TAB.
  17803. See `org-ctrl-c-ctrl-c-hook' for more information.
  17804. This hook runs as the first action when TAB is pressed, even before
  17805. `org-cycle' messes around with the `outline-regexp' to cater for
  17806. inline tasks and plain list item folding.
  17807. If any function in this hook returns t, any other actions that
  17808. would have been caused by TAB (such as table field motion or visibility
  17809. cycling) will not occur.")
  17810. (defvar org-tab-after-check-for-table-hook nil
  17811. "Hook for functions to attach themselves to TAB.
  17812. See `org-ctrl-c-ctrl-c-hook' for more information.
  17813. This hook runs after it has been established that the cursor is not in a
  17814. table, but before checking if the cursor is in a headline or if global cycling
  17815. should be done.
  17816. If any function in this hook returns t, not other actions like visibility
  17817. cycling will be done.")
  17818. (defvar org-tab-after-check-for-cycling-hook nil
  17819. "Hook for functions to attach themselves to TAB.
  17820. See `org-ctrl-c-ctrl-c-hook' for more information.
  17821. This hook runs after it has been established that not table field motion and
  17822. not visibility should be done because of current context. This is probably
  17823. the place where a package like yasnippets can hook in.")
  17824. (defvar org-tab-before-tab-emulation-hook nil
  17825. "Hook for functions to attach themselves to TAB.
  17826. See `org-ctrl-c-ctrl-c-hook' for more information.
  17827. This hook runs after every other options for TAB have been exhausted, but
  17828. before indentation and \t insertion takes place.")
  17829. (defvar org-metaleft-hook nil
  17830. "Hook for functions attaching themselves to `M-left'.
  17831. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17832. (defvar org-metaright-hook nil
  17833. "Hook for functions attaching themselves to `M-right'.
  17834. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17835. (defvar org-metaup-hook nil
  17836. "Hook for functions attaching themselves to `M-up'.
  17837. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17838. (defvar org-metadown-hook nil
  17839. "Hook for functions attaching themselves to `M-down'.
  17840. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17841. (defvar org-shiftmetaleft-hook nil
  17842. "Hook for functions attaching themselves to `M-S-left'.
  17843. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17844. (defvar org-shiftmetaright-hook nil
  17845. "Hook for functions attaching themselves to `M-S-right'.
  17846. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17847. (defvar org-shiftmetaup-hook nil
  17848. "Hook for functions attaching themselves to `M-S-up'.
  17849. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17850. (defvar org-shiftmetadown-hook nil
  17851. "Hook for functions attaching themselves to `M-S-down'.
  17852. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17853. (defvar org-metareturn-hook nil
  17854. "Hook for functions attaching themselves to `M-RET'.
  17855. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17856. (defvar org-shiftup-hook nil
  17857. "Hook for functions attaching themselves to `S-up'.
  17858. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17859. (defvar org-shiftup-final-hook nil
  17860. "Hook for functions attaching themselves to `S-up'.
  17861. This one runs after all other options except shift-select have been excluded.
  17862. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17863. (defvar org-shiftdown-hook nil
  17864. "Hook for functions attaching themselves to `S-down'.
  17865. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17866. (defvar org-shiftdown-final-hook nil
  17867. "Hook for functions attaching themselves to `S-down'.
  17868. This one runs after all other options except shift-select have been excluded.
  17869. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17870. (defvar org-shiftleft-hook nil
  17871. "Hook for functions attaching themselves to `S-left'.
  17872. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17873. (defvar org-shiftleft-final-hook nil
  17874. "Hook for functions attaching themselves to `S-left'.
  17875. This one runs after all other options except shift-select have been excluded.
  17876. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17877. (defvar org-shiftright-hook nil
  17878. "Hook for functions attaching themselves to `S-right'.
  17879. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17880. (defvar org-shiftright-final-hook nil
  17881. "Hook for functions attaching themselves to `S-right'.
  17882. This one runs after all other options except shift-select have been excluded.
  17883. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17884. (defun org-modifier-cursor-error ()
  17885. "Throw an error, a modified cursor command was applied in wrong context."
  17886. (user-error "This command is active in special context like tables, headlines or items"))
  17887. (defun org-shiftselect-error ()
  17888. "Throw an error because Shift-Cursor command was applied in wrong context."
  17889. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17890. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17891. (user-error "This command works only in special context like headlines or timestamps")))
  17892. (defun org-call-for-shift-select (cmd)
  17893. (let ((this-command-keys-shift-translated t))
  17894. (call-interactively cmd)))
  17895. (defun org-shifttab (&optional arg)
  17896. "Global visibility cycling or move to previous table field.
  17897. Call `org-table-previous-field' within a table.
  17898. When ARG is nil, cycle globally through visibility states.
  17899. When ARG is a numeric prefix, show contents of this level."
  17900. (interactive "P")
  17901. (cond
  17902. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17903. ((integerp arg)
  17904. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17905. (message "Content view to level: %d" arg)
  17906. (org-content (prefix-numeric-value arg2))
  17907. (org-cycle-show-empty-lines t)
  17908. (setq org-cycle-global-status 'overview)))
  17909. (t (call-interactively 'org-global-cycle))))
  17910. (defun org-shiftmetaleft ()
  17911. "Promote subtree or delete table column.
  17912. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17913. `org-table-delete-column', depending on context. See the
  17914. individual commands for more information."
  17915. (interactive)
  17916. (cond
  17917. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17918. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17919. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17920. ((if (not (org-region-active-p)) (org-at-item-p)
  17921. (save-excursion (goto-char (region-beginning))
  17922. (org-at-item-p)))
  17923. (call-interactively 'org-outdent-item-tree))
  17924. (t (org-modifier-cursor-error))))
  17925. (defun org-shiftmetaright ()
  17926. "Demote subtree or insert table column.
  17927. Calls `org-demote-subtree', `org-indent-item-tree', or
  17928. `org-table-insert-column', depending on context. See the
  17929. individual commands for more information."
  17930. (interactive)
  17931. (cond
  17932. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17933. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17934. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17935. ((if (not (org-region-active-p)) (org-at-item-p)
  17936. (save-excursion (goto-char (region-beginning))
  17937. (org-at-item-p)))
  17938. (call-interactively 'org-indent-item-tree))
  17939. (t (org-modifier-cursor-error))))
  17940. (defun org-shiftmetaup (&optional _arg)
  17941. "Drag the line at point up.
  17942. In a table, kill the current row.
  17943. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17944. but also adjust the previous clocked item in the clock history.
  17945. Everywhere else, drag the line at point up."
  17946. (interactive "P")
  17947. (cond
  17948. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17949. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17950. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17951. (call-interactively 'org-timestamp-up)))
  17952. (t (call-interactively 'org-drag-line-backward))))
  17953. (defun org-shiftmetadown (&optional _arg)
  17954. "Drag the line at point down.
  17955. In a table, insert an empty row at the current line.
  17956. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17957. but also adjust the previous clocked item in the clock history.
  17958. Everywhere else, drag the line at point down."
  17959. (interactive "P")
  17960. (cond
  17961. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17962. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17963. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17964. (call-interactively 'org-timestamp-down)))
  17965. (t (call-interactively 'org-drag-line-forward))))
  17966. (defsubst org-hidden-tree-error ()
  17967. (user-error
  17968. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17969. (defun org-metaleft (&optional _arg)
  17970. "Promote heading, list item at point or move table column left.
  17971. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17972. depending on context. With no specific context, calls the Emacs
  17973. default `backward-word'. See the individual commands for more
  17974. information.
  17975. This function runs the hook `org-metaleft-hook' as a first step,
  17976. and returns at first non-nil value."
  17977. (interactive "P")
  17978. (cond
  17979. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17980. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17981. ((org-with-limited-levels
  17982. (or (org-at-heading-p)
  17983. (and (org-region-active-p)
  17984. (save-excursion
  17985. (goto-char (region-beginning))
  17986. (org-at-heading-p)))))
  17987. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17988. (call-interactively 'org-do-promote))
  17989. ;; At an inline task.
  17990. ((org-at-heading-p)
  17991. (call-interactively 'org-inlinetask-promote))
  17992. ((or (org-at-item-p)
  17993. (and (org-region-active-p)
  17994. (save-excursion
  17995. (goto-char (region-beginning))
  17996. (org-at-item-p))))
  17997. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17998. (call-interactively 'org-outdent-item))
  17999. (t (call-interactively 'backward-word))))
  18000. (defun org-metaright (&optional _arg)
  18001. "Demote heading, list item at point or move table column right.
  18002. In front of a drawer or a block keyword, indent it correctly.
  18003. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18004. `org-indent-drawer' or `org-indent-block' depending on context.
  18005. With no specific context, calls the Emacs default `forward-word'.
  18006. See the individual commands for more information.
  18007. This function runs the hook `org-metaright-hook' as a first step,
  18008. and returns at first non-nil value."
  18009. (interactive "P")
  18010. (cond
  18011. ((run-hook-with-args-until-success 'org-metaright-hook))
  18012. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18013. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18014. ((org-at-block-p) (call-interactively 'org-indent-block))
  18015. ((org-with-limited-levels
  18016. (or (org-at-heading-p)
  18017. (and (org-region-active-p)
  18018. (save-excursion
  18019. (goto-char (region-beginning))
  18020. (org-at-heading-p)))))
  18021. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18022. (call-interactively 'org-do-demote))
  18023. ;; At an inline task.
  18024. ((org-at-heading-p)
  18025. (call-interactively 'org-inlinetask-demote))
  18026. ((or (org-at-item-p)
  18027. (and (org-region-active-p)
  18028. (save-excursion
  18029. (goto-char (region-beginning))
  18030. (org-at-item-p))))
  18031. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18032. (call-interactively 'org-indent-item))
  18033. (t (call-interactively 'forward-word))))
  18034. (defun org-check-for-hidden (what)
  18035. "Check if there are hidden headlines/items in the current visual line.
  18036. WHAT can be either `headlines' or `items'. If the current line is
  18037. an outline or item heading and it has a folded subtree below it,
  18038. this function returns t, nil otherwise."
  18039. (let ((re (cond
  18040. ((eq what 'headlines) org-outline-regexp-bol)
  18041. ((eq what 'items) (org-item-beginning-re))
  18042. (t (error "This should not happen"))))
  18043. beg end)
  18044. (save-excursion
  18045. (catch 'exit
  18046. (unless (org-region-active-p)
  18047. (setq beg (point-at-bol))
  18048. (beginning-of-line 2)
  18049. (while (and (not (eobp)) ;; this is like `next-line'
  18050. (get-char-property (1- (point)) 'invisible))
  18051. (beginning-of-line 2))
  18052. (setq end (point))
  18053. (goto-char beg)
  18054. (goto-char (point-at-eol))
  18055. (setq end (max end (point)))
  18056. (while (re-search-forward re end t)
  18057. (when (get-char-property (match-beginning 0) 'invisible)
  18058. (throw 'exit t))))
  18059. nil))))
  18060. (defun org-metaup (&optional _arg)
  18061. "Move subtree up or move table row up.
  18062. Calls `org-move-subtree-up' or `org-table-move-row' or
  18063. `org-move-item-up', depending on context. See the individual commands
  18064. for more information."
  18065. (interactive "P")
  18066. (cond
  18067. ((run-hook-with-args-until-success 'org-metaup-hook))
  18068. ((org-region-active-p)
  18069. (let* ((a (save-excursion
  18070. (goto-char (min (region-beginning) (region-end)))
  18071. (line-beginning-position)))
  18072. (b (save-excursion
  18073. (goto-char (max (region-beginning) (region-end)))
  18074. (if (bolp) (1- (point)) (line-end-position))))
  18075. (c (save-excursion
  18076. (goto-char a)
  18077. (move-beginning-of-line 0)
  18078. (point)))
  18079. (d (save-excursion
  18080. (goto-char a)
  18081. (move-end-of-line 0)
  18082. (point))))
  18083. (transpose-regions a b c d)
  18084. (goto-char c)))
  18085. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18086. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18087. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18088. (t (org-drag-element-backward))))
  18089. (defun org-metadown (&optional _arg)
  18090. "Move subtree down or move table row down.
  18091. Calls `org-move-subtree-down' or `org-table-move-row' or
  18092. `org-move-item-down', depending on context. See the individual
  18093. commands for more information."
  18094. (interactive "P")
  18095. (cond
  18096. ((run-hook-with-args-until-success 'org-metadown-hook))
  18097. ((org-region-active-p)
  18098. (let* ((a (save-excursion
  18099. (goto-char (min (region-beginning) (region-end)))
  18100. (line-beginning-position)))
  18101. (b (save-excursion
  18102. (goto-char (max (region-beginning) (region-end)))
  18103. (if (bolp) (1- (point)) (line-end-position))))
  18104. (c (save-excursion
  18105. (goto-char b)
  18106. (move-beginning-of-line (if (bolp) 1 2))
  18107. (point)))
  18108. (d (save-excursion
  18109. (goto-char b)
  18110. (move-end-of-line (if (bolp) 1 2))
  18111. (point))))
  18112. (transpose-regions a b c d)
  18113. (goto-char d)))
  18114. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18115. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18116. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18117. (t (org-drag-element-forward))))
  18118. (defun org-shiftup (&optional arg)
  18119. "Increase item in timestamp or increase priority of current headline.
  18120. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18121. depending on context. See the individual commands for more information."
  18122. (interactive "P")
  18123. (cond
  18124. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18125. ((and org-support-shift-select (org-region-active-p))
  18126. (org-call-for-shift-select 'previous-line))
  18127. ((org-at-timestamp-p 'lax)
  18128. (call-interactively (if org-edit-timestamp-down-means-later
  18129. 'org-timestamp-down 'org-timestamp-up)))
  18130. ((and (not (eq org-support-shift-select 'always))
  18131. org-enable-priority-commands
  18132. (org-at-heading-p))
  18133. (call-interactively 'org-priority-up))
  18134. ((and (not org-support-shift-select) (org-at-item-p))
  18135. (call-interactively 'org-previous-item))
  18136. ((org-clocktable-try-shift 'up arg))
  18137. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18138. (org-support-shift-select
  18139. (org-call-for-shift-select 'previous-line))
  18140. (t (org-shiftselect-error))))
  18141. (defun org-shiftdown (&optional arg)
  18142. "Decrease item in timestamp or decrease priority of current headline.
  18143. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18144. depending on context. See the individual commands for more information."
  18145. (interactive "P")
  18146. (cond
  18147. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18148. ((and org-support-shift-select (org-region-active-p))
  18149. (org-call-for-shift-select 'next-line))
  18150. ((org-at-timestamp-p 'lax)
  18151. (call-interactively (if org-edit-timestamp-down-means-later
  18152. 'org-timestamp-up 'org-timestamp-down)))
  18153. ((and (not (eq org-support-shift-select 'always))
  18154. org-enable-priority-commands
  18155. (org-at-heading-p))
  18156. (call-interactively 'org-priority-down))
  18157. ((and (not org-support-shift-select) (org-at-item-p))
  18158. (call-interactively 'org-next-item))
  18159. ((org-clocktable-try-shift 'down arg))
  18160. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18161. (org-support-shift-select
  18162. (org-call-for-shift-select 'next-line))
  18163. (t (org-shiftselect-error))))
  18164. (defun org-shiftright (&optional arg)
  18165. "Cycle the thing at point or in the current line, depending on context.
  18166. Depending on context, this does one of the following:
  18167. - switch a timestamp at point one day into the future
  18168. - on a headline, switch to the next TODO keyword.
  18169. - on an item, switch entire list to the next bullet type
  18170. - on a property line, switch to the next allowed value
  18171. - on a clocktable definition line, move time block into the future"
  18172. (interactive "P")
  18173. (cond
  18174. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18175. ((and org-support-shift-select (org-region-active-p))
  18176. (org-call-for-shift-select 'forward-char))
  18177. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18178. ((and (not (eq org-support-shift-select 'always))
  18179. (org-at-heading-p))
  18180. (let ((org-inhibit-logging
  18181. (not org-treat-S-cursor-todo-selection-as-state-change))
  18182. (org-inhibit-blocking
  18183. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18184. (org-call-with-arg 'org-todo 'right)))
  18185. ((or (and org-support-shift-select
  18186. (not (eq org-support-shift-select 'always))
  18187. (org-at-item-bullet-p))
  18188. (and (not org-support-shift-select) (org-at-item-p)))
  18189. (org-call-with-arg 'org-cycle-list-bullet nil))
  18190. ((and (not (eq org-support-shift-select 'always))
  18191. (org-at-property-p))
  18192. (call-interactively 'org-property-next-allowed-value))
  18193. ((org-clocktable-try-shift 'right arg))
  18194. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18195. (org-support-shift-select
  18196. (org-call-for-shift-select 'forward-char))
  18197. (t (org-shiftselect-error))))
  18198. (defun org-shiftleft (&optional arg)
  18199. "Cycle the thing at point or in the current line, depending on context.
  18200. Depending on context, this does one of the following:
  18201. - switch a timestamp at point one day into the past
  18202. - on a headline, switch to the previous TODO keyword.
  18203. - on an item, switch entire list to the previous bullet type
  18204. - on a property line, switch to the previous allowed value
  18205. - on a clocktable definition line, move time block into the past"
  18206. (interactive "P")
  18207. (cond
  18208. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18209. ((and org-support-shift-select (org-region-active-p))
  18210. (org-call-for-shift-select 'backward-char))
  18211. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18212. ((and (not (eq org-support-shift-select 'always))
  18213. (org-at-heading-p))
  18214. (let ((org-inhibit-logging
  18215. (not org-treat-S-cursor-todo-selection-as-state-change))
  18216. (org-inhibit-blocking
  18217. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18218. (org-call-with-arg 'org-todo 'left)))
  18219. ((or (and org-support-shift-select
  18220. (not (eq org-support-shift-select 'always))
  18221. (org-at-item-bullet-p))
  18222. (and (not org-support-shift-select) (org-at-item-p)))
  18223. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18224. ((and (not (eq org-support-shift-select 'always))
  18225. (org-at-property-p))
  18226. (call-interactively 'org-property-previous-allowed-value))
  18227. ((org-clocktable-try-shift 'left arg))
  18228. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18229. (org-support-shift-select
  18230. (org-call-for-shift-select 'backward-char))
  18231. (t (org-shiftselect-error))))
  18232. (defun org-shiftcontrolright ()
  18233. "Switch to next TODO set."
  18234. (interactive)
  18235. (cond
  18236. ((and org-support-shift-select (org-region-active-p))
  18237. (org-call-for-shift-select 'forward-word))
  18238. ((and (not (eq org-support-shift-select 'always))
  18239. (org-at-heading-p))
  18240. (org-call-with-arg 'org-todo 'nextset))
  18241. (org-support-shift-select
  18242. (org-call-for-shift-select 'forward-word))
  18243. (t (org-shiftselect-error))))
  18244. (defun org-shiftcontrolleft ()
  18245. "Switch to previous TODO set."
  18246. (interactive)
  18247. (cond
  18248. ((and org-support-shift-select (org-region-active-p))
  18249. (org-call-for-shift-select 'backward-word))
  18250. ((and (not (eq org-support-shift-select 'always))
  18251. (org-at-heading-p))
  18252. (org-call-with-arg 'org-todo 'previousset))
  18253. (org-support-shift-select
  18254. (org-call-for-shift-select 'backward-word))
  18255. (t (org-shiftselect-error))))
  18256. (defun org-shiftcontrolup (&optional n)
  18257. "Change timestamps synchronously up in CLOCK log lines.
  18258. Optional argument N tells to change by that many units."
  18259. (interactive "P")
  18260. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18261. (let (org-support-shift-select)
  18262. (org-clock-timestamps-up n))
  18263. (user-error "Not at a clock log")))
  18264. (defun org-shiftcontroldown (&optional n)
  18265. "Change timestamps synchronously down in CLOCK log lines.
  18266. Optional argument N tells to change by that many units."
  18267. (interactive "P")
  18268. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18269. (let (org-support-shift-select)
  18270. (org-clock-timestamps-down n))
  18271. (user-error "Not at a clock log")))
  18272. (defun org-increase-number-at-point (&optional inc)
  18273. "Increment the number at point.
  18274. With an optional prefix numeric argument INC, increment using
  18275. this numeric value."
  18276. (interactive "p")
  18277. (if (not (number-at-point))
  18278. (user-error "Not on a number")
  18279. (unless inc (setq inc 1))
  18280. (let ((pos (point))
  18281. (beg (skip-chars-backward "-+^/*0-9eE."))
  18282. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18283. (setq nap (buffer-substring-no-properties
  18284. (+ pos beg) (+ pos beg end)))
  18285. (delete-region (+ pos beg) (+ pos beg end))
  18286. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18287. (when (org-at-table-p)
  18288. (org-table-align)
  18289. (org-table-end-of-field 1))))
  18290. (defun org-decrease-number-at-point (&optional inc)
  18291. "Decrement the number at point.
  18292. With an optional prefix numeric argument INC, decrement using
  18293. this numeric value."
  18294. (interactive "p")
  18295. (org-increase-number-at-point (- (or inc 1))))
  18296. (defun org-ctrl-c-ret ()
  18297. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18298. (interactive)
  18299. (cond
  18300. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18301. (t (call-interactively 'org-insert-heading))))
  18302. (defun org-find-visible ()
  18303. (let ((s (point)))
  18304. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18305. (get-char-property s 'invisible)))
  18306. s))
  18307. (defun org-find-invisible ()
  18308. (let ((s (point)))
  18309. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18310. (not (get-char-property s 'invisible))))
  18311. s))
  18312. (defun org-copy-visible (beg end)
  18313. "Copy the visible parts of the region."
  18314. (interactive "r")
  18315. (let ((result ""))
  18316. (while (/= beg end)
  18317. (when (get-char-property beg 'invisible)
  18318. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18319. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18320. (setq result (concat result (buffer-substring beg next)))
  18321. (setq beg next)))
  18322. (setq deactivate-mark t)
  18323. (kill-new result)
  18324. (message "Visible strings have been copied to the kill ring.")))
  18325. (defun org-copy-special ()
  18326. "Copy region in table or copy current subtree.
  18327. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18328. context. See the individual commands for more information."
  18329. (interactive)
  18330. (call-interactively
  18331. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18332. (defun org-cut-special ()
  18333. "Cut region in table or cut current subtree.
  18334. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18335. context. See the individual commands for more information."
  18336. (interactive)
  18337. (call-interactively
  18338. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18339. (defun org-paste-special (arg)
  18340. "Paste rectangular region into table, or past subtree relative to level.
  18341. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18342. See the individual commands for more information."
  18343. (interactive "P")
  18344. (if (org-at-table-p)
  18345. (org-table-paste-rectangle)
  18346. (org-paste-subtree arg)))
  18347. (defun org-edit-special (&optional arg)
  18348. "Call a special editor for the element at point.
  18349. When at a table, call the formula editor with `org-table-edit-formulas'.
  18350. When in a source code block, call `org-edit-src-code'.
  18351. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18352. When in an export block, call `org-edit-export-block'.
  18353. When in a LaTeX environment, call `org-edit-latex-environment'.
  18354. When at an #+INCLUDE keyword, visit the included file.
  18355. When at a footnote reference, call `org-edit-footnote-reference'.
  18356. When at a planning line call, `org-deadline' and/or `org-schedule'.
  18357. When at an active timestamp, call `org-time-stamp'.
  18358. When at an inactive timestamp, call `org-time-stamp-inactive'.
  18359. On a link, call `ffap' to visit the link at point.
  18360. Otherwise, return a user error."
  18361. (interactive "P")
  18362. (let ((element (org-element-at-point)))
  18363. (barf-if-buffer-read-only)
  18364. (pcase (org-element-type element)
  18365. (`src-block
  18366. (if (not arg) (org-edit-src-code)
  18367. (let* ((info (org-babel-get-src-block-info))
  18368. (lang (nth 0 info))
  18369. (params (nth 2 info))
  18370. (session (cdr (assq :session params))))
  18371. (if (not session) (org-edit-src-code)
  18372. ;; At a source block with a session and function called
  18373. ;; with an ARG: switch to the buffer related to the
  18374. ;; inferior process.
  18375. (switch-to-buffer
  18376. (funcall (intern (concat "org-babel-prep-session:" lang))
  18377. session params))))))
  18378. (`keyword
  18379. (unless (member (org-element-property :key element)
  18380. '("INCLUDE" "SETUPFILE"))
  18381. (user-error "No special environment to edit here"))
  18382. (let ((value (org-element-property :value element)))
  18383. (unless (org-string-nw-p value) (user-error "No file to edit"))
  18384. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  18385. (or (match-string 1 value)
  18386. (match-string 0 value)))))
  18387. (when (org-file-url-p file)
  18388. (user-error "Files located with a URL cannot be edited"))
  18389. (org-open-link-from-string
  18390. (format "[[%s]]" (expand-file-name file))))))
  18391. (`table
  18392. (if (eq (org-element-property :type element) 'table.el)
  18393. (org-edit-table.el)
  18394. (call-interactively 'org-table-edit-formulas)))
  18395. ;; Only Org tables contain `table-row' type elements.
  18396. (`table-row (call-interactively 'org-table-edit-formulas))
  18397. (`example-block (org-edit-src-code))
  18398. (`export-block (org-edit-export-block))
  18399. (`fixed-width (org-edit-fixed-width-region))
  18400. (`latex-environment (org-edit-latex-environment))
  18401. (`planning
  18402. (let ((proplist (cadr element)))
  18403. (mapc #'call-interactively
  18404. (remq nil
  18405. (list
  18406. (when (plist-get proplist :deadline) #'org-deadline)
  18407. (when (plist-get proplist :scheduled) #'org-schedule))))))
  18408. (_
  18409. ;; No notable element at point. Though, we may be at a link or
  18410. ;; a footnote reference, which are objects. Thus, scan deeper.
  18411. (let ((context (org-element-context element)))
  18412. (pcase (org-element-type context)
  18413. (`footnote-reference (org-edit-footnote-reference))
  18414. (`inline-src-block (org-edit-inline-src-code))
  18415. (`timestamp (if (eq 'inactive (org-element-property :type context))
  18416. (call-interactively #'org-time-stamp-inactive)
  18417. (call-interactively #'org-time-stamp)))
  18418. (`link (call-interactively #'ffap))
  18419. (_ (user-error "No special environment to edit here"))))))))
  18420. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18421. (defun org-ctrl-c-ctrl-c (&optional arg)
  18422. "Set tags in headline, or update according to changed information at point.
  18423. This command does many different things, depending on context:
  18424. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18425. this is what we do.
  18426. - If the cursor is on a statistics cookie, update it.
  18427. - If the cursor is in a headline, prompt for tags and insert them
  18428. into the current line, aligned to `org-tags-column'. When called
  18429. with prefix arg, realign all tags in the current buffer.
  18430. - If the cursor is in one of the special #+KEYWORD lines, this
  18431. triggers scanning the buffer for these lines and updating the
  18432. information.
  18433. - If the cursor is inside a table, realign the table. This command
  18434. works even if the automatic table editor has been turned off.
  18435. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18436. the entire table.
  18437. - If the cursor is at a footnote reference or definition, jump to
  18438. the corresponding definition or references, respectively.
  18439. - If the cursor is a the beginning of a dynamic block, update it.
  18440. - If the current buffer is a capture buffer, close note and file it.
  18441. - If the cursor is on a <<<target>>>, update radio targets and
  18442. corresponding links in this buffer.
  18443. - If the cursor is on a numbered item in a plain list, renumber the
  18444. ordered list.
  18445. - If the cursor is on a checkbox, toggle it.
  18446. - If the cursor is on a code block, evaluate it. The variable
  18447. `org-confirm-babel-evaluate' can be used to control prompting
  18448. before code block evaluation, by default every code block
  18449. evaluation requires confirmation. Code block evaluation can be
  18450. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18451. (interactive "P")
  18452. (cond
  18453. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18454. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18455. (org-remove-occur-highlights)
  18456. (message "Temporary highlights/overlays removed from current buffer"))
  18457. ((and (local-variable-p 'org-finish-function)
  18458. (fboundp org-finish-function))
  18459. (funcall org-finish-function))
  18460. ((org-babel-hash-at-point))
  18461. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18462. (t
  18463. (let* ((context
  18464. (org-element-lineage
  18465. (org-element-context)
  18466. ;; Limit to supported contexts.
  18467. '(babel-call clock dynamic-block footnote-definition
  18468. footnote-reference inline-babel-call inline-src-block
  18469. inlinetask item keyword node-property paragraph
  18470. plain-list planning property-drawer radio-target
  18471. src-block statistics-cookie table table-cell table-row
  18472. timestamp)
  18473. t))
  18474. (type (org-element-type context)))
  18475. ;; For convenience: at the first line of a paragraph on the same
  18476. ;; line as an item, apply function on that item instead.
  18477. (when (eq type 'paragraph)
  18478. (let ((parent (org-element-property :parent context)))
  18479. (when (and (eq (org-element-type parent) 'item)
  18480. (= (line-beginning-position)
  18481. (org-element-property :begin parent)))
  18482. (setq context parent)
  18483. (setq type 'item))))
  18484. ;; Act according to type of element or object at point.
  18485. ;;
  18486. ;; Do nothing on a blank line, except if it is contained in
  18487. ;; a source block. Hence, we first check if point is in such
  18488. ;; a block and then if it is at a blank line.
  18489. (pcase type
  18490. ((or `inline-src-block `src-block)
  18491. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18492. (org-babel-eval-wipe-error-buffer)
  18493. (org-babel-execute-src-block
  18494. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18495. ((guard (org-match-line "[ \t]*$"))
  18496. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18497. (user-error
  18498. (substitute-command-keys
  18499. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18500. ((or `babel-call `inline-babel-call)
  18501. (let ((info (org-babel-lob-get-info context)))
  18502. (when info (org-babel-execute-src-block nil info))))
  18503. (`clock (org-clock-update-time-maybe))
  18504. (`dynamic-block
  18505. (save-excursion
  18506. (goto-char (org-element-property :post-affiliated context))
  18507. (org-update-dblock)))
  18508. (`footnote-definition
  18509. (goto-char (org-element-property :post-affiliated context))
  18510. (call-interactively 'org-footnote-action))
  18511. (`footnote-reference (call-interactively #'org-footnote-action))
  18512. ((or `headline `inlinetask)
  18513. (save-excursion (goto-char (org-element-property :begin context))
  18514. (call-interactively #'org-set-tags-command)))
  18515. (`item
  18516. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18517. ;; unconditionally, whereas `C-u' will toggle its presence.
  18518. ;; Without a universal argument, if the item has a checkbox,
  18519. ;; toggle it. Otherwise repair the list.
  18520. (let* ((box (org-element-property :checkbox context))
  18521. (struct (org-element-property :structure context))
  18522. (old-struct (copy-tree struct))
  18523. (parents (org-list-parents-alist struct))
  18524. (prevs (org-list-prevs-alist struct))
  18525. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18526. (org-list-set-checkbox
  18527. (org-element-property :begin context) struct
  18528. (cond ((equal arg '(16)) "[-]")
  18529. ((and (not box) (equal arg '(4))) "[ ]")
  18530. ((or (not box) (equal arg '(4))) nil)
  18531. ((eq box 'on) "[ ]")
  18532. (t "[X]")))
  18533. ;; Mimic `org-list-write-struct' but with grabbing a return
  18534. ;; value from `org-list-struct-fix-box'.
  18535. (org-list-struct-fix-ind struct parents 2)
  18536. (org-list-struct-fix-item-end struct)
  18537. (org-list-struct-fix-bul struct prevs)
  18538. (org-list-struct-fix-ind struct parents)
  18539. (let ((block-item
  18540. (org-list-struct-fix-box struct parents prevs orderedp)))
  18541. (if (and box (equal struct old-struct))
  18542. (if (equal arg '(16))
  18543. (message "Checkboxes already reset")
  18544. (user-error "Cannot toggle this checkbox: %s"
  18545. (if (eq box 'on)
  18546. "all subitems checked"
  18547. "unchecked subitems")))
  18548. (org-list-struct-apply-struct struct old-struct)
  18549. (org-update-checkbox-count-maybe))
  18550. (when block-item
  18551. (message "Checkboxes were removed due to empty box at line %d"
  18552. (org-current-line block-item))))))
  18553. (`keyword
  18554. (let ((org-inhibit-startup-visibility-stuff t)
  18555. (org-startup-align-all-tables nil))
  18556. (when (boundp 'org-table-coordinate-overlays)
  18557. (mapc #'delete-overlay org-table-coordinate-overlays)
  18558. (setq org-table-coordinate-overlays nil))
  18559. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18560. (message "Local setup has been refreshed"))
  18561. (`plain-list
  18562. ;; At a plain list, with a double C-u argument, set
  18563. ;; checkboxes of each item to "[-]", whereas a single one
  18564. ;; will toggle their presence according to the state of the
  18565. ;; first item in the list. Without an argument, repair the
  18566. ;; list.
  18567. (let* ((begin (org-element-property :contents-begin context))
  18568. (struct (org-element-property :structure context))
  18569. (old-struct (copy-tree struct))
  18570. (first-box (save-excursion
  18571. (goto-char begin)
  18572. (looking-at org-list-full-item-re)
  18573. (match-string-no-properties 3)))
  18574. (new-box (cond ((equal arg '(16)) "[-]")
  18575. ((equal arg '(4)) (unless first-box "[ ]"))
  18576. ((equal first-box "[X]") "[ ]")
  18577. (t "[X]"))))
  18578. (cond
  18579. (arg
  18580. (dolist (pos
  18581. (org-list-get-all-items
  18582. begin struct (org-list-prevs-alist struct)))
  18583. (org-list-set-checkbox pos struct new-box)))
  18584. ((and first-box (eq (point) begin))
  18585. ;; For convenience, when point is at bol on the first
  18586. ;; item of the list and no argument is provided, simply
  18587. ;; toggle checkbox of that item, if any.
  18588. (org-list-set-checkbox begin struct new-box)))
  18589. (when (equal
  18590. (org-list-write-struct
  18591. struct (org-list-parents-alist struct) old-struct)
  18592. old-struct)
  18593. (message "Cannot update this checkbox"))
  18594. (org-update-checkbox-count-maybe)))
  18595. ((or `property-drawer `node-property)
  18596. (call-interactively #'org-property-action))
  18597. (`radio-target
  18598. (call-interactively #'org-update-radio-target-regexp))
  18599. (`statistics-cookie
  18600. (call-interactively #'org-update-statistics-cookies))
  18601. ((or `table `table-cell `table-row)
  18602. ;; At a table, recalculate every field and align it. Also
  18603. ;; send the table if necessary. If the table has
  18604. ;; a `table.el' type, just give up. At a table row or cell,
  18605. ;; maybe recalculate line but always align table.
  18606. (if (eq (org-element-property :type context) 'table.el)
  18607. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18608. Use `\\[org-edit-special]' to edit table.el tables"))
  18609. (if (or (eq type 'table)
  18610. ;; Check if point is at a TBLFM line.
  18611. (and (eq type 'table-row)
  18612. (= (point) (org-element-property :end context))))
  18613. (save-excursion
  18614. (if (org-at-TBLFM-p)
  18615. (progn (require 'org-table)
  18616. (org-table-calc-current-TBLFM))
  18617. (goto-char (org-element-property :contents-begin context))
  18618. (org-call-with-arg 'org-table-recalculate (or arg t))
  18619. (orgtbl-send-table 'maybe)))
  18620. (org-table-maybe-eval-formula)
  18621. (cond (arg (call-interactively #'org-table-recalculate))
  18622. ((org-table-maybe-recalculate-line))
  18623. (t (org-table-align))))))
  18624. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18625. (org-timestamp-change 0 'day))
  18626. ((and `nil (guard (org-at-heading-p)))
  18627. ;; When point is on an unsupported object type, we can miss
  18628. ;; the fact that it also is at a heading. Handle it here.
  18629. (call-interactively #'org-set-tags-command))
  18630. ((guard
  18631. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18632. (_
  18633. (user-error
  18634. (substitute-command-keys
  18635. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18636. (defun org-mode-restart ()
  18637. (interactive)
  18638. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18639. (funcall major-mode)
  18640. (hack-local-variables)
  18641. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18642. (org-indent-mode -1))
  18643. (org-reset-file-cache))
  18644. (message "%s restarted" major-mode))
  18645. (defun org-kill-note-or-show-branches ()
  18646. "Abort storing current note, or call `outline-show-branches'."
  18647. (interactive)
  18648. (if (not org-finish-function)
  18649. (save-excursion
  18650. (save-restriction
  18651. (org-narrow-to-subtree)
  18652. (org-flag-subtree t)
  18653. (call-interactively 'outline-show-branches)
  18654. (org-hide-archived-subtrees (point-min) (point-max))))
  18655. (let ((org-note-abort t))
  18656. (funcall org-finish-function))))
  18657. (defun org-delete-indentation (&optional arg)
  18658. "Join current line to previous and fix whitespace at join.
  18659. If previous line is a headline add to headline title. Otherwise
  18660. the function calls `delete-indentation'.
  18661. With a non-nil optional argument, join it to the following one."
  18662. (interactive "*P")
  18663. (if (save-excursion
  18664. (beginning-of-line (if arg 1 0))
  18665. (let ((case-fold-search nil))
  18666. (looking-at org-complex-heading-regexp)))
  18667. ;; At headline.
  18668. (let ((tags-column (when (match-beginning 5)
  18669. (save-excursion (goto-char (match-beginning 5))
  18670. (current-column))))
  18671. (string (concat " " (progn (when arg (forward-line 1))
  18672. (org-trim (delete-and-extract-region
  18673. (line-beginning-position)
  18674. (line-end-position)))))))
  18675. (unless (bobp) (delete-region (point) (1- (point))))
  18676. (goto-char (or (match-end 4)
  18677. (match-beginning 5)
  18678. (match-end 0)))
  18679. (skip-chars-backward " \t")
  18680. (save-excursion (insert string))
  18681. ;; Adjust alignment of tags.
  18682. (cond
  18683. ((not tags-column)) ;no tags
  18684. (org-auto-align-tags (org-align-tags))
  18685. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18686. (delete-indentation arg)))
  18687. (defun org-open-line (n)
  18688. "Insert a new row in tables, call `open-line' elsewhere.
  18689. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18690. As a special case, when a document starts with a table, allow to
  18691. call `open-line' on the very first character."
  18692. (interactive "*p")
  18693. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18694. (org-table-insert-row)
  18695. (open-line n)))
  18696. (defun org-return (&optional indent)
  18697. "Goto next table row or insert a newline.
  18698. Calls `org-table-next-row' or `newline', depending on context.
  18699. When optional INDENT argument is non-nil, call
  18700. `newline-and-indent' instead of `newline'.
  18701. When `org-return-follows-link' is non-nil and point is on
  18702. a timestamp or a link, call `org-open-at-point'. However, it
  18703. will not happen if point is in a table or on a \"dead\"
  18704. object (e.g., within a comment). In these case, you need to use
  18705. `org-open-at-point' directly."
  18706. (interactive)
  18707. (let ((context (if org-return-follows-link (org-element-context)
  18708. (org-element-at-point))))
  18709. (cond
  18710. ;; In a table, call `org-table-next-row'. However, before first
  18711. ;; column or after last one, split the table.
  18712. ((or (and (eq 'table (org-element-type context))
  18713. (not (eq 'table.el (org-element-property :type context)))
  18714. (>= (point) (org-element-property :contents-begin context))
  18715. (< (point) (org-element-property :contents-end context)))
  18716. (org-element-lineage context '(table-row table-cell) t))
  18717. (if (or (looking-at-p "[ \t]*$")
  18718. (save-excursion (skip-chars-backward " \t") (bolp)))
  18719. (insert "\n")
  18720. (org-table-justify-field-maybe)
  18721. (call-interactively #'org-table-next-row)))
  18722. ;; On a link or a timestamp, call `org-open-at-point' if
  18723. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18724. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18725. ((and org-return-follows-link
  18726. (or (and (eq 'link (org-element-type context))
  18727. ;; Ensure point is not on the white spaces after
  18728. ;; the link.
  18729. (let ((origin (point)))
  18730. (org-with-point-at (org-element-property :end context)
  18731. (skip-chars-backward " \t")
  18732. (> (point) origin))))
  18733. (org-in-regexp org-ts-regexp-both nil t)
  18734. (org-in-regexp org-tsr-regexp-both nil t)
  18735. (org-in-regexp org-any-link-re nil t)))
  18736. (call-interactively #'org-open-at-point))
  18737. ;; Insert newline in heading, but preserve tags.
  18738. ((and (not (bolp))
  18739. (let ((case-fold-search nil))
  18740. (org-match-line org-complex-heading-regexp)))
  18741. ;; At headline. Split line. However, if point is on keyword,
  18742. ;; priority cookie or tags, do not break any of them: add
  18743. ;; a newline after the headline instead.
  18744. (let ((tags-column (and (match-beginning 5)
  18745. (save-excursion (goto-char (match-beginning 5))
  18746. (current-column))))
  18747. (string
  18748. (when (and (match-end 4) (org-point-in-group (point) 4))
  18749. (delete-and-extract-region (point) (match-end 4)))))
  18750. ;; Adjust tag alignment.
  18751. (cond
  18752. ((not (and tags-column string)))
  18753. (org-auto-align-tags (org-align-tags))
  18754. (t (org--align-tags-here tags-column))) ;preserve tags column
  18755. (end-of-line)
  18756. (org-show-entry)
  18757. (if indent (newline-and-indent) (newline))
  18758. (when string (save-excursion (insert (org-trim string))))))
  18759. ;; In a list, make sure indenting keeps trailing text within.
  18760. ((and indent
  18761. (not (eolp))
  18762. (org-element-lineage context '(item)))
  18763. (let ((trailing-data
  18764. (delete-and-extract-region (point) (line-end-position))))
  18765. (newline-and-indent)
  18766. (save-excursion (insert trailing-data))))
  18767. (t
  18768. ;; Do not auto-fill when point is in an Org property drawer.
  18769. (let ((auto-fill-function (and (not (org-at-property-p))
  18770. auto-fill-function)))
  18771. (if indent
  18772. (newline-and-indent)
  18773. (newline)))))))
  18774. (defun org-return-indent ()
  18775. "Goto next table row or insert a newline and indent.
  18776. Calls `org-table-next-row' or `newline-and-indent', depending on
  18777. context. See the individual commands for more information."
  18778. (interactive)
  18779. (org-return t))
  18780. (defun org-ctrl-c-tab (&optional _arg)
  18781. "Toggle columns width in a table, or show children.
  18782. Call `org-table-toggle-column-width' if point is in a table.
  18783. Otherwise, call `org-show-children'."
  18784. (interactive "p")
  18785. (call-interactively
  18786. (if (org-at-table-p) #'org-table-toggle-column-width
  18787. #'org-show-children)))
  18788. (defun org-ctrl-c-star ()
  18789. "Compute table, or change heading status of lines.
  18790. Calls `org-table-recalculate' or `org-toggle-heading',
  18791. depending on context."
  18792. (interactive)
  18793. (cond
  18794. ((org-at-table-p)
  18795. (call-interactively 'org-table-recalculate))
  18796. (t
  18797. ;; Convert all lines in region to list items
  18798. (call-interactively 'org-toggle-heading))))
  18799. (defun org-ctrl-c-minus ()
  18800. "Insert separator line in table or modify bullet status of line.
  18801. Also turns a plain line or a region of lines into list items.
  18802. Calls `org-table-insert-hline', `org-toggle-item', or
  18803. `org-cycle-list-bullet', depending on context."
  18804. (interactive)
  18805. (cond
  18806. ((org-at-table-p)
  18807. (call-interactively 'org-table-insert-hline))
  18808. ((org-region-active-p)
  18809. (call-interactively 'org-toggle-item))
  18810. ((org-in-item-p)
  18811. (call-interactively 'org-cycle-list-bullet))
  18812. (t
  18813. (call-interactively 'org-toggle-item))))
  18814. (defun org-toggle-heading (&optional nstars)
  18815. "Convert headings to normal text, or items or text to headings.
  18816. If there is no active region, only convert the current line.
  18817. With a `\\[universal-argument]' prefix, convert the whole list at
  18818. point into heading.
  18819. In a region:
  18820. - If the first non blank line is a headline, remove the stars
  18821. from all headlines in the region.
  18822. - If it is a normal line, turn each and every normal line (i.e.,
  18823. not an heading or an item) in the region into headings. If you
  18824. want to convert only the first line of this region, use one
  18825. universal prefix argument.
  18826. - If it is a plain list item, turn all plain list items into headings.
  18827. When converting a line into a heading, the number of stars is chosen
  18828. such that the lines become children of the current entry. However,
  18829. when a numeric prefix argument is given, its value determines the
  18830. number of stars to add."
  18831. (interactive "P")
  18832. (let ((skip-blanks
  18833. (function
  18834. ;; Return beginning of first non-blank line, starting from
  18835. ;; line at POS.
  18836. (lambda (pos)
  18837. (save-excursion
  18838. (goto-char pos)
  18839. (while (org-at-comment-p) (forward-line))
  18840. (skip-chars-forward " \r\t\n")
  18841. (point-at-bol)))))
  18842. beg end toggled)
  18843. ;; Determine boundaries of changes. If a universal prefix has
  18844. ;; been given, put the list in a region. If region ends at a bol,
  18845. ;; do not consider the last line to be in the region.
  18846. (when (and current-prefix-arg (org-at-item-p))
  18847. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18848. (org-mark-element))
  18849. (if (org-region-active-p)
  18850. (setq beg (funcall skip-blanks (region-beginning))
  18851. end (copy-marker (save-excursion
  18852. (goto-char (region-end))
  18853. (if (bolp) (point) (point-at-eol)))))
  18854. (setq beg (funcall skip-blanks (point-at-bol))
  18855. end (copy-marker (point-at-eol))))
  18856. ;; Ensure inline tasks don't count as headings.
  18857. (org-with-limited-levels
  18858. (save-excursion
  18859. (goto-char beg)
  18860. (cond
  18861. ;; Case 1. Started at an heading: de-star headings.
  18862. ((org-at-heading-p)
  18863. (while (< (point) end)
  18864. (when (org-at-heading-p t)
  18865. (looking-at org-outline-regexp) (replace-match "")
  18866. (setq toggled t))
  18867. (forward-line)))
  18868. ;; Case 2. Started at an item: change items into headlines.
  18869. ;; One star will be added by `org-list-to-subtree'.
  18870. ((org-at-item-p)
  18871. (while (< (point) end)
  18872. (when (org-at-item-p)
  18873. ;; Pay attention to cases when region ends before list.
  18874. (let* ((struct (org-list-struct))
  18875. (list-end
  18876. (min (org-list-get-bottom-point struct) (1+ end))))
  18877. (save-restriction
  18878. (narrow-to-region (point) list-end)
  18879. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18880. (setq toggled t))
  18881. (forward-line)))
  18882. ;; Case 3. Started at normal text: make every line an heading,
  18883. ;; skipping headlines and items.
  18884. (t (let* ((stars
  18885. (make-string
  18886. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18887. (add-stars
  18888. (cond (nstars "") ; stars from prefix only
  18889. ((equal stars "") "*") ; before first heading
  18890. (org-odd-levels-only "**") ; inside heading, odd
  18891. (t "*"))) ; inside heading, oddeven
  18892. (rpl (concat stars add-stars " "))
  18893. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18894. (while (< (point) (if (equal nstars '(4)) lend end))
  18895. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18896. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18897. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18898. (forward-line)))))))
  18899. (unless toggled (message "Cannot toggle heading from here"))))
  18900. (defun org-meta-return (&optional arg)
  18901. "Insert a new heading or wrap a region in a table.
  18902. Calls `org-insert-heading', `org-insert-item' or
  18903. `org-table-wrap-region', depending on context. When called with
  18904. an argument, unconditionally call `org-insert-heading'."
  18905. (interactive "P")
  18906. (org-check-before-invisible-edit 'insert)
  18907. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18908. (call-interactively (cond (arg #'org-insert-heading)
  18909. ((org-at-table-p) #'org-table-wrap-region)
  18910. ((org-in-item-p) #'org-insert-item)
  18911. (t #'org-insert-heading)))))
  18912. ;;; Menu entries
  18913. (defsubst org-in-subtree-not-table-p ()
  18914. "Are we in a subtree and not in a table?"
  18915. (and (not (org-before-first-heading-p))
  18916. (not (org-at-table-p))))
  18917. ;; Define the Org mode menus
  18918. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18919. '("Tbl"
  18920. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18921. ["Next Field" org-cycle (org-at-table-p)]
  18922. ["Previous Field" org-shifttab (org-at-table-p)]
  18923. ["Next Row" org-return (org-at-table-p)]
  18924. "--"
  18925. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18926. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18927. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18928. "--"
  18929. ("Column"
  18930. ["Move Column Left" org-metaleft (org-at-table-p)]
  18931. ["Move Column Right" org-metaright (org-at-table-p)]
  18932. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18933. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18934. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18935. ("Row"
  18936. ["Move Row Up" org-metaup (org-at-table-p)]
  18937. ["Move Row Down" org-metadown (org-at-table-p)]
  18938. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18939. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18940. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18941. "--"
  18942. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18943. ("Rectangle"
  18944. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18945. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18946. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18947. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18948. "--"
  18949. ("Calculate"
  18950. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18951. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18952. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18953. "--"
  18954. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18955. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18956. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18957. "--"
  18958. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18959. "--"
  18960. ["Sum Column/Rectangle" org-table-sum
  18961. (or (org-at-table-p) (org-region-active-p))]
  18962. ["Which Column?" org-table-current-column (org-at-table-p)])
  18963. ["Debug Formulas"
  18964. org-table-toggle-formula-debugger
  18965. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18966. ["Show Col/Row Numbers"
  18967. org-table-toggle-coordinate-overlays
  18968. :style toggle
  18969. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18970. "--"
  18971. ["Create" org-table-create (not (org-at-table-p))]
  18972. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18973. ["Import from File" org-table-import (not (org-at-table-p))]
  18974. ["Export to File" org-table-export (org-at-table-p)]
  18975. "--"
  18976. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18977. "--"
  18978. ("Plot"
  18979. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18980. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18981. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18982. '("Org"
  18983. ("Show/Hide"
  18984. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18985. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18986. ["Sparse Tree..." org-sparse-tree t]
  18987. ["Reveal Context" org-reveal t]
  18988. ["Show All" org-show-all t]
  18989. "--"
  18990. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18991. "--"
  18992. ["New Heading" org-insert-heading t]
  18993. ("Navigate Headings"
  18994. ["Up" outline-up-heading t]
  18995. ["Next" outline-next-visible-heading t]
  18996. ["Previous" outline-previous-visible-heading t]
  18997. ["Next Same Level" outline-forward-same-level t]
  18998. ["Previous Same Level" outline-backward-same-level t]
  18999. "--"
  19000. ["Jump" org-goto t])
  19001. ("Edit Structure"
  19002. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19003. "--"
  19004. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19005. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19006. "--"
  19007. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19008. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19009. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19010. "--"
  19011. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19012. "--"
  19013. ["Copy visible text" org-copy-visible t]
  19014. "--"
  19015. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19016. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19017. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19018. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19019. "--"
  19020. ["Sort Region/Children" org-sort t]
  19021. "--"
  19022. ["Convert to odd levels" org-convert-to-odd-levels t]
  19023. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19024. ("Editing"
  19025. ["Emphasis..." org-emphasize t]
  19026. ["Edit Source Example" org-edit-special t]
  19027. "--"
  19028. ["Footnote new/jump" org-footnote-action t]
  19029. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19030. ("Archive"
  19031. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19032. "--"
  19033. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19034. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19035. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19036. )
  19037. "--"
  19038. ("Hyperlinks"
  19039. ["Store Link (Global)" org-store-link t]
  19040. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19041. ["Insert Link" org-insert-link t]
  19042. ["Follow Link" org-open-at-point t]
  19043. "--"
  19044. ["Next link" org-next-link t]
  19045. ["Previous link" org-previous-link t]
  19046. "--"
  19047. ["Descriptive Links"
  19048. org-toggle-link-display
  19049. :style radio
  19050. :selected org-descriptive-links
  19051. ]
  19052. ["Literal Links"
  19053. org-toggle-link-display
  19054. :style radio
  19055. :selected (not org-descriptive-links)])
  19056. "--"
  19057. ("TODO Lists"
  19058. ["TODO/DONE/-" org-todo t]
  19059. ("Select keyword"
  19060. ["Next keyword" org-shiftright (org-at-heading-p)]
  19061. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19062. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19063. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19064. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19065. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19066. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19067. "--"
  19068. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19069. :selected org-enforce-todo-dependencies :style toggle :active t]
  19070. "Settings for tree at point"
  19071. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19072. :selected (org-entry-get nil "ORDERED")
  19073. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19074. ["Do Children parallel" org-toggle-ordered-property :style radio
  19075. :selected (not (org-entry-get nil "ORDERED"))
  19076. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19077. "--"
  19078. ["Set Priority" org-priority t]
  19079. ["Priority Up" org-shiftup t]
  19080. ["Priority Down" org-shiftdown t]
  19081. "--"
  19082. ["Get news from all feeds" org-feed-update-all t]
  19083. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19084. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19085. ("TAGS and Properties"
  19086. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19087. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19088. "--"
  19089. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19090. ["Column view of properties" org-columns t]
  19091. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19092. ("Dates and Scheduling"
  19093. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19094. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19095. ("Change Date"
  19096. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19097. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19098. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19099. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19100. ["Compute Time Range" org-evaluate-time-range t]
  19101. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19102. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19103. "--"
  19104. ["Custom time format" org-toggle-time-stamp-overlays
  19105. :style radio :selected org-display-custom-times]
  19106. "--"
  19107. ["Goto Calendar" org-goto-calendar t]
  19108. ["Date from Calendar" org-date-from-calendar t]
  19109. "--"
  19110. ["Start/Restart Timer" org-timer-start t]
  19111. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19112. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19113. ["Insert Timer String" org-timer t]
  19114. ["Insert Timer Item" org-timer-item t])
  19115. ("Logging work"
  19116. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19117. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19118. ["Clock out" org-clock-out t]
  19119. ["Clock cancel" org-clock-cancel t]
  19120. "--"
  19121. ["Mark as default task" org-clock-mark-default-task t]
  19122. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19123. ["Goto running clock" org-clock-goto t]
  19124. "--"
  19125. ["Display times" org-clock-display t]
  19126. ["Create clock table" org-clock-report t]
  19127. "--"
  19128. ["Record DONE time"
  19129. (progn (setq org-log-done (not org-log-done))
  19130. (message "Switching to %s will %s record a timestamp"
  19131. (car org-done-keywords)
  19132. (if org-log-done "automatically" "not")))
  19133. :style toggle :selected org-log-done])
  19134. "--"
  19135. ["Agenda Command..." org-agenda t]
  19136. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19137. ("File List for Agenda")
  19138. ("Special views current file"
  19139. ["TODO Tree" org-show-todo-tree t]
  19140. ["Check Deadlines" org-check-deadlines t]
  19141. ["Tags/Property tree" org-match-sparse-tree t])
  19142. "--"
  19143. ["Export/Publish..." org-export-dispatch t]
  19144. ("LaTeX"
  19145. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19146. :style toggle :selected org-cdlatex-mode]
  19147. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19148. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19149. ["Modify math symbol" org-cdlatex-math-modify
  19150. (org-inside-LaTeX-fragment-p)]
  19151. ["Insert citation" org-reftex-citation t])
  19152. "--"
  19153. ("MobileOrg"
  19154. ["Push Files and Views" org-mobile-push t]
  19155. ["Get Captured and Flagged" org-mobile-pull t]
  19156. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19157. "--"
  19158. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19159. "--"
  19160. ("Documentation"
  19161. ["Show Version" org-version t]
  19162. ["Info Documentation" org-info t]
  19163. ["Browse Org News" org-browse-news t])
  19164. ("Customize"
  19165. ["Browse Org Group" org-customize t]
  19166. "--"
  19167. ["Expand This Menu" org-create-customize-menu
  19168. (fboundp 'customize-menu-create)])
  19169. ["Send bug report" org-submit-bug-report t]
  19170. "--"
  19171. ("Refresh/Reload"
  19172. ["Refresh setup current buffer" org-mode-restart t]
  19173. ["Reload Org (after update)" org-reload t]
  19174. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  19175. (defun org-info (&optional node)
  19176. "Read documentation for Org in the info system.
  19177. With optional NODE, go directly to that node."
  19178. (interactive)
  19179. (info (format "(org)%s" (or node ""))))
  19180. (defun org-browse-news ()
  19181. "Browse the news for the latest major release."
  19182. (interactive)
  19183. (browse-url "https://orgmode.org/Changes.html"))
  19184. ;;;###autoload
  19185. (defun org-submit-bug-report ()
  19186. "Submit a bug report on Org via mail.
  19187. Don't hesitate to report any problems or inaccurate documentation.
  19188. If you don't have setup sending mail from (X)Emacs, please copy the
  19189. output buffer into your mail program, as it gives us important
  19190. information about your Org version and configuration."
  19191. (interactive)
  19192. (require 'reporter)
  19193. (defvar reporter-prompt-for-summary-p)
  19194. (org-load-modules-maybe)
  19195. (org-require-autoloaded-modules)
  19196. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19197. (reporter-submit-bug-report
  19198. "emacs-orgmode@gnu.org"
  19199. (org-version nil 'full)
  19200. (let (list)
  19201. (save-window-excursion
  19202. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19203. (delete-other-windows)
  19204. (erase-buffer)
  19205. (insert "You are about to submit a bug report to the Org mailing list.
  19206. We would like to add your full Org and Outline configuration to the
  19207. bug report. This greatly simplifies the work of the maintainer and
  19208. other experts on the mailing list.
  19209. HOWEVER, some variables you have customized may contain private
  19210. information. The names of customers, colleagues, or friends, might
  19211. appear in the form of file names, tags, todo states, or search strings.
  19212. If you answer yes to the prompt, you might want to check and remove
  19213. such private information before sending the email.")
  19214. (add-text-properties (point-min) (point-max) '(face org-warning))
  19215. (when (yes-or-no-p "Include your Org configuration ")
  19216. (mapatoms
  19217. (lambda (v)
  19218. (and (boundp v)
  19219. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19220. (or (and (symbol-value v)
  19221. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19222. (and
  19223. (get v 'custom-type) (get v 'standard-value)
  19224. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19225. (push v list)))))
  19226. (kill-buffer (get-buffer "*Warn about privacy*"))
  19227. list))
  19228. nil nil
  19229. "Remember to cover the basics, that is, what you expected to happen and
  19230. what in fact did happen. You don't know how to make a good report? See
  19231. https://orgmode.org/manual/Feedback.html#Feedback
  19232. Your bug report will be posted to the Org mailing list.
  19233. ------------------------------------------------------------------------")
  19234. (save-excursion
  19235. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19236. (replace-match "\\1Bug: \\3 [\\2]")))))
  19237. (defun org-install-agenda-files-menu ()
  19238. (let ((bl (buffer-list)))
  19239. (save-excursion
  19240. (while bl
  19241. (set-buffer (pop bl))
  19242. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19243. (when (derived-mode-p 'org-mode)
  19244. (easy-menu-change
  19245. '("Org") "File List for Agenda"
  19246. (append
  19247. (list
  19248. ["Edit File List" (org-edit-agenda-file-list) t]
  19249. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19250. ["Remove Current File from List" org-remove-file t]
  19251. ["Cycle through agenda files" org-cycle-agenda-files t]
  19252. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19253. "--")
  19254. (mapcar 'org-file-menu-entry
  19255. ;; Prevent initialization from failing.
  19256. (ignore-errors (org-agenda-files t)))))))))
  19257. ;;;; Documentation
  19258. (defun org-require-autoloaded-modules ()
  19259. (interactive)
  19260. (mapc #'require
  19261. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19262. org-table org-timer)))
  19263. ;;;###autoload
  19264. (defun org-reload (&optional uncompiled)
  19265. "Reload all Org Lisp files.
  19266. With prefix arg UNCOMPILED, load the uncompiled versions."
  19267. (interactive "P")
  19268. (require 'loadhist)
  19269. (let* ((org-dir (org-find-library-dir "org"))
  19270. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19271. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19272. (remove-re (format "\\`%s\\'"
  19273. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19274. (feats (delete-dups
  19275. (mapcar 'file-name-sans-extension
  19276. (mapcar 'file-name-nondirectory
  19277. (delq nil
  19278. (mapcar 'feature-file
  19279. features))))))
  19280. (lfeat (append
  19281. (sort
  19282. (setq feats
  19283. (delq nil (mapcar
  19284. (lambda (f)
  19285. (if (and (string-match feature-re f)
  19286. (not (string-match remove-re f)))
  19287. f nil))
  19288. feats)))
  19289. 'string-lessp)
  19290. (list "org-version" "org")))
  19291. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19292. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19293. load-uncore load-misses)
  19294. (setq load-misses
  19295. (delq 't
  19296. (mapcar (lambda (f)
  19297. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19298. (and (string= org-dir contrib-dir)
  19299. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19300. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19301. (add-to-list 'load-uncore f 'append)
  19302. 't)
  19303. f))
  19304. lfeat)))
  19305. (when load-uncore
  19306. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19307. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19308. (if load-misses
  19309. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19310. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19311. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19312. ;;;###autoload
  19313. (defun org-customize ()
  19314. "Call the customize function with org as argument."
  19315. (interactive)
  19316. (org-load-modules-maybe)
  19317. (org-require-autoloaded-modules)
  19318. (customize-browse 'org))
  19319. (defun org-create-customize-menu ()
  19320. "Create a full customization menu for Org mode, insert it into the menu."
  19321. (interactive)
  19322. (org-load-modules-maybe)
  19323. (org-require-autoloaded-modules)
  19324. (if (fboundp 'customize-menu-create)
  19325. (progn
  19326. (easy-menu-change
  19327. '("Org") "Customize"
  19328. `(["Browse Org group" org-customize t]
  19329. "--"
  19330. ,(customize-menu-create 'org)
  19331. ["Set" Custom-set t]
  19332. ["Save" Custom-save t]
  19333. ["Reset to Current" Custom-reset-current t]
  19334. ["Reset to Saved" Custom-reset-saved t]
  19335. ["Reset to Standard Settings" Custom-reset-standard t]))
  19336. (message "\"Org\"-menu now contains full customization menu"))
  19337. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19338. ;;;; Miscellaneous stuff
  19339. ;;; Generally useful functions
  19340. (defun org-link-display-format (s)
  19341. "Replace links in string S with their description.
  19342. If there is no description, use the link target."
  19343. (save-match-data
  19344. (replace-regexp-in-string
  19345. org-bracket-link-analytic-regexp
  19346. (lambda (m)
  19347. (if (match-end 5) (match-string 5 m)
  19348. (concat (match-string 1 m) (match-string 3 m))))
  19349. s nil t)))
  19350. (defun org-toggle-link-display ()
  19351. "Toggle the literal or descriptive display of links."
  19352. (interactive)
  19353. (if org-descriptive-links
  19354. (remove-from-invisibility-spec '(org-link))
  19355. (add-to-invisibility-spec '(org-link)))
  19356. (org-restart-font-lock)
  19357. (setq org-descriptive-links (not org-descriptive-links)))
  19358. (defun org-in-clocktable-p ()
  19359. "Check if the cursor is in a clocktable."
  19360. (let ((pos (point)) start)
  19361. (save-excursion
  19362. (end-of-line 1)
  19363. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19364. (setq start (match-beginning 0))
  19365. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19366. (>= (match-end 0) pos)
  19367. start))))
  19368. (defun org-in-verbatim-emphasis ()
  19369. (save-match-data
  19370. (and (org-in-regexp org-verbatim-re 2)
  19371. (>= (point) (match-beginning 3))
  19372. (<= (point) (match-end 4)))))
  19373. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19374. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19375. (if (and marker (marker-buffer marker)
  19376. (buffer-live-p (marker-buffer marker)))
  19377. (progn
  19378. (pop-to-buffer-same-window (marker-buffer marker))
  19379. (when (or (> marker (point-max)) (< marker (point-min)))
  19380. (widen))
  19381. (goto-char marker)
  19382. (org-show-context 'org-goto))
  19383. (if bookmark
  19384. (bookmark-jump bookmark)
  19385. (error "Cannot find location"))))
  19386. (defun org-quote-csv-field (s)
  19387. "Quote field for inclusion in CSV material."
  19388. (if (string-match "[\",]" s)
  19389. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19390. s))
  19391. (defun org-force-self-insert (N)
  19392. "Needed to enforce self-insert under remapping."
  19393. (interactive "p")
  19394. (self-insert-command N))
  19395. (defun org-fill-template (template alist)
  19396. "Find each %key of ALIST in TEMPLATE and replace it."
  19397. (let ((case-fold-search nil))
  19398. (dolist (entry (sort (copy-sequence alist)
  19399. (lambda (a b) (< (length (car a)) (length (car b))))))
  19400. (setq template
  19401. (replace-regexp-in-string
  19402. (concat "%" (regexp-quote (car entry)))
  19403. (or (cdr entry) "") template t t)))
  19404. template))
  19405. (defun org-quote-vert (s)
  19406. "Replace \"|\" with \"\\vert\"."
  19407. (while (string-match "|" s)
  19408. (setq s (replace-match "\\vert" t t s)))
  19409. s)
  19410. (defun org-uuidgen-p (s)
  19411. "Is S an ID created by UUIDGEN?"
  19412. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19413. (defun org-in-src-block-p (&optional inside)
  19414. "Whether point is in a code source block.
  19415. When INSIDE is non-nil, don't consider we are within a source
  19416. block when point is at #+BEGIN_SRC or #+END_SRC."
  19417. (let ((case-fold-search t))
  19418. (or (and (eq (get-char-property (point) 'src-block) t))
  19419. (and (not inside)
  19420. (save-match-data
  19421. (save-excursion
  19422. (beginning-of-line)
  19423. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19424. (defun org-context ()
  19425. "Return a list of contexts of the current cursor position.
  19426. If several contexts apply, all are returned.
  19427. Each context entry is a list with a symbol naming the context, and
  19428. two positions indicating start and end of the context. Possible
  19429. contexts are:
  19430. :headline anywhere in a headline
  19431. :headline-stars on the leading stars in a headline
  19432. :todo-keyword on a TODO keyword (including DONE) in a headline
  19433. :tags on the TAGS in a headline
  19434. :priority on the priority cookie in a headline
  19435. :item on the first line of a plain list item
  19436. :item-bullet on the bullet/number of a plain list item
  19437. :checkbox on the checkbox in a plain list item
  19438. :table in an Org table
  19439. :table-special on a special filed in a table
  19440. :table-table in a table.el table
  19441. :clocktable in a clocktable
  19442. :src-block in a source block
  19443. :link on a hyperlink
  19444. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19445. :target on a <<target>>
  19446. :radio-target on a <<<radio-target>>>
  19447. :latex-fragment on a LaTeX fragment
  19448. :latex-preview on a LaTeX fragment with overlaid preview image
  19449. This function expects the position to be visible because it uses font-lock
  19450. faces as a help to recognize the following contexts: :table-special, :link,
  19451. and :keyword."
  19452. (let* ((f (get-text-property (point) 'face))
  19453. (faces (if (listp f) f (list f)))
  19454. (case-fold-search t)
  19455. (p (point)) clist o)
  19456. ;; First the large context
  19457. (cond
  19458. ((org-at-heading-p t)
  19459. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19460. (when (progn
  19461. (beginning-of-line 1)
  19462. (looking-at org-todo-line-tags-regexp))
  19463. (push (org-point-in-group p 1 :headline-stars) clist)
  19464. (push (org-point-in-group p 2 :todo-keyword) clist)
  19465. (push (org-point-in-group p 4 :tags) clist))
  19466. (goto-char p)
  19467. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19468. (when (looking-at "\\[#[A-Z0-9]\\]")
  19469. (push (org-point-in-group p 0 :priority) clist)))
  19470. ((org-at-item-p)
  19471. (push (org-point-in-group p 2 :item-bullet) clist)
  19472. (push (list :item (point-at-bol)
  19473. (save-excursion (org-end-of-item) (point)))
  19474. clist)
  19475. (and (org-at-item-checkbox-p)
  19476. (push (org-point-in-group p 0 :checkbox) clist)))
  19477. ((org-at-table-p)
  19478. (push (list :table (org-table-begin) (org-table-end)) clist)
  19479. (when (memq 'org-formula faces)
  19480. (push (list :table-special
  19481. (previous-single-property-change p 'face)
  19482. (next-single-property-change p 'face)) clist)))
  19483. ((org-at-table-p 'any)
  19484. (push (list :table-table) clist)))
  19485. (goto-char p)
  19486. (let ((case-fold-search t))
  19487. ;; New the "medium" contexts: clocktables, source blocks
  19488. (cond ((org-in-clocktable-p)
  19489. (push (list :clocktable
  19490. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19491. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19492. (match-beginning 1))
  19493. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19494. (match-end 0))) clist))
  19495. ((org-in-src-block-p)
  19496. (push (list :src-block
  19497. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19498. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19499. (match-beginning 1))
  19500. (and (search-forward "#+END_SRC" nil t)
  19501. (match-beginning 0))) clist))))
  19502. (goto-char p)
  19503. ;; Now the small context
  19504. (cond
  19505. ((org-at-timestamp-p)
  19506. (push (org-point-in-group p 0 :timestamp) clist))
  19507. ((memq 'org-link faces)
  19508. (push (list :link
  19509. (previous-single-property-change p 'face)
  19510. (next-single-property-change p 'face)) clist))
  19511. ((memq 'org-special-keyword faces)
  19512. (push (list :keyword
  19513. (previous-single-property-change p 'face)
  19514. (next-single-property-change p 'face)) clist))
  19515. ((org-at-target-p)
  19516. (push (org-point-in-group p 0 :target) clist)
  19517. (goto-char (1- (match-beginning 0)))
  19518. (when (looking-at org-radio-target-regexp)
  19519. (push (org-point-in-group p 0 :radio-target) clist))
  19520. (goto-char p))
  19521. ((setq o (cl-some
  19522. (lambda (o)
  19523. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19524. o))
  19525. (overlays-at (point))))
  19526. (push (list :latex-fragment
  19527. (overlay-start o) (overlay-end o)) clist)
  19528. (push (list :latex-preview
  19529. (overlay-start o) (overlay-end o)) clist))
  19530. ((org-inside-LaTeX-fragment-p)
  19531. ;; FIXME: positions wrong.
  19532. (push (list :latex-fragment (point) (point)) clist)))
  19533. (setq clist (nreverse (delq nil clist)))
  19534. clist))
  19535. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19536. "Non-nil when point is between matches of START-RE and END-RE.
  19537. Also return a non-nil value when point is on one of the matches.
  19538. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19539. buffer positions. Default values are the positions of headlines
  19540. surrounding the point.
  19541. The functions returns a cons cell whose car (resp. cdr) is the
  19542. position before START-RE (resp. after END-RE)."
  19543. (save-match-data
  19544. (let ((pos (point))
  19545. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19546. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19547. beg end)
  19548. (save-excursion
  19549. ;; Point is on a block when on START-RE or if START-RE can be
  19550. ;; found before it...
  19551. (and (or (org-in-regexp start-re)
  19552. (re-search-backward start-re limit-up t))
  19553. (setq beg (match-beginning 0))
  19554. ;; ... and END-RE after it...
  19555. (goto-char (match-end 0))
  19556. (re-search-forward end-re limit-down t)
  19557. (> (setq end (match-end 0)) pos)
  19558. ;; ... without another START-RE in-between.
  19559. (goto-char (match-beginning 0))
  19560. (not (re-search-backward start-re (1+ beg) t))
  19561. ;; Return value.
  19562. (cons beg end))))))
  19563. (defun org-in-block-p (names)
  19564. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19565. NAMES is a list of strings containing names of blocks.
  19566. Return first block name matched, or nil. Beware that in case of
  19567. nested blocks, the returned name may not belong to the closest
  19568. block from point."
  19569. (save-match-data
  19570. (catch 'exit
  19571. (let ((case-fold-search t)
  19572. (lim-up (save-excursion (outline-previous-heading)))
  19573. (lim-down (save-excursion (outline-next-heading))))
  19574. (dolist (name names)
  19575. (let ((n (regexp-quote name)))
  19576. (when (org-between-regexps-p
  19577. (concat "^[ \t]*#\\+begin_" n)
  19578. (concat "^[ \t]*#\\+end_" n)
  19579. lim-up lim-down)
  19580. (throw 'exit n)))))
  19581. nil)))
  19582. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19583. "Call `multi-occur' with buffers for all agenda files."
  19584. (interactive "sOrg-files matching: ")
  19585. (let* ((files (org-agenda-files))
  19586. (tnames (mapcar #'file-truename files))
  19587. (extra org-agenda-text-search-extra-files))
  19588. (when (eq (car extra) 'agenda-archives)
  19589. (setq extra (cdr extra))
  19590. (setq files (org-add-archive-files files)))
  19591. (dolist (f extra)
  19592. (unless (member (file-truename f) tnames)
  19593. (unless (member f files) (setq files (append files (list f))))
  19594. (setq tnames (append tnames (list (file-truename f))))))
  19595. (multi-occur
  19596. (mapcar (lambda (x)
  19597. (with-current-buffer
  19598. ;; FIXME: Why not just (find-file-noselect x)?
  19599. ;; Is it to avoid the "revert buffer" prompt?
  19600. (or (get-file-buffer x) (find-file-noselect x))
  19601. (widen)
  19602. (current-buffer)))
  19603. files)
  19604. regexp)))
  19605. (add-hook 'occur-mode-find-occurrence-hook
  19606. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19607. (defun org-occur-link-in-agenda-files ()
  19608. "Create a link and search for it in the agendas.
  19609. The link is not stored in `org-stored-links', it is just created
  19610. for the search purpose."
  19611. (interactive)
  19612. (let ((link (condition-case nil
  19613. (org-store-link nil)
  19614. (error "Unable to create a link to here"))))
  19615. (org-occur-in-agenda-files (regexp-quote link))))
  19616. (defun org-back-over-empty-lines ()
  19617. "Move backwards over whitespace, to the beginning of the first empty line.
  19618. Returns the number of empty lines passed."
  19619. (let ((pos (point)))
  19620. (if (cdr (assq 'heading org-blank-before-new-entry))
  19621. (skip-chars-backward " \t\n\r")
  19622. (unless (eobp)
  19623. (forward-line -1)))
  19624. (beginning-of-line 2)
  19625. (goto-char (min (point) pos))
  19626. (count-lines (point) pos)))
  19627. (defun org-replace-escapes (string table)
  19628. "Replace %-escapes in STRING with values in TABLE.
  19629. TABLE is an association list with keys like \"%a\" and string values.
  19630. The sequences in STRING may contain normal field width and padding information,
  19631. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19632. so values can contain further %-escapes if they are define later in TABLE."
  19633. (let ((tbl (copy-alist table))
  19634. (case-fold-search nil)
  19635. (pchg 0)
  19636. re rpl)
  19637. (dolist (e tbl)
  19638. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19639. (when (and (cdr e) (string-match re (cdr e)))
  19640. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19641. (safe "SREF"))
  19642. (add-text-properties 0 3 (list 'sref sref) safe)
  19643. (setcdr e (replace-match safe t t (cdr e)))))
  19644. (while (string-match re string)
  19645. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19646. (cdr e)))
  19647. (setq string (replace-match rpl t t string))))
  19648. (while (setq pchg (next-property-change pchg string))
  19649. (let ((sref (get-text-property pchg 'sref string)))
  19650. (when (and sref (string-match "SREF" string pchg))
  19651. (setq string (replace-match sref t t string)))))
  19652. string))
  19653. ;;; TODO: Only called once, from ox-odt which should probably use
  19654. ;;; org-export-inline-image-p or something.
  19655. (defun org-file-image-p (file)
  19656. "Return non-nil if FILE is an image."
  19657. (save-match-data
  19658. (string-match (image-file-name-regexp) file)))
  19659. (defun org-get-cursor-date (&optional with-time)
  19660. "Return the date at cursor in as a time.
  19661. This works in the calendar and in the agenda, anywhere else it just
  19662. returns the current time.
  19663. If WITH-TIME is non-nil, returns the time of the event at point (in
  19664. the agenda) or the current time of the day."
  19665. (let (date day defd tp hod mod)
  19666. (when with-time
  19667. (setq tp (get-text-property (point) 'time))
  19668. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19669. (setq hod (string-to-number (match-string 1 tp))
  19670. mod (string-to-number (match-string 2 tp))))
  19671. (or tp (let ((now (decode-time)))
  19672. (setq hod (nth 2 now)
  19673. mod (nth 1 now)))))
  19674. (cond
  19675. ((eq major-mode 'calendar-mode)
  19676. (setq date (calendar-cursor-to-date)
  19677. defd (encode-time 0 (or mod 0) (or hod 0)
  19678. (nth 1 date) (nth 0 date) (nth 2 date))))
  19679. ((eq major-mode 'org-agenda-mode)
  19680. (setq day (get-text-property (point) 'day))
  19681. (when day
  19682. (setq date (calendar-gregorian-from-absolute day)
  19683. defd (encode-time 0 (or mod 0) (or hod 0)
  19684. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19685. (or defd (current-time))))
  19686. (defun org-mark-subtree (&optional up)
  19687. "Mark the current subtree.
  19688. This puts point at the start of the current subtree, and mark at
  19689. the end. If a numeric prefix UP is given, move up into the
  19690. hierarchy of headlines by UP levels before marking the subtree."
  19691. (interactive "P")
  19692. (org-with-limited-levels
  19693. (cond ((org-at-heading-p) (beginning-of-line))
  19694. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19695. (t (outline-previous-visible-heading 1))))
  19696. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19697. (if (called-interactively-p 'any)
  19698. (call-interactively 'org-mark-element)
  19699. (org-mark-element)))
  19700. ;;; Indentation
  19701. (defvar org-element-greater-elements)
  19702. (defun org--get-expected-indentation (element contentsp)
  19703. "Expected indentation column for current line, according to ELEMENT.
  19704. ELEMENT is an element containing point. CONTENTSP is non-nil
  19705. when indentation is to be computed according to contents of
  19706. ELEMENT."
  19707. (let ((type (org-element-type element))
  19708. (start (org-element-property :begin element))
  19709. (post-affiliated (org-element-property :post-affiliated element)))
  19710. (org-with-wide-buffer
  19711. (cond
  19712. (contentsp
  19713. (cl-case type
  19714. ((diary-sexp footnote-definition) 0)
  19715. ((headline inlinetask nil)
  19716. (if (not org-adapt-indentation) 0
  19717. (let ((level (org-current-level)))
  19718. (if level (1+ level) 0))))
  19719. ((item plain-list) (org-list-item-body-column post-affiliated))
  19720. (t
  19721. (goto-char start)
  19722. (current-indentation))))
  19723. ((memq type '(headline inlinetask nil))
  19724. (if (org-match-line "[ \t]*$")
  19725. (org--get-expected-indentation element t)
  19726. 0))
  19727. ((memq type '(diary-sexp footnote-definition)) 0)
  19728. ;; First paragraph of a footnote definition or an item.
  19729. ;; Indent like parent.
  19730. ((< (line-beginning-position) start)
  19731. (org--get-expected-indentation
  19732. (org-element-property :parent element) t))
  19733. ;; At first line: indent according to previous sibling, if any,
  19734. ;; ignoring footnote definitions and inline tasks, or parent's
  19735. ;; contents.
  19736. ((= (line-beginning-position) start)
  19737. (catch 'exit
  19738. (while t
  19739. (if (= (point-min) start) (throw 'exit 0)
  19740. (goto-char (1- start))
  19741. (let* ((previous (org-element-at-point))
  19742. (parent previous))
  19743. (while (and parent (<= (org-element-property :end parent) start))
  19744. (setq previous parent
  19745. parent (org-element-property :parent parent)))
  19746. (cond
  19747. ((not previous) (throw 'exit 0))
  19748. ((> (org-element-property :end previous) start)
  19749. (throw 'exit (org--get-expected-indentation previous t)))
  19750. ((memq (org-element-type previous)
  19751. '(footnote-definition inlinetask))
  19752. (setq start (org-element-property :begin previous)))
  19753. (t (goto-char (org-element-property :begin previous))
  19754. (throw 'exit
  19755. (if (bolp) (current-indentation)
  19756. ;; At first paragraph in an item or
  19757. ;; a footnote definition.
  19758. (org--get-expected-indentation
  19759. (org-element-property :parent previous) t))))))))))
  19760. ;; Otherwise, move to the first non-blank line above.
  19761. (t
  19762. (beginning-of-line)
  19763. (let ((pos (point)))
  19764. (skip-chars-backward " \r\t\n")
  19765. (cond
  19766. ;; Two blank lines end a footnote definition or a plain
  19767. ;; list. When we indent an empty line after them, the
  19768. ;; containing list or footnote definition is over, so it
  19769. ;; qualifies as a previous sibling. Therefore, we indent
  19770. ;; like its first line.
  19771. ((and (memq type '(footnote-definition plain-list))
  19772. (> (count-lines (point) pos) 2))
  19773. (goto-char start)
  19774. (current-indentation))
  19775. ;; Line above is the first one of a paragraph at the
  19776. ;; beginning of an item or a footnote definition. Indent
  19777. ;; like parent.
  19778. ((< (line-beginning-position) start)
  19779. (org--get-expected-indentation
  19780. (org-element-property :parent element) t))
  19781. ;; Line above is the beginning of an element, i.e., point
  19782. ;; was originally on the blank lines between element's start
  19783. ;; and contents.
  19784. ((= (line-beginning-position) post-affiliated)
  19785. (org--get-expected-indentation element t))
  19786. ;; POS is after contents in a greater element. Indent like
  19787. ;; the beginning of the element.
  19788. ((and (memq type org-element-greater-elements)
  19789. (let ((cend (org-element-property :contents-end element)))
  19790. (and cend (<= cend pos))))
  19791. ;; As a special case, if point is at the end of a footnote
  19792. ;; definition or an item, indent like the very last element
  19793. ;; within. If that last element is an item, indent like
  19794. ;; its contents.
  19795. (if (memq type '(footnote-definition item plain-list))
  19796. (let ((last (org-element-at-point)))
  19797. (goto-char pos)
  19798. (org--get-expected-indentation
  19799. last (eq (org-element-type last) 'item)))
  19800. (goto-char start)
  19801. (current-indentation)))
  19802. ;; In any other case, indent like the current line.
  19803. (t (current-indentation)))))))))
  19804. (defun org--align-node-property ()
  19805. "Align node property at point.
  19806. Alignment is done according to `org-property-format', which see."
  19807. (when (save-excursion
  19808. (beginning-of-line)
  19809. (looking-at org-property-re))
  19810. (replace-match
  19811. (concat (match-string 4)
  19812. (org-trim
  19813. (format org-property-format (match-string 1) (match-string 3))))
  19814. t t)))
  19815. (defun org-indent-line ()
  19816. "Indent line depending on context.
  19817. Indentation is done according to the following rules:
  19818. - Footnote definitions, diary sexps, headlines and inline tasks
  19819. have to start at column 0.
  19820. - On the very first line of an element, consider, in order, the
  19821. next rules until one matches:
  19822. 1. If there's a sibling element before, ignoring footnote
  19823. definitions and inline tasks, indent like its first line.
  19824. 2. If element has a parent, indent like its contents. More
  19825. precisely, if parent is an item, indent after the
  19826. description part, if any, or the bullet (see
  19827. `org-list-description-max-indent'). Else, indent like
  19828. parent's first line.
  19829. 3. Otherwise, indent relatively to current level, if
  19830. `org-adapt-indentation' is non-nil, or to left margin.
  19831. - On a blank line at the end of an element, indent according to
  19832. the type of the element. More precisely
  19833. 1. If element is a plain list, an item, or a footnote
  19834. definition, indent like the very last element within.
  19835. 2. If element is a paragraph, indent like its last non blank
  19836. line.
  19837. 3. Otherwise, indent like its very first line.
  19838. - In the code part of a source block, use language major mode
  19839. to indent current line if `org-src-tab-acts-natively' is
  19840. non-nil. If it is nil, do nothing.
  19841. - Otherwise, indent like the first non-blank line above.
  19842. The function doesn't indent an item as it could break the whole
  19843. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19844. `\\[org-shiftmetaright]'.
  19845. Also align node properties according to `org-property-format'."
  19846. (interactive)
  19847. (cond
  19848. ((org-at-heading-p) 'noindent)
  19849. (t
  19850. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19851. (type (org-element-type element)))
  19852. (cond ((and (memq type '(plain-list item))
  19853. (= (line-beginning-position)
  19854. (org-element-property :post-affiliated element)))
  19855. 'noindent)
  19856. ((and (eq type 'latex-environment)
  19857. (>= (point) (org-element-property :post-affiliated element))
  19858. (< (point) (org-with-wide-buffer
  19859. (goto-char (org-element-property :end element))
  19860. (skip-chars-backward " \r\t\n")
  19861. (line-beginning-position 2))))
  19862. 'noindent)
  19863. ((and (eq type 'src-block)
  19864. org-src-tab-acts-natively
  19865. (> (line-beginning-position)
  19866. (org-element-property :post-affiliated element))
  19867. (< (line-beginning-position)
  19868. (org-with-wide-buffer
  19869. (goto-char (org-element-property :end element))
  19870. (skip-chars-backward " \r\t\n")
  19871. (line-beginning-position))))
  19872. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19873. (t
  19874. (let ((column (org--get-expected-indentation element nil)))
  19875. ;; Preserve current column.
  19876. (if (<= (current-column) (current-indentation))
  19877. (indent-line-to column)
  19878. (save-excursion (indent-line-to column))))
  19879. ;; Align node property. Also preserve current column.
  19880. (when (eq type 'node-property)
  19881. (let ((column (current-column)))
  19882. (org--align-node-property)
  19883. (org-move-to-column column)))))))))
  19884. (defun org-indent-region (start end)
  19885. "Indent each non-blank line in the region.
  19886. Called from a program, START and END specify the region to
  19887. indent. The function will not indent contents of example blocks,
  19888. verse blocks and export blocks as leading white spaces are
  19889. assumed to be significant there."
  19890. (interactive "r")
  19891. (save-excursion
  19892. (goto-char start)
  19893. (skip-chars-forward " \r\t\n")
  19894. (unless (eobp) (beginning-of-line))
  19895. (let ((indent-to
  19896. (lambda (ind pos)
  19897. ;; Set IND as indentation for all lines between point and
  19898. ;; POS. Blank lines are ignored. Leave point after POS
  19899. ;; once done.
  19900. (let ((limit (copy-marker pos)))
  19901. (while (< (point) limit)
  19902. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19903. (forward-line))
  19904. (set-marker limit nil))))
  19905. (end (copy-marker end)))
  19906. (while (< (point) end)
  19907. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19908. (let* ((element (org-element-at-point))
  19909. (type (org-element-type element))
  19910. (element-end (copy-marker (org-element-property :end element)))
  19911. (ind (org--get-expected-indentation element nil)))
  19912. (cond
  19913. ;; Element indented as a single block. Example blocks
  19914. ;; preserving indentation are a special case since the
  19915. ;; "contents" must not be indented whereas the block
  19916. ;; boundaries can.
  19917. ((or (memq type '(export-block latex-environment))
  19918. (and (eq type 'example-block)
  19919. (not
  19920. (or org-src-preserve-indentation
  19921. (org-element-property :preserve-indent element)))))
  19922. (let ((offset (- ind (current-indentation))))
  19923. (unless (zerop offset)
  19924. (indent-rigidly (org-element-property :begin element)
  19925. (org-element-property :end element)
  19926. offset)))
  19927. (goto-char element-end))
  19928. ;; Elements indented line wise. Be sure to exclude
  19929. ;; example blocks (preserving indentation) and source
  19930. ;; blocks from this category as they are treated
  19931. ;; specially later.
  19932. ((or (memq type '(paragraph table table-row))
  19933. (not (or (org-element-property :contents-begin element)
  19934. (memq type '(example-block src-block)))))
  19935. (when (eq type 'node-property)
  19936. (org--align-node-property)
  19937. (beginning-of-line))
  19938. (funcall indent-to ind (min element-end end)))
  19939. ;; Elements consisting of three parts: before the
  19940. ;; contents, the contents, and after the contents. The
  19941. ;; contents are treated specially, according to the
  19942. ;; element type, or not indented at all. Other parts are
  19943. ;; indented as a single block.
  19944. (t
  19945. (let* ((post (copy-marker
  19946. (org-element-property :post-affiliated element)))
  19947. (cbeg
  19948. (copy-marker
  19949. (cond
  19950. ((not (org-element-property :contents-begin element))
  19951. ;; Fake contents for source blocks.
  19952. (org-with-wide-buffer
  19953. (goto-char post)
  19954. (line-beginning-position 2)))
  19955. ((memq type '(footnote-definition item plain-list))
  19956. ;; Contents in these elements could start on
  19957. ;; the same line as the beginning of the
  19958. ;; element. Make sure we start indenting
  19959. ;; from the second line.
  19960. (org-with-wide-buffer
  19961. (goto-char post)
  19962. (end-of-line)
  19963. (skip-chars-forward " \r\t\n")
  19964. (if (eobp) (point) (line-beginning-position))))
  19965. (t (org-element-property :contents-begin element)))))
  19966. (cend (copy-marker
  19967. (or (org-element-property :contents-end element)
  19968. ;; Fake contents for source blocks.
  19969. (org-with-wide-buffer
  19970. (goto-char element-end)
  19971. (skip-chars-backward " \r\t\n")
  19972. (line-beginning-position)))
  19973. t)))
  19974. ;; Do not change items indentation individually as it
  19975. ;; might break the list as a whole. On the other
  19976. ;; hand, when at a plain list, indent it as a whole.
  19977. (cond ((eq type 'plain-list)
  19978. (let ((offset (- ind (current-indentation))))
  19979. (unless (zerop offset)
  19980. (indent-rigidly (org-element-property :begin element)
  19981. (org-element-property :end element)
  19982. offset))
  19983. (goto-char cbeg)))
  19984. ((eq type 'item) (goto-char cbeg))
  19985. (t (funcall indent-to ind (min cbeg end))))
  19986. (when (< (point) end)
  19987. (cl-case type
  19988. ((example-block verse-block))
  19989. (src-block
  19990. ;; In a source block, indent source code
  19991. ;; according to language major mode, but only if
  19992. ;; `org-src-tab-acts-natively' is non-nil.
  19993. (when (and (< (point) end) org-src-tab-acts-natively)
  19994. (ignore-errors
  19995. (org-babel-do-in-edit-buffer
  19996. (indent-region (point-min) (point-max))))))
  19997. (t (org-indent-region (point) (min cend end))))
  19998. (goto-char (min cend end))
  19999. (when (< (point) end)
  20000. (funcall indent-to ind (min element-end end))))
  20001. (set-marker post nil)
  20002. (set-marker cbeg nil)
  20003. (set-marker cend nil))))
  20004. (set-marker element-end nil))))
  20005. (set-marker end nil))))
  20006. (defun org-indent-drawer ()
  20007. "Indent the drawer at point."
  20008. (interactive)
  20009. (unless (save-excursion
  20010. (beginning-of-line)
  20011. (looking-at-p org-drawer-regexp))
  20012. (user-error "Not at a drawer"))
  20013. (let ((element (org-element-at-point)))
  20014. (unless (memq (org-element-type element) '(drawer property-drawer))
  20015. (user-error "Not at a drawer"))
  20016. (org-with-wide-buffer
  20017. (org-indent-region (org-element-property :begin element)
  20018. (org-element-property :end element))))
  20019. (message "Drawer at point indented"))
  20020. (defun org-indent-block ()
  20021. "Indent the block at point."
  20022. (interactive)
  20023. (unless (save-excursion
  20024. (beginning-of-line)
  20025. (let ((case-fold-search t))
  20026. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20027. (user-error "Not at a block"))
  20028. (let ((element (org-element-at-point)))
  20029. (unless (memq (org-element-type element)
  20030. '(comment-block center-block dynamic-block example-block
  20031. export-block quote-block special-block
  20032. src-block verse-block))
  20033. (user-error "Not at a block"))
  20034. (org-with-wide-buffer
  20035. (org-indent-region (org-element-property :begin element)
  20036. (org-element-property :end element))))
  20037. (message "Block at point indented"))
  20038. ;;; Filling
  20039. ;; We use our own fill-paragraph and auto-fill functions.
  20040. ;; `org-fill-paragraph' relies on adaptive filling and context
  20041. ;; checking. Appropriate `fill-prefix' is computed with
  20042. ;; `org-adaptive-fill-function'.
  20043. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20044. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20045. ;; `org-adaptive-fill-function' value. Internally,
  20046. ;; `org-comment-line-break-function' breaks the line.
  20047. ;; `org-setup-filling' installs filling and auto-filling related
  20048. ;; variables during `org-mode' initialization.
  20049. (defun org-setup-filling ()
  20050. (require 'org-element)
  20051. ;; Prevent auto-fill from inserting unwanted new items.
  20052. (when (boundp 'fill-nobreak-predicate)
  20053. (setq-local
  20054. fill-nobreak-predicate
  20055. (org-uniquify
  20056. (append fill-nobreak-predicate
  20057. '(org-fill-line-break-nobreak-p
  20058. org-fill-n-macro-as-item-nobreak-p
  20059. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20060. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20061. (setq-local paragraph-start paragraph-ending)
  20062. (setq-local paragraph-separate paragraph-ending))
  20063. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20064. (setq-local auto-fill-inhibit-regexp nil)
  20065. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20066. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20067. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20068. (defun org-fill-line-break-nobreak-p ()
  20069. "Non-nil when a new line at point would create an Org line break."
  20070. (save-excursion
  20071. (skip-chars-backward "[ \t]")
  20072. (skip-chars-backward "\\\\")
  20073. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20074. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20075. "Non-nil when a new line at point would split a timestamp."
  20076. (and (org-at-timestamp-p 'lax)
  20077. (not (looking-at org-ts-regexp-both))))
  20078. (defun org-fill-n-macro-as-item-nobreak-p ()
  20079. "Non-nil when a new line at point would create a new list."
  20080. ;; During export, a "n" macro followed by a dot or a closing
  20081. ;; parenthesis can end up being parsed as a new list item.
  20082. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20083. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20084. (defun org-adaptive-fill-function ()
  20085. "Compute a fill prefix for the current line.
  20086. Return fill prefix, as a string, or nil if current line isn't
  20087. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20088. matches in paragraphs or comments, use it."
  20089. (org-with-wide-buffer
  20090. (unless (org-at-heading-p)
  20091. (let* ((p (line-beginning-position))
  20092. (element (save-excursion
  20093. (beginning-of-line)
  20094. (org-element-at-point)))
  20095. (type (org-element-type element))
  20096. (post-affiliated (org-element-property :post-affiliated element)))
  20097. (unless (< p post-affiliated)
  20098. (cl-case type
  20099. (comment
  20100. (save-excursion
  20101. (beginning-of-line)
  20102. (looking-at "[ \t]*")
  20103. (concat (match-string 0) "# ")))
  20104. (footnote-definition "")
  20105. ((item plain-list)
  20106. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20107. (paragraph
  20108. ;; Fill prefix is usually the same as the current line,
  20109. ;; unless the paragraph is at the beginning of an item.
  20110. (let ((parent (org-element-property :parent element)))
  20111. (save-excursion
  20112. (beginning-of-line)
  20113. (cond ((eq (org-element-type parent) 'item)
  20114. (make-string (org-list-item-body-column
  20115. (org-element-property :begin parent))
  20116. ?\s))
  20117. ((and adaptive-fill-regexp
  20118. ;; Locally disable
  20119. ;; `adaptive-fill-function' to let
  20120. ;; `fill-context-prefix' handle
  20121. ;; `adaptive-fill-regexp' variable.
  20122. (let (adaptive-fill-function)
  20123. (fill-context-prefix
  20124. post-affiliated
  20125. (org-element-property :end element)))))
  20126. ((looking-at "[ \t]+") (match-string 0))
  20127. (t "")))))
  20128. (comment-block
  20129. ;; Only fill contents if P is within block boundaries.
  20130. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20131. (forward-line)
  20132. (point)))
  20133. (cend (save-excursion
  20134. (goto-char (org-element-property :end element))
  20135. (skip-chars-backward " \r\t\n")
  20136. (line-beginning-position))))
  20137. (when (and (>= p cbeg) (< p cend))
  20138. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20139. (match-string 0)
  20140. ""))))))))))
  20141. (defun org-fill-element (&optional justify)
  20142. "Fill element at point, when applicable.
  20143. This function only applies to comment blocks, comments, example
  20144. blocks and paragraphs. Also, as a special case, re-align table
  20145. when point is at one.
  20146. If JUSTIFY is non-nil (interactively, with prefix argument),
  20147. justify as well. If `sentence-end-double-space' is non-nil, then
  20148. period followed by one space does not end a sentence, so don't
  20149. break a line there. The variable `fill-column' controls the
  20150. width for filling.
  20151. For convenience, when point is at a plain list, an item or
  20152. a footnote definition, try to fill the first paragraph within."
  20153. (with-syntax-table org-mode-transpose-word-syntax-table
  20154. ;; Move to end of line in order to get the first paragraph within
  20155. ;; a plain list or a footnote definition.
  20156. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20157. ;; First check if point is in a blank line at the beginning of
  20158. ;; the buffer. In that case, ignore filling.
  20159. (cl-case (org-element-type element)
  20160. ;; Use major mode filling function is source blocks.
  20161. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20162. ;; Align Org tables, leave table.el tables as-is.
  20163. (table-row (org-table-align) t)
  20164. (table
  20165. (when (eq (org-element-property :type element) 'org)
  20166. (save-excursion
  20167. (goto-char (org-element-property :post-affiliated element))
  20168. (org-table-align)))
  20169. t)
  20170. (paragraph
  20171. ;; Paragraphs may contain `line-break' type objects.
  20172. (let ((beg (max (point-min)
  20173. (org-element-property :contents-begin element)))
  20174. (end (min (point-max)
  20175. (org-element-property :contents-end element))))
  20176. ;; Do nothing if point is at an affiliated keyword.
  20177. (if (< (line-end-position) beg) t
  20178. ;; Fill paragraph, taking line breaks into account.
  20179. (save-excursion
  20180. (goto-char beg)
  20181. (let ((cuts (list beg)))
  20182. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20183. (when (eq 'line-break
  20184. (org-element-type
  20185. (save-excursion (backward-char)
  20186. (org-element-context))))
  20187. (push (point) cuts)))
  20188. (dolist (c (delq end cuts))
  20189. (fill-region-as-paragraph c end justify)
  20190. (setq end c))))
  20191. t)))
  20192. ;; Contents of `comment-block' type elements should be
  20193. ;; filled as plain text, but only if point is within block
  20194. ;; markers.
  20195. (comment-block
  20196. (let* ((case-fold-search t)
  20197. (beg (save-excursion
  20198. (goto-char (org-element-property :begin element))
  20199. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20200. (forward-line)
  20201. (point)))
  20202. (end (save-excursion
  20203. (goto-char (org-element-property :end element))
  20204. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20205. (line-beginning-position))))
  20206. (if (or (< (point) beg) (> (point) end)) t
  20207. (fill-region-as-paragraph
  20208. (save-excursion (end-of-line)
  20209. (re-search-backward "^[ \t]*$" beg 'move)
  20210. (line-beginning-position))
  20211. (save-excursion (beginning-of-line)
  20212. (re-search-forward "^[ \t]*$" end 'move)
  20213. (line-beginning-position))
  20214. justify))))
  20215. ;; Fill comments.
  20216. (comment
  20217. (let ((begin (org-element-property :post-affiliated element))
  20218. (end (org-element-property :end element)))
  20219. (when (and (>= (point) begin) (<= (point) end))
  20220. (let ((begin (save-excursion
  20221. (end-of-line)
  20222. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20223. (progn (forward-line) (point))
  20224. begin)))
  20225. (end (save-excursion
  20226. (end-of-line)
  20227. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20228. (1- (line-beginning-position))
  20229. (skip-chars-backward " \r\t\n")
  20230. (line-end-position)))))
  20231. ;; Do not fill comments when at a blank line.
  20232. (when (> end begin)
  20233. (let ((fill-prefix
  20234. (save-excursion
  20235. (beginning-of-line)
  20236. (looking-at "[ \t]*#")
  20237. (let ((comment-prefix (match-string 0)))
  20238. (goto-char (match-end 0))
  20239. (if (looking-at adaptive-fill-regexp)
  20240. (concat comment-prefix (match-string 0))
  20241. (concat comment-prefix " "))))))
  20242. (save-excursion
  20243. (fill-region-as-paragraph begin end justify))))))
  20244. t))
  20245. ;; Ignore every other element.
  20246. (otherwise t)))))
  20247. (defun org-fill-paragraph (&optional justify region)
  20248. "Fill element at point, when applicable.
  20249. This function only applies to comment blocks, comments, example
  20250. blocks and paragraphs. Also, as a special case, re-align table
  20251. when point is at one.
  20252. For convenience, when point is at a plain list, an item or
  20253. a footnote definition, try to fill the first paragraph within.
  20254. If JUSTIFY is non-nil (interactively, with prefix argument),
  20255. justify as well. If `sentence-end-double-space' is non-nil, then
  20256. period followed by one space does not end a sentence, so don't
  20257. break a line there. The variable `fill-column' controls the
  20258. width for filling.
  20259. The REGION argument is non-nil if called interactively; in that
  20260. case, if Transient Mark mode is enabled and the mark is active,
  20261. fill each of the elements in the active region, instead of just
  20262. filling the current element."
  20263. (interactive (progn
  20264. (barf-if-buffer-read-only)
  20265. (list (when current-prefix-arg 'full) t)))
  20266. (cond
  20267. ((and region transient-mark-mode mark-active
  20268. (not (eq (region-beginning) (region-end))))
  20269. (let ((origin (point-marker))
  20270. (start (region-beginning)))
  20271. (unwind-protect
  20272. (progn
  20273. (goto-char (region-end))
  20274. (while (> (point) start)
  20275. (org-backward-paragraph)
  20276. (org-fill-element justify)))
  20277. (goto-char origin)
  20278. (set-marker origin nil))))
  20279. (t (org-fill-element justify))))
  20280. (defun org-auto-fill-function ()
  20281. "Auto-fill function."
  20282. ;; Check if auto-filling is meaningful.
  20283. (let ((fc (current-fill-column)))
  20284. (when (and fc (> (current-column) fc))
  20285. (let* ((fill-prefix (org-adaptive-fill-function))
  20286. ;; Enforce empty fill prefix, if required. Otherwise, it
  20287. ;; will be computed again.
  20288. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20289. (when fill-prefix (do-auto-fill))))))
  20290. (defun org-comment-line-break-function (&optional soft)
  20291. "Break line at point and indent, continuing comment if within one.
  20292. The inserted newline is marked hard if variable
  20293. `use-hard-newlines' is true, unless optional argument SOFT is
  20294. non-nil."
  20295. (if soft (insert-and-inherit ?\n) (newline 1))
  20296. (save-excursion (forward-char -1) (delete-horizontal-space))
  20297. (delete-horizontal-space)
  20298. (indent-to-left-margin)
  20299. (insert-before-markers-and-inherit fill-prefix))
  20300. ;;; Fixed Width Areas
  20301. (defun org-toggle-fixed-width ()
  20302. "Toggle fixed-width markup.
  20303. Add or remove fixed-width markup on current line, whenever it
  20304. makes sense. Return an error otherwise.
  20305. If a region is active and if it contains only fixed-width areas
  20306. or blank lines, remove all fixed-width markup in it. If the
  20307. region contains anything else, convert all non-fixed-width lines
  20308. to fixed-width ones.
  20309. Blank lines at the end of the region are ignored unless the
  20310. region only contains such lines."
  20311. (interactive)
  20312. (if (not (org-region-active-p))
  20313. ;; No region:
  20314. ;;
  20315. ;; Remove fixed width marker only in a fixed-with element.
  20316. ;;
  20317. ;; Add fixed width maker in paragraphs, in blank lines after
  20318. ;; elements or at the beginning of a headline or an inlinetask,
  20319. ;; and before any one-line elements (e.g., a clock).
  20320. (progn
  20321. (beginning-of-line)
  20322. (let* ((element (org-element-at-point))
  20323. (type (org-element-type element)))
  20324. (cond
  20325. ((and (eq type 'fixed-width)
  20326. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20327. (replace-match
  20328. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20329. ((and (memq type '(babel-call clock comment diary-sexp headline
  20330. horizontal-rule keyword paragraph
  20331. planning))
  20332. (<= (org-element-property :post-affiliated element) (point)))
  20333. (skip-chars-forward " \t")
  20334. (insert ": "))
  20335. ((and (looking-at-p "[ \t]*$")
  20336. (or (eq type 'inlinetask)
  20337. (save-excursion
  20338. (skip-chars-forward " \r\t\n")
  20339. (<= (org-element-property :end element) (point)))))
  20340. (delete-region (point) (line-end-position))
  20341. (org-indent-line)
  20342. (insert ": "))
  20343. (t (user-error "Cannot insert a fixed-width line here")))))
  20344. ;; Region active.
  20345. (let* ((begin (save-excursion
  20346. (goto-char (region-beginning))
  20347. (line-beginning-position)))
  20348. (end (copy-marker
  20349. (save-excursion
  20350. (goto-char (region-end))
  20351. (unless (eolp) (beginning-of-line))
  20352. (if (save-excursion (re-search-backward "\\S-" begin t))
  20353. (progn (skip-chars-backward " \r\t\n") (point))
  20354. (point)))))
  20355. (all-fixed-width-p
  20356. (catch 'not-all-p
  20357. (save-excursion
  20358. (goto-char begin)
  20359. (skip-chars-forward " \r\t\n")
  20360. (when (eobp) (throw 'not-all-p nil))
  20361. (while (< (point) end)
  20362. (let ((element (org-element-at-point)))
  20363. (if (eq (org-element-type element) 'fixed-width)
  20364. (goto-char (org-element-property :end element))
  20365. (throw 'not-all-p nil))))
  20366. t))))
  20367. (if all-fixed-width-p
  20368. (save-excursion
  20369. (goto-char begin)
  20370. (while (< (point) end)
  20371. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20372. (replace-match
  20373. "" nil nil nil
  20374. (if (= (line-end-position) (match-end 0)) 0 1)))
  20375. (forward-line)))
  20376. (let ((min-ind (point-max)))
  20377. ;; Find minimum indentation across all lines.
  20378. (save-excursion
  20379. (goto-char begin)
  20380. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20381. (setq min-ind 0)
  20382. (catch 'zerop
  20383. (while (< (point) end)
  20384. (unless (looking-at-p "[ \t]*$")
  20385. (let ((ind (current-indentation)))
  20386. (setq min-ind (min min-ind ind))
  20387. (when (zerop ind) (throw 'zerop t))))
  20388. (forward-line)))))
  20389. ;; Loop over all lines and add fixed-width markup everywhere
  20390. ;; but in fixed-width lines.
  20391. (save-excursion
  20392. (goto-char begin)
  20393. (while (< (point) end)
  20394. (cond
  20395. ((org-at-heading-p)
  20396. (insert ": ")
  20397. (forward-line)
  20398. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20399. (insert ":")
  20400. (forward-line)))
  20401. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20402. (let* ((element (org-element-at-point))
  20403. (element-end (org-element-property :end element)))
  20404. (if (eq (org-element-type element) 'fixed-width)
  20405. (progn (goto-char element-end)
  20406. (skip-chars-backward " \r\t\n")
  20407. (forward-line))
  20408. (let ((limit (min end element-end)))
  20409. (while (< (point) limit)
  20410. (org-move-to-column min-ind t)
  20411. (insert ": ")
  20412. (forward-line))))))
  20413. (t
  20414. (org-move-to-column min-ind t)
  20415. (insert ": ")
  20416. (forward-line)))))))
  20417. (set-marker end nil))))
  20418. ;;; Blocks
  20419. (defun org-block-map (function &optional start end)
  20420. "Call FUNCTION at the head of all source blocks in the current buffer.
  20421. Optional arguments START and END can be used to limit the range."
  20422. (let ((start (or start (point-min)))
  20423. (end (or end (point-max))))
  20424. (save-excursion
  20425. (goto-char start)
  20426. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20427. (save-excursion
  20428. (save-match-data
  20429. (goto-char (match-beginning 0))
  20430. (funcall function)))))))
  20431. (defun org-next-block (arg &optional backward block-regexp)
  20432. "Jump to the next block.
  20433. With a prefix argument ARG, jump forward ARG many blocks.
  20434. When BACKWARD is non-nil, jump to the previous block.
  20435. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20436. Match data is set according to this regexp when the function
  20437. returns.
  20438. Return point at beginning of the opening line of found block.
  20439. Throw an error if no block is found."
  20440. (interactive "p")
  20441. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20442. (case-fold-search t)
  20443. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20444. (count (or arg 1))
  20445. (origin (point))
  20446. last-element)
  20447. (if backward (beginning-of-line) (end-of-line))
  20448. (while (and (> count 0) (funcall search-fn re nil t))
  20449. (let ((element (save-excursion
  20450. (goto-char (match-beginning 0))
  20451. (save-match-data (org-element-at-point)))))
  20452. (when (and (memq (org-element-type element)
  20453. '(center-block comment-block dynamic-block
  20454. example-block export-block quote-block
  20455. special-block src-block verse-block))
  20456. (<= (match-beginning 0)
  20457. (org-element-property :post-affiliated element)))
  20458. (setq last-element element)
  20459. (cl-decf count))))
  20460. (if (= count 0)
  20461. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20462. (save-match-data (org-show-context)))
  20463. (goto-char origin)
  20464. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20465. (defun org-previous-block (arg &optional block-regexp)
  20466. "Jump to the previous block.
  20467. With a prefix argument ARG, jump backward ARG many source blocks.
  20468. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20469. (interactive "p")
  20470. (org-next-block arg t block-regexp))
  20471. ;;; Comments
  20472. ;; Org comments syntax is quite complex. It requires the entire line
  20473. ;; to be just a comment. Also, even with the right syntax at the
  20474. ;; beginning of line, some elements (e.g., verse-block or
  20475. ;; example-block) don't accept comments. Usual Emacs comment commands
  20476. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20477. ;; Org still relies on `comment-dwim', but cannot trust
  20478. ;; `comment-only-p'. So, `comment-region-function' and
  20479. ;; `uncomment-region-function' both point
  20480. ;; to`org-comment-or-uncomment-region'. Eventually,
  20481. ;; `org-insert-comment' takes care of insertion of comments at the
  20482. ;; beginning of line.
  20483. ;; `org-setup-comments-handling' install comments related variables
  20484. ;; during `org-mode' initialization.
  20485. (defun org-setup-comments-handling ()
  20486. (interactive)
  20487. (setq-local comment-use-syntax nil)
  20488. (setq-local comment-start "# ")
  20489. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20490. (setq-local comment-insert-comment-function 'org-insert-comment)
  20491. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20492. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20493. (defun org-insert-comment ()
  20494. "Insert an empty comment above current line.
  20495. If the line is empty, insert comment at its beginning. When
  20496. point is within a source block, comment according to the related
  20497. major mode."
  20498. (if (let ((element (org-element-at-point)))
  20499. (and (eq (org-element-type element) 'src-block)
  20500. (< (save-excursion
  20501. (goto-char (org-element-property :post-affiliated element))
  20502. (line-end-position))
  20503. (point))
  20504. (> (save-excursion
  20505. (goto-char (org-element-property :end element))
  20506. (skip-chars-backward " \r\t\n")
  20507. (line-beginning-position))
  20508. (point))))
  20509. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20510. (beginning-of-line)
  20511. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20512. (open-line 1))
  20513. (org-indent-line)
  20514. (insert "# ")))
  20515. (defvar comment-empty-lines) ; From newcomment.el.
  20516. (defun org-comment-or-uncomment-region (beg end &rest _)
  20517. "Comment or uncomment each non-blank line in the region.
  20518. Uncomment each non-blank line between BEG and END if it only
  20519. contains commented lines. Otherwise, comment them. If region is
  20520. strictly within a source block, use appropriate comment syntax."
  20521. (if (let ((element (org-element-at-point)))
  20522. (and (eq (org-element-type element) 'src-block)
  20523. (< (save-excursion
  20524. (goto-char (org-element-property :post-affiliated element))
  20525. (line-end-position))
  20526. beg)
  20527. (>= (save-excursion
  20528. (goto-char (org-element-property :end element))
  20529. (skip-chars-backward " \r\t\n")
  20530. (line-beginning-position))
  20531. end)))
  20532. ;; Translate region boundaries for the Org buffer to the source
  20533. ;; buffer.
  20534. (let ((offset (- end beg)))
  20535. (save-excursion
  20536. (goto-char beg)
  20537. (org-babel-do-in-edit-buffer
  20538. (comment-or-uncomment-region (point) (+ offset (point))))))
  20539. (save-restriction
  20540. ;; Restrict region
  20541. (narrow-to-region (save-excursion (goto-char beg)
  20542. (skip-chars-forward " \r\t\n" end)
  20543. (line-beginning-position))
  20544. (save-excursion (goto-char end)
  20545. (skip-chars-backward " \r\t\n" beg)
  20546. (line-end-position)))
  20547. (let ((uncommentp
  20548. ;; UNCOMMENTP is non-nil when every non blank line between
  20549. ;; BEG and END is a comment.
  20550. (save-excursion
  20551. (goto-char (point-min))
  20552. (while (and (not (eobp))
  20553. (let ((element (org-element-at-point)))
  20554. (and (eq (org-element-type element) 'comment)
  20555. (goto-char (min (point-max)
  20556. (org-element-property
  20557. :end element)))))))
  20558. (eobp))))
  20559. (if uncommentp
  20560. ;; Only blank lines and comments in region: uncomment it.
  20561. (save-excursion
  20562. (goto-char (point-min))
  20563. (while (not (eobp))
  20564. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20565. (replace-match "" nil nil nil 1))
  20566. (forward-line)))
  20567. ;; Comment each line in region.
  20568. (let ((min-indent (point-max)))
  20569. ;; First find the minimum indentation across all lines.
  20570. (save-excursion
  20571. (goto-char (point-min))
  20572. (while (and (not (eobp)) (not (zerop min-indent)))
  20573. (unless (looking-at "[ \t]*$")
  20574. (setq min-indent (min min-indent (current-indentation))))
  20575. (forward-line)))
  20576. ;; Then loop over all lines.
  20577. (save-excursion
  20578. (goto-char (point-min))
  20579. (while (not (eobp))
  20580. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20581. ;; Don't get fooled by invisible text (e.g. link path)
  20582. ;; when moving to column MIN-INDENT.
  20583. (let ((buffer-invisibility-spec nil))
  20584. (org-move-to-column min-indent t))
  20585. (insert comment-start))
  20586. (forward-line)))))))))
  20587. (defun org-comment-dwim (_arg)
  20588. "Call the comment command you mean.
  20589. Call `org-toggle-comment' if on a heading, otherwise call
  20590. `comment-dwim', within a source edit buffer if needed."
  20591. (interactive "*P")
  20592. (cond ((org-at-heading-p)
  20593. (call-interactively #'org-toggle-comment))
  20594. ((org-in-src-block-p)
  20595. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20596. (t (call-interactively #'comment-dwim))))
  20597. ;;; Timestamps API
  20598. ;; This section contains tools to operate on, or create, timestamp
  20599. ;; objects, as returned by, e.g. `org-element-context'.
  20600. (defun org-timestamp-from-string (s)
  20601. "Convert Org timestamp S, as a string, into a timestamp object.
  20602. Return nil if S is not a valid timestamp string."
  20603. (when (org-string-nw-p s)
  20604. (with-temp-buffer
  20605. (save-excursion (insert s))
  20606. (org-element-timestamp-parser))))
  20607. (defun org-timestamp-from-time (time &optional with-time inactive)
  20608. "Convert a time value into a timestamp object.
  20609. TIME is an Emacs internal time representation, as returned, e.g.,
  20610. by `current-time'.
  20611. When optional argument WITH-TIME is non-nil, return a timestamp
  20612. object with a time part, i.e., with hours and minutes.
  20613. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20614. return an active timestamp."
  20615. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20616. (org-element-create 'timestamp
  20617. (list :type (if inactive 'inactive 'active)
  20618. :year-start year
  20619. :month-start month
  20620. :day-start day
  20621. :hour-start (and with-time hour)
  20622. :minute-start (and with-time minute)))))
  20623. (defun org-timestamp-to-time (timestamp &optional end)
  20624. "Convert TIMESTAMP object into an Emacs internal time value.
  20625. Use end of date range or time range when END is non-nil.
  20626. Otherwise, use its start."
  20627. (apply #'encode-time
  20628. (cons 0
  20629. (mapcar
  20630. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20631. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20632. '(:minute-start :hour-start :day-start :month-start
  20633. :year-start))))))
  20634. (defun org-timestamp-has-time-p (timestamp)
  20635. "Non-nil when TIMESTAMP has a time specified."
  20636. (org-element-property :hour-start timestamp))
  20637. (defun org-timestamp-format (timestamp format &optional end utc)
  20638. "Format a TIMESTAMP object into a string.
  20639. FORMAT is a format specifier to be passed to
  20640. `format-time-string'.
  20641. When optional argument END is non-nil, use end of date-range or
  20642. time-range, if possible.
  20643. When optional argument UTC is non-nil, time is be expressed as
  20644. Universal Time."
  20645. (format-time-string format (org-timestamp-to-time timestamp end)
  20646. (and utc t)))
  20647. (defun org-timestamp-split-range (timestamp &optional end)
  20648. "Extract a TIMESTAMP object from a date or time range.
  20649. END, when non-nil, means extract the end of the range.
  20650. Otherwise, extract its start.
  20651. Return a new timestamp object."
  20652. (let ((type (org-element-property :type timestamp)))
  20653. (if (memq type '(active inactive diary)) timestamp
  20654. (let ((split-ts (org-element-copy timestamp)))
  20655. ;; Set new type.
  20656. (org-element-put-property
  20657. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20658. ;; Copy start properties over end properties if END is
  20659. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20660. (let ((p-alist '((:minute-start . :minute-end)
  20661. (:hour-start . :hour-end)
  20662. (:day-start . :day-end)
  20663. (:month-start . :month-end)
  20664. (:year-start . :year-end))))
  20665. (dolist (p-cell p-alist)
  20666. (org-element-put-property
  20667. split-ts
  20668. (funcall (if end #'car #'cdr) p-cell)
  20669. (org-element-property
  20670. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20671. ;; Eventually refresh `:raw-value'.
  20672. (org-element-put-property split-ts :raw-value nil)
  20673. (org-element-put-property
  20674. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20675. (defun org-timestamp-translate (timestamp &optional boundary)
  20676. "Translate TIMESTAMP object to custom format.
  20677. Format string is defined in `org-time-stamp-custom-formats',
  20678. which see.
  20679. When optional argument BOUNDARY is non-nil, it is either the
  20680. symbol `start' or `end'. In this case, only translate the
  20681. starting or ending part of TIMESTAMP if it is a date or time
  20682. range. Otherwise, translate both parts.
  20683. Return timestamp as-is if `org-display-custom-times' is nil or if
  20684. it has a `diary' type."
  20685. (let ((type (org-element-property :type timestamp)))
  20686. (if (or (not org-display-custom-times) (eq type 'diary))
  20687. (org-element-interpret-data timestamp)
  20688. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20689. org-time-stamp-custom-formats)))
  20690. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20691. (concat (org-timestamp-format timestamp fmt)
  20692. "--"
  20693. (org-timestamp-format timestamp fmt t))
  20694. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20695. ;;; Other stuff
  20696. (defvar reftex-docstruct-symbol)
  20697. (defvar org--rds)
  20698. (defun org-reftex-citation ()
  20699. "Use reftex-citation to insert a citation into the buffer.
  20700. This looks for a line like
  20701. #+BIBLIOGRAPHY: foo plain option:-d
  20702. and derives from it that foo.bib is the bibliography file relevant
  20703. for this document. It then installs the necessary environment for RefTeX
  20704. to work in this buffer and calls `reftex-citation' to insert a citation
  20705. into the buffer.
  20706. Export of such citations to both LaTeX and HTML is handled by the contributed
  20707. package ox-bibtex by Taru Karttunen."
  20708. (interactive)
  20709. (let ((reftex-docstruct-symbol 'org--rds)
  20710. org--rds bib)
  20711. (org-with-wide-buffer
  20712. (let ((case-fold-search t)
  20713. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20714. (if (not (save-excursion
  20715. (or (re-search-forward re nil t)
  20716. (re-search-backward re nil t))))
  20717. (user-error "No bibliography defined in file")
  20718. (setq bib (concat (match-string 1) ".bib")
  20719. org--rds (list (list 'bib bib))))))
  20720. (call-interactively 'reftex-citation)))
  20721. ;;;; Functions extending outline functionality
  20722. (defun org-beginning-of-line (&optional n)
  20723. "Go to the beginning of the current visible line.
  20724. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20725. symbol `reversed', on the first attempt move to where the
  20726. headline text starts, and only move to beginning of line when the
  20727. cursor is already before the start of the text of the headline.
  20728. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20729. start of the text on the second attempt.
  20730. With argument N not nil or 1, move forward N - 1 lines first."
  20731. (interactive "^p")
  20732. (let ((origin (point))
  20733. (special (pcase org-special-ctrl-a/e
  20734. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20735. deactivate-mark)
  20736. ;; First move to a visible line.
  20737. (if (bound-and-true-p visual-line-mode)
  20738. (beginning-of-visual-line n)
  20739. (move-beginning-of-line n)
  20740. ;; `move-beginning-of-line' may leave point after invisible
  20741. ;; characters if line starts with such of these (e.g., with
  20742. ;; a link at column 0). Really move to the beginning of the
  20743. ;; current visible line.
  20744. (beginning-of-line))
  20745. (cond
  20746. ;; No special behavior. Point is already at the beginning of
  20747. ;; a line, logical or visual.
  20748. ((not special))
  20749. ;; `beginning-of-visual-line' left point before logical beginning
  20750. ;; of line: point is at the beginning of a visual line. Bail
  20751. ;; out.
  20752. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20753. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20754. ;; At a headline, special position is before the title, but
  20755. ;; after any TODO keyword or priority cookie.
  20756. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20757. (line-end-position)))
  20758. (bol (point)))
  20759. (if (eq special 'reversed)
  20760. (when (and (= origin bol) (eq last-command this-command))
  20761. (goto-char refpos))
  20762. (when (or (> origin refpos) (= origin bol))
  20763. (goto-char refpos)))))
  20764. ((and (looking-at org-list-full-item-re)
  20765. (memq (org-element-type (save-match-data (org-element-at-point)))
  20766. '(item plain-list)))
  20767. ;; Set special position at first white space character after
  20768. ;; bullet, and check-box, if any.
  20769. (let ((after-bullet
  20770. (let ((box (match-end 3)))
  20771. (cond ((not box) (match-end 1))
  20772. ((eq (char-after box) ?\s) (1+ box))
  20773. (t box)))))
  20774. (if (eq special 'reversed)
  20775. (when (and (= (point) origin) (eq last-command this-command))
  20776. (goto-char after-bullet))
  20777. (when (or (> origin after-bullet) (= (point) origin))
  20778. (goto-char after-bullet)))))
  20779. ;; No special context. Point is already at beginning of line.
  20780. (t nil))))
  20781. (defun org-end-of-line (&optional n)
  20782. "Go to the end of the line, but before ellipsis, if any.
  20783. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20784. symbol `reversed', ignore tags on the first attempt, and only
  20785. move to after the tags when the cursor is already beyond the end
  20786. of the headline.
  20787. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20788. on the second attempt.
  20789. With argument N not nil or 1, move forward N - 1 lines first."
  20790. (interactive "^p")
  20791. (let ((origin (point))
  20792. (special (pcase org-special-ctrl-a/e
  20793. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20794. deactivate-mark)
  20795. ;; First move to a visible line.
  20796. (if (bound-and-true-p visual-line-mode)
  20797. (beginning-of-visual-line n)
  20798. (move-beginning-of-line n))
  20799. (cond
  20800. ;; At a headline, with tags.
  20801. ((and special
  20802. (save-excursion
  20803. (beginning-of-line)
  20804. (let ((case-fold-search nil))
  20805. (looking-at org-complex-heading-regexp)))
  20806. (match-end 5))
  20807. (let ((tags (save-excursion
  20808. (goto-char (match-beginning 5))
  20809. (skip-chars-backward " \t")
  20810. (point)))
  20811. (visual-end (and (bound-and-true-p visual-line-mode)
  20812. (save-excursion
  20813. (end-of-visual-line)
  20814. (point)))))
  20815. ;; If `end-of-visual-line' brings us before end of line or
  20816. ;; even tags, i.e., the headline spans over multiple visual
  20817. ;; lines, move there.
  20818. (cond ((and visual-end
  20819. (< visual-end tags)
  20820. (<= origin visual-end))
  20821. (goto-char visual-end))
  20822. ((eq special 'reversed)
  20823. (if (and (= origin (line-end-position))
  20824. (eq this-command last-command))
  20825. (goto-char tags)
  20826. (end-of-line)))
  20827. (t
  20828. (if (or (< origin tags) (= origin (line-end-position)))
  20829. (goto-char tags)
  20830. (end-of-line))))))
  20831. ((bound-and-true-p visual-line-mode)
  20832. (let ((bol (line-beginning-position)))
  20833. (end-of-visual-line)
  20834. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20835. ;; end of a line, backtrack and use `end-of-line' instead.
  20836. (when (/= bol (line-beginning-position))
  20837. (goto-char bol)
  20838. (end-of-line))))
  20839. (t (end-of-line)))))
  20840. (defun org-backward-sentence (&optional _arg)
  20841. "Go to beginning of sentence, or beginning of table field.
  20842. This will call `backward-sentence' or `org-table-beginning-of-field',
  20843. depending on context."
  20844. (interactive)
  20845. (let* ((element (org-element-at-point))
  20846. (contents-begin (org-element-property :contents-begin element))
  20847. (table (org-element-lineage element '(table) t)))
  20848. (if (and table
  20849. (> (point) contents-begin)
  20850. (<= (point) (org-element-property :contents-end table)))
  20851. (call-interactively #'org-table-beginning-of-field)
  20852. (save-restriction
  20853. (when (and contents-begin
  20854. (< (point-min) contents-begin)
  20855. (> (point) contents-begin))
  20856. (narrow-to-region contents-begin
  20857. (org-element-property :contents-end element)))
  20858. (call-interactively #'backward-sentence)))))
  20859. (defun org-forward-sentence (&optional _arg)
  20860. "Go to end of sentence, or end of table field.
  20861. This will call `forward-sentence' or `org-table-end-of-field',
  20862. depending on context."
  20863. (interactive)
  20864. (if (and (org-at-heading-p)
  20865. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20866. (save-restriction
  20867. (narrow-to-region (line-beginning-position) (line-end-position))
  20868. (call-interactively #'forward-sentence))
  20869. (let* ((element (org-element-at-point))
  20870. (contents-end (org-element-property :contents-end element))
  20871. (table (org-element-lineage element '(table) t)))
  20872. (if (and table
  20873. (>= (point) (org-element-property :contents-begin table))
  20874. (< (point) contents-end))
  20875. (call-interactively #'org-table-end-of-field)
  20876. (save-restriction
  20877. (when (and contents-end
  20878. (> (point-max) contents-end)
  20879. ;; Skip blank lines between elements.
  20880. (< (org-element-property :end element)
  20881. (save-excursion (goto-char contents-end)
  20882. (skip-chars-forward " \r\t\n"))))
  20883. (narrow-to-region (org-element-property :contents-begin element)
  20884. contents-end))
  20885. ;; End of heading is considered as the end of a sentence.
  20886. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20887. (call-interactively #'forward-sentence)))))))
  20888. (defun org-kill-line (&optional _arg)
  20889. "Kill line, to tags or end of line."
  20890. (interactive)
  20891. (cond
  20892. ((or (not org-special-ctrl-k)
  20893. (bolp)
  20894. (not (org-at-heading-p)))
  20895. (when (and (get-char-property (line-end-position) 'invisible)
  20896. org-ctrl-k-protect-subtree
  20897. (or (eq org-ctrl-k-protect-subtree 'error)
  20898. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20899. (user-error
  20900. (substitute-command-keys
  20901. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20902. (call-interactively
  20903. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20904. ((org-match-line org-tag-line-re)
  20905. (let ((end (save-excursion
  20906. (goto-char (match-beginning 1))
  20907. (skip-chars-backward " \t")
  20908. (point))))
  20909. (if (<= end (point)) ;on tags part
  20910. (kill-region (point) (line-end-position))
  20911. (kill-region (point) end)))
  20912. (org-align-tags))
  20913. (t (kill-region (point) (line-end-position)))))
  20914. (defun org-yank (&optional arg)
  20915. "Yank. If the kill is a subtree, treat it specially.
  20916. This command will look at the current kill and check if is a single
  20917. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20918. cursor is at the beginning of a line or after the stars of a currently
  20919. empty headline, then the yank is handled specially. How exactly depends
  20920. on the value of the following variables.
  20921. `org-yank-folded-subtrees'
  20922. By default, this variable is non-nil, which results in
  20923. subtree(s) being folded after insertion, except if doing so
  20924. would swallow text after the yanked text.
  20925. `org-yank-adjusted-subtrees'
  20926. When non-nil (the default value is nil), the subtree will be
  20927. promoted or demoted in order to fit into the local outline tree
  20928. structure, which means that the level will be adjusted so that it
  20929. becomes the smaller one of the two *visible* surrounding headings.
  20930. Any prefix to this command will cause `yank' to be called directly with
  20931. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20932. will just
  20933. plainly yank the text as it is.
  20934. \[1] The test checks if the first non-white line is a heading
  20935. and if there are no other headings with fewer stars."
  20936. (interactive "P")
  20937. (org-yank-generic 'yank arg))
  20938. (defun org-yank-generic (command arg)
  20939. "Perform some yank-like command.
  20940. This function implements the behavior described in the `org-yank'
  20941. documentation. However, it has been generalized to work for any
  20942. interactive command with similar behavior."
  20943. ;; pretend to be command COMMAND
  20944. (setq this-command command)
  20945. (if arg
  20946. (call-interactively command)
  20947. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20948. (and (org-kill-is-subtree-p)
  20949. (or (bolp)
  20950. (and (looking-at "[ \t]*$")
  20951. (string-match
  20952. "\\`\\*+\\'"
  20953. (buffer-substring (point-at-bol) (point)))))))
  20954. swallowp)
  20955. (cond
  20956. ((and subtreep org-yank-folded-subtrees)
  20957. (let ((beg (point))
  20958. end)
  20959. (if (and subtreep org-yank-adjusted-subtrees)
  20960. (org-paste-subtree nil nil 'for-yank)
  20961. (call-interactively command))
  20962. (setq end (point))
  20963. (goto-char beg)
  20964. (when (and (bolp) subtreep
  20965. (not (setq swallowp
  20966. (org-yank-folding-would-swallow-text beg end))))
  20967. (org-with-limited-levels
  20968. (or (looking-at org-outline-regexp)
  20969. (re-search-forward org-outline-regexp-bol end t))
  20970. (while (and (< (point) end) (looking-at org-outline-regexp))
  20971. (outline-hide-subtree)
  20972. (org-cycle-show-empty-lines 'folded)
  20973. (condition-case nil
  20974. (outline-forward-same-level 1)
  20975. (error (goto-char end))))))
  20976. (when swallowp
  20977. (message
  20978. "Inserted text not folded because that would swallow text"))
  20979. (goto-char end)
  20980. (skip-chars-forward " \t\n\r")
  20981. (beginning-of-line 1)
  20982. (push-mark beg 'nomsg)))
  20983. ((and subtreep org-yank-adjusted-subtrees)
  20984. (let ((beg (point-at-bol)))
  20985. (org-paste-subtree nil nil 'for-yank)
  20986. (push-mark beg 'nomsg)))
  20987. (t
  20988. (call-interactively command))))))
  20989. (defun org-yank-folding-would-swallow-text (beg end)
  20990. "Would hide-subtree at BEG swallow any text after END?"
  20991. (let (level)
  20992. (org-with-limited-levels
  20993. (save-excursion
  20994. (goto-char beg)
  20995. (when (or (looking-at org-outline-regexp)
  20996. (re-search-forward org-outline-regexp-bol end t))
  20997. (setq level (org-outline-level)))
  20998. (goto-char end)
  20999. (skip-chars-forward " \t\r\n\v\f")
  21000. (not (or (eobp)
  21001. (and (bolp) (looking-at-p org-outline-regexp)
  21002. (<= (org-outline-level) level))))))))
  21003. (defun org-back-to-heading (&optional invisible-ok)
  21004. "Call `outline-back-to-heading', but provide a better error message."
  21005. (condition-case nil
  21006. (outline-back-to-heading invisible-ok)
  21007. (error (error "Before first headline at position %d in buffer %s"
  21008. (point) (current-buffer)))))
  21009. (defun org-before-first-heading-p ()
  21010. "Before first heading?"
  21011. (org-with-limited-levels
  21012. (save-excursion
  21013. (end-of-line)
  21014. (null (re-search-backward org-outline-regexp-bol nil t)))))
  21015. (defun org-at-heading-p (&optional _)
  21016. "Non-nil when on a headline."
  21017. (outline-on-heading-p t))
  21018. (defun org-in-commented-heading-p (&optional no-inheritance)
  21019. "Non-nil if point is under a commented heading.
  21020. This function also checks ancestors of the current headline,
  21021. unless optional argument NO-INHERITANCE is non-nil."
  21022. (cond
  21023. ((org-before-first-heading-p) nil)
  21024. ((let ((headline (nth 4 (org-heading-components))))
  21025. (and headline
  21026. (let ((case-fold-search nil))
  21027. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21028. headline)))))
  21029. (no-inheritance nil)
  21030. (t
  21031. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21032. (defun org-at-comment-p nil
  21033. "Is cursor in a commented line?"
  21034. (save-excursion
  21035. (save-match-data
  21036. (beginning-of-line)
  21037. (looking-at "^[ \t]*# "))))
  21038. (defun org-at-drawer-p nil
  21039. "Is cursor at a drawer keyword?"
  21040. (save-excursion
  21041. (move-beginning-of-line 1)
  21042. (looking-at org-drawer-regexp)))
  21043. (defun org-at-block-p nil
  21044. "Is cursor at a block keyword?"
  21045. (save-excursion
  21046. (move-beginning-of-line 1)
  21047. (looking-at org-block-regexp)))
  21048. (defun org-point-at-end-of-empty-headline ()
  21049. "If point is at the end of an empty headline, return t, else nil.
  21050. If the heading only contains a TODO keyword, it is still still considered
  21051. empty."
  21052. (let ((case-fold-search nil))
  21053. (and (looking-at "[ \t]*$")
  21054. org-todo-line-regexp
  21055. (save-excursion
  21056. (beginning-of-line)
  21057. (looking-at org-todo-line-regexp)
  21058. (string= (match-string 3) "")))))
  21059. (defun org-at-heading-or-item-p ()
  21060. (or (org-at-heading-p) (org-at-item-p)))
  21061. (defun org-at-target-p ()
  21062. (or (org-in-regexp org-radio-target-regexp)
  21063. (org-in-regexp org-target-regexp)))
  21064. (defun org-up-heading-all (arg)
  21065. "Move to the heading line of which the present line is a subheading.
  21066. This function considers both visible and invisible heading lines.
  21067. With argument, move up ARG levels."
  21068. (outline-up-heading arg t))
  21069. (defun org-up-heading-safe ()
  21070. "Move to the heading line of which the present line is a subheading.
  21071. This version will not throw an error. It will return the level of the
  21072. headline found, or nil if no higher level is found.
  21073. Also, this function will be a lot faster than `outline-up-heading',
  21074. because it relies on stars being the outline starters. This can really
  21075. make a significant difference in outlines with very many siblings."
  21076. (when (ignore-errors (org-back-to-heading t))
  21077. (let ((level-up (1- (funcall outline-level))))
  21078. (and (> level-up 0)
  21079. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21080. (funcall outline-level)))))
  21081. (defun org-first-sibling-p ()
  21082. "Is this heading the first child of its parents?"
  21083. (interactive)
  21084. (let ((re org-outline-regexp-bol)
  21085. level l)
  21086. (unless (org-at-heading-p t)
  21087. (user-error "Not at a heading"))
  21088. (setq level (funcall outline-level))
  21089. (save-excursion
  21090. (if (not (re-search-backward re nil t))
  21091. t
  21092. (setq l (funcall outline-level))
  21093. (< l level)))))
  21094. (defun org-goto-sibling (&optional previous)
  21095. "Goto the next sibling, even if it is invisible.
  21096. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21097. when a sibling was found. When none is found, return nil and don't
  21098. move point."
  21099. (let ((fun (if previous 're-search-backward 're-search-forward))
  21100. (pos (point))
  21101. (re org-outline-regexp-bol)
  21102. level l)
  21103. (when (ignore-errors (org-back-to-heading t))
  21104. (setq level (funcall outline-level))
  21105. (catch 'exit
  21106. (or previous (forward-char 1))
  21107. (while (funcall fun re nil t)
  21108. (setq l (funcall outline-level))
  21109. (when (< l level) (goto-char pos) (throw 'exit nil))
  21110. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21111. (goto-char pos)
  21112. nil))))
  21113. (defun org-show-siblings ()
  21114. "Show all siblings of the current headline."
  21115. (save-excursion
  21116. (while (org-goto-sibling) (org-flag-heading nil)))
  21117. (save-excursion
  21118. (while (org-goto-sibling 'previous)
  21119. (org-flag-heading nil))))
  21120. (defun org-goto-first-child ()
  21121. "Goto the first child, even if it is invisible.
  21122. Return t when a child was found. Otherwise don't move point and
  21123. return nil."
  21124. (let (level (pos (point)) (re org-outline-regexp-bol))
  21125. (when (ignore-errors (org-back-to-heading t))
  21126. (setq level (outline-level))
  21127. (forward-char 1)
  21128. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21129. (progn (goto-char (match-beginning 0)) t)
  21130. (goto-char pos) nil))))
  21131. (defun org-show-hidden-entry ()
  21132. "Show an entry where even the heading is hidden."
  21133. (save-excursion
  21134. (org-show-entry)))
  21135. (defun org-flag-heading (flag &optional entry)
  21136. "Flag the current heading. FLAG non-nil means make invisible.
  21137. When ENTRY is non-nil, show the entire entry."
  21138. (save-excursion
  21139. (org-back-to-heading t)
  21140. ;; Check if we should show the entire entry
  21141. (if (not entry)
  21142. (org-flag-region
  21143. (line-end-position 0) (line-end-position) flag 'outline)
  21144. (org-show-entry)
  21145. (save-excursion
  21146. (and (outline-next-heading)
  21147. (org-flag-heading nil))))))
  21148. (defun org-get-next-sibling ()
  21149. "Move to next heading of the same level, and return point.
  21150. If there is no such heading, return nil.
  21151. This is like outline-next-sibling, but invisible headings are ok."
  21152. (let ((level (funcall outline-level)))
  21153. (outline-next-heading)
  21154. (while (and (not (eobp)) (> (funcall outline-level) level))
  21155. (outline-next-heading))
  21156. (unless (or (eobp) (< (funcall outline-level) level))
  21157. (point))))
  21158. (defun org-get-last-sibling ()
  21159. "Move to previous heading of the same level, and return point.
  21160. If there is no such heading, return nil."
  21161. (let ((opoint (point))
  21162. (level (funcall outline-level)))
  21163. (outline-previous-heading)
  21164. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21165. (while (and (> (funcall outline-level) level)
  21166. (not (bobp)))
  21167. (outline-previous-heading))
  21168. (unless (< (funcall outline-level) level)
  21169. (point)))))
  21170. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21171. "Goto to the end of a subtree."
  21172. ;; This contains an exact copy of the original function, but it uses
  21173. ;; `org-back-to-heading', to make it work also in invisible
  21174. ;; trees. And is uses an invisible-ok argument.
  21175. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21176. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21177. ;; with many children and grandchildren etc, this can be much faster
  21178. ;; than the outline version.
  21179. (org-back-to-heading invisible-ok)
  21180. (let ((first t)
  21181. (level (funcall outline-level)))
  21182. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21183. ;; A true heading (not a plain list item), in Org
  21184. ;; This means we can easily find the end by looking
  21185. ;; only for the right number of stars. Using a regexp to do
  21186. ;; this is so much faster than using a Lisp loop.
  21187. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21188. (forward-char 1)
  21189. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21190. ;; something else, do it the slow way
  21191. (while (and (not (eobp))
  21192. (or first (> (funcall outline-level) level)))
  21193. (setq first nil)
  21194. (outline-next-heading)))
  21195. (unless to-heading
  21196. (when (memq (preceding-char) '(?\n ?\^M))
  21197. ;; Go to end of line before heading
  21198. (forward-char -1)
  21199. (when (memq (preceding-char) '(?\n ?\^M))
  21200. ;; leave blank line before heading
  21201. (forward-char -1)))))
  21202. (point))
  21203. (defun org-end-of-meta-data (&optional full)
  21204. "Skip planning line and properties drawer in current entry.
  21205. When optional argument FULL is non-nil, also skip empty lines,
  21206. clocking lines and regular drawers at the beginning of the
  21207. entry."
  21208. (org-back-to-heading t)
  21209. (forward-line)
  21210. (when (looking-at-p org-planning-line-re) (forward-line))
  21211. (when (looking-at org-property-drawer-re)
  21212. (goto-char (match-end 0))
  21213. (forward-line))
  21214. (when (and full (not (org-at-heading-p)))
  21215. (catch 'exit
  21216. (let ((end (save-excursion (outline-next-heading) (point)))
  21217. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21218. (while (not (eobp))
  21219. (cond ((looking-at-p org-drawer-regexp)
  21220. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21221. (forward-line)
  21222. (throw 'exit t)))
  21223. ((looking-at-p re) (forward-line))
  21224. (t (throw 'exit t))))))))
  21225. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21226. "Move forward to the ARG'th subheading at same level as this one.
  21227. Stop at the first and last subheadings of a superior heading.
  21228. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21229. non-nil it will also look at invisible ones."
  21230. (interactive "p")
  21231. (let ((backward? (and arg (< arg 0))))
  21232. (if (org-before-first-heading-p)
  21233. (if backward? (goto-char (point-min)) (outline-next-heading))
  21234. (org-back-to-heading invisible-ok)
  21235. (unless backward? (end-of-line)) ;do not match current headline
  21236. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21237. (f (if backward? #'re-search-backward #'re-search-forward))
  21238. (count (if arg (abs arg) 1))
  21239. (result (point)))
  21240. (while (and (> count 0)
  21241. (funcall f org-outline-regexp-bol nil 'move))
  21242. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21243. (cond ((< l level) (setq count 0))
  21244. ((and (= l level)
  21245. (or invisible-ok
  21246. (not (org-invisible-p
  21247. (line-beginning-position)))))
  21248. (cl-decf count)
  21249. (when (= l level) (setq result (point)))))))
  21250. (goto-char result))
  21251. (beginning-of-line))))
  21252. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21253. "Move backward to the ARG'th subheading at same level as this one.
  21254. Stop at the first and last subheadings of a superior heading."
  21255. (interactive "p")
  21256. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21257. (defun org-next-visible-heading (arg)
  21258. "Move to the next visible heading.
  21259. This function wraps `outline-next-visible-heading' with
  21260. `org-with-limited-levels' in order to skip over inline tasks and
  21261. respect customization of `org-odd-levels-only'."
  21262. (interactive "p")
  21263. (org-with-limited-levels
  21264. (outline-next-visible-heading arg)))
  21265. (defun org-previous-visible-heading (arg)
  21266. "Move to the previous visible heading.
  21267. This function wraps `outline-previous-visible-heading' with
  21268. `org-with-limited-levels' in order to skip over inline tasks and
  21269. respect customization of `org-odd-levels-only'."
  21270. (interactive "p")
  21271. (org-with-limited-levels
  21272. (outline-previous-visible-heading arg)))
  21273. (defun org-forward-paragraph ()
  21274. "Move forward to beginning of next paragraph or equivalent.
  21275. The function moves point to the beginning of the next visible
  21276. structural element, which can be a paragraph, a table, a list
  21277. item, etc. It also provides some special moves for convenience:
  21278. - On an affiliated keyword, jump to the beginning of the
  21279. relative element.
  21280. - On an item or a footnote definition, move to the second
  21281. element inside, if any.
  21282. - On a table or a property drawer, jump after it.
  21283. - On a verse or source block, stop after blank lines."
  21284. (interactive)
  21285. (unless (eobp)
  21286. (let* ((deactivate-mark nil)
  21287. (element (org-element-at-point))
  21288. (type (org-element-type element))
  21289. (post-affiliated (org-element-property :post-affiliated element))
  21290. (contents-begin (org-element-property :contents-begin element))
  21291. (contents-end (org-element-property :contents-end element))
  21292. (end (let ((end (org-element-property :end element)) (parent element))
  21293. (while (and (setq parent (org-element-property :parent parent))
  21294. (= (org-element-property :contents-end parent) end))
  21295. (setq end (org-element-property :end parent)))
  21296. end)))
  21297. (cond ((not element)
  21298. (skip-chars-forward " \r\t\n")
  21299. (or (eobp) (beginning-of-line)))
  21300. ;; On affiliated keywords, move to element's beginning.
  21301. ((< (point) post-affiliated)
  21302. (goto-char post-affiliated))
  21303. ;; At a table row, move to the end of the table. Similarly,
  21304. ;; at a node property, move to the end of the property
  21305. ;; drawer.
  21306. ((memq type '(node-property table-row))
  21307. (goto-char (org-element-property
  21308. :end (org-element-property :parent element))))
  21309. ((memq type '(property-drawer table)) (goto-char end))
  21310. ;; Consider blank lines as separators in verse and source
  21311. ;; blocks to ease editing.
  21312. ((memq type '(src-block verse-block))
  21313. (when (eq type 'src-block)
  21314. (setq contents-end
  21315. (save-excursion (goto-char end)
  21316. (skip-chars-backward " \r\t\n")
  21317. (line-beginning-position))))
  21318. (beginning-of-line)
  21319. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21320. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21321. (goto-char end)
  21322. (skip-chars-forward " \r\t\n")
  21323. (if (= (point) contents-end) (goto-char end)
  21324. (beginning-of-line))))
  21325. ;; With no contents, just skip element.
  21326. ((not contents-begin) (goto-char end))
  21327. ;; If contents are invisible, skip the element altogether.
  21328. ((org-invisible-p (line-end-position))
  21329. (cl-case type
  21330. (headline
  21331. (org-with-limited-levels (outline-next-visible-heading 1)))
  21332. ;; At a plain list, make sure we move to the next item
  21333. ;; instead of skipping the whole list.
  21334. (plain-list (forward-char)
  21335. (org-forward-paragraph))
  21336. (otherwise (goto-char end))))
  21337. ((>= (point) contents-end) (goto-char end))
  21338. ((>= (point) contents-begin)
  21339. ;; This can only happen on paragraphs and plain lists.
  21340. (cl-case type
  21341. (paragraph (goto-char end))
  21342. ;; At a plain list, try to move to second element in
  21343. ;; first item, if possible.
  21344. (plain-list (end-of-line)
  21345. (org-forward-paragraph))))
  21346. ;; When contents start on the middle of a line (e.g. in
  21347. ;; items and footnote definitions), try to reach first
  21348. ;; element starting after current line.
  21349. ((> (line-end-position) contents-begin)
  21350. (end-of-line)
  21351. (org-forward-paragraph))
  21352. (t (goto-char contents-begin))))))
  21353. (defun org-backward-paragraph ()
  21354. "Move backward to start of previous paragraph or equivalent.
  21355. The function moves point to the beginning of the current
  21356. structural element, which can be a paragraph, a table, a list
  21357. item, etc., or to the beginning of the previous visible one if
  21358. point is already there. It also provides some special moves for
  21359. convenience:
  21360. - On an affiliated keyword, jump to the first one.
  21361. - On a table or a property drawer, move to its beginning.
  21362. - On comment, example, export, src and verse blocks, stop
  21363. before blank lines."
  21364. (interactive)
  21365. (unless (bobp)
  21366. (let* ((deactivate-mark nil)
  21367. (element (org-element-at-point))
  21368. (type (org-element-type element))
  21369. (contents-end (org-element-property :contents-end element))
  21370. (post-affiliated (org-element-property :post-affiliated element))
  21371. (begin (org-element-property :begin element))
  21372. (special? ;blocks handled specially
  21373. (memq type '(comment-block example-block export-block src-block
  21374. verse-block)))
  21375. (contents-begin
  21376. (if special?
  21377. ;; These types have no proper contents. Fake line
  21378. ;; below the block opening line as contents beginning.
  21379. (save-excursion (goto-char begin) (line-beginning-position 2))
  21380. (org-element-property :contents-begin element))))
  21381. (cond
  21382. ((not element) (goto-char (point-min)))
  21383. ((= (point) begin)
  21384. (backward-char)
  21385. (org-backward-paragraph))
  21386. ((<= (point) post-affiliated) (goto-char begin))
  21387. ;; Special behavior: on a table or a property drawer, move to
  21388. ;; its beginning.
  21389. ((memq type '(node-property table-row))
  21390. (goto-char (org-element-property
  21391. :post-affiliated (org-element-property :parent element))))
  21392. (special?
  21393. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21394. ;; Inside a verse block, see blank lines as paragraph
  21395. ;; separators.
  21396. (let ((origin (point)))
  21397. (skip-chars-backward " \r\t\n" contents-begin)
  21398. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21399. (skip-chars-forward " \r\t\n" origin)
  21400. (if (= (point) origin) (goto-char contents-begin)
  21401. (beginning-of-line))))))
  21402. ((eq type 'paragraph) (goto-char contents-begin)
  21403. ;; When at first paragraph in an item or a footnote definition,
  21404. ;; move directly to beginning of line.
  21405. (let ((parent-contents
  21406. (org-element-property
  21407. :contents-begin (org-element-property :parent element))))
  21408. (when (and parent-contents (= parent-contents contents-begin))
  21409. (beginning-of-line))))
  21410. ;; At the end of a greater element, move to the beginning of
  21411. ;; the last element within.
  21412. ((and contents-end (>= (point) contents-end))
  21413. (goto-char (1- contents-end))
  21414. (org-backward-paragraph))
  21415. (t (goto-char (or post-affiliated begin))))
  21416. ;; Ensure we never leave point invisible.
  21417. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21418. (defun org-forward-element ()
  21419. "Move forward by one element.
  21420. Move to the next element at the same level, when possible."
  21421. (interactive)
  21422. (cond ((eobp) (user-error "Cannot move further down"))
  21423. ((org-with-limited-levels (org-at-heading-p))
  21424. (let ((origin (point)))
  21425. (goto-char (org-end-of-subtree nil t))
  21426. (unless (org-with-limited-levels (org-at-heading-p))
  21427. (goto-char origin)
  21428. (user-error "Cannot move further down"))))
  21429. (t
  21430. (let* ((elem (org-element-at-point))
  21431. (end (org-element-property :end elem))
  21432. (parent (org-element-property :parent elem)))
  21433. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21434. (goto-char (org-element-property :end parent)))
  21435. ((integer-or-marker-p end) (goto-char end))
  21436. (t (message "No element at point")))))))
  21437. (defun org-backward-element ()
  21438. "Move backward by one element.
  21439. Move to the previous element at the same level, when possible."
  21440. (interactive)
  21441. (cond ((bobp) (user-error "Cannot move further up"))
  21442. ((org-with-limited-levels (org-at-heading-p))
  21443. ;; At a headline, move to the previous one, if any, or stay
  21444. ;; here.
  21445. (let ((origin (point)))
  21446. (org-with-limited-levels (org-backward-heading-same-level 1))
  21447. ;; When current headline has no sibling above, move to its
  21448. ;; parent.
  21449. (when (= (point) origin)
  21450. (or (org-with-limited-levels (org-up-heading-safe))
  21451. (progn (goto-char origin)
  21452. (user-error "Cannot move further up"))))))
  21453. (t
  21454. (let* ((elem (org-element-at-point))
  21455. (beg (org-element-property :begin elem)))
  21456. (cond
  21457. ;; Move to beginning of current element if point isn't
  21458. ;; there already.
  21459. ((null beg) (message "No element at point"))
  21460. ((/= (point) beg) (goto-char beg))
  21461. (t (goto-char beg)
  21462. (skip-chars-backward " \r\t\n")
  21463. (unless (bobp)
  21464. (let ((prev (org-element-at-point)))
  21465. (goto-char (org-element-property :begin prev))
  21466. (while (and (setq prev (org-element-property :parent prev))
  21467. (<= (org-element-property :end prev) beg))
  21468. (goto-char (org-element-property :begin prev)))))))))))
  21469. (defun org-up-element ()
  21470. "Move to upper element."
  21471. (interactive)
  21472. (if (org-with-limited-levels (org-at-heading-p))
  21473. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21474. (let* ((elem (org-element-at-point))
  21475. (parent (org-element-property :parent elem)))
  21476. (if parent (goto-char (org-element-property :begin parent))
  21477. (if (org-with-limited-levels (org-before-first-heading-p))
  21478. (user-error "No surrounding element")
  21479. (org-with-limited-levels (org-back-to-heading)))))))
  21480. (defun org-down-element ()
  21481. "Move to inner element."
  21482. (interactive)
  21483. (let ((element (org-element-at-point)))
  21484. (cond
  21485. ((memq (org-element-type element) '(plain-list table))
  21486. (goto-char (org-element-property :contents-begin element))
  21487. (forward-char))
  21488. ((memq (org-element-type element) org-element-greater-elements)
  21489. ;; If contents are hidden, first disclose them.
  21490. (when (org-invisible-p (line-end-position)) (org-cycle))
  21491. (goto-char (or (org-element-property :contents-begin element)
  21492. (user-error "No content for this element"))))
  21493. (t (user-error "No inner element")))))
  21494. (defun org-drag-element-backward ()
  21495. "Move backward element at point."
  21496. (interactive)
  21497. (let ((elem (or (org-element-at-point)
  21498. (user-error "No element at point"))))
  21499. (if (eq (org-element-type elem) 'headline)
  21500. ;; Preserve point when moving a whole tree, even if point was
  21501. ;; on blank lines below the headline.
  21502. (let ((offset (skip-chars-backward " \t\n")))
  21503. (unwind-protect (org-move-subtree-up)
  21504. (forward-char (- offset))))
  21505. (let ((prev-elem
  21506. (save-excursion
  21507. (goto-char (org-element-property :begin elem))
  21508. (skip-chars-backward " \r\t\n")
  21509. (unless (bobp)
  21510. (let* ((beg (org-element-property :begin elem))
  21511. (prev (org-element-at-point))
  21512. (up prev))
  21513. (while (and (setq up (org-element-property :parent up))
  21514. (<= (org-element-property :end up) beg))
  21515. (setq prev up))
  21516. prev)))))
  21517. ;; Error out if no previous element or previous element is
  21518. ;; a parent of the current one.
  21519. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21520. (user-error "Cannot drag element backward")
  21521. (let ((pos (point)))
  21522. (org-element-swap-A-B prev-elem elem)
  21523. (goto-char (+ (org-element-property :begin prev-elem)
  21524. (- pos (org-element-property :begin elem))))))))))
  21525. (defun org-drag-element-forward ()
  21526. "Move forward element at point."
  21527. (interactive)
  21528. (let* ((pos (point))
  21529. (elem (or (org-element-at-point)
  21530. (user-error "No element at point"))))
  21531. (when (= (point-max) (org-element-property :end elem))
  21532. (user-error "Cannot drag element forward"))
  21533. (goto-char (org-element-property :end elem))
  21534. (let ((next-elem (org-element-at-point)))
  21535. (when (or (org-element-nested-p elem next-elem)
  21536. (and (eq (org-element-type next-elem) 'headline)
  21537. (not (eq (org-element-type elem) 'headline))))
  21538. (goto-char pos)
  21539. (user-error "Cannot drag element forward"))
  21540. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21541. ;; body's length (without final blanks) and by the length of
  21542. ;; blanks between ELEM and NEXT-ELEM.
  21543. (let ((size-next (- (save-excursion
  21544. (goto-char (org-element-property :end next-elem))
  21545. (skip-chars-backward " \r\t\n")
  21546. (forward-line)
  21547. ;; Small correction if buffer doesn't end
  21548. ;; with a newline character.
  21549. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21550. (org-element-property :begin next-elem)))
  21551. (size-blank (- (org-element-property :end elem)
  21552. (save-excursion
  21553. (goto-char (org-element-property :end elem))
  21554. (skip-chars-backward " \r\t\n")
  21555. (forward-line)
  21556. (point)))))
  21557. (org-element-swap-A-B elem next-elem)
  21558. (goto-char (+ pos size-next size-blank))))))
  21559. (defun org-drag-line-forward (arg)
  21560. "Drag the line at point ARG lines forward."
  21561. (interactive "p")
  21562. (dotimes (_ (abs arg))
  21563. (let ((c (current-column)))
  21564. (if (< 0 arg)
  21565. (progn
  21566. (beginning-of-line 2)
  21567. (transpose-lines 1)
  21568. (beginning-of-line 0))
  21569. (transpose-lines 1)
  21570. (beginning-of-line -1))
  21571. (org-move-to-column c))))
  21572. (defun org-drag-line-backward (arg)
  21573. "Drag the line at point ARG lines backward."
  21574. (interactive "p")
  21575. (org-drag-line-forward (- arg)))
  21576. (defun org-mark-element ()
  21577. "Put point at beginning of this element, mark at end.
  21578. Interactively, if this command is repeated or (in Transient Mark
  21579. mode) if the mark is active, it marks the next element after the
  21580. ones already marked."
  21581. (interactive)
  21582. (let (deactivate-mark)
  21583. (if (and (called-interactively-p 'any)
  21584. (or (and (eq last-command this-command) (mark t))
  21585. (and transient-mark-mode mark-active)))
  21586. (set-mark
  21587. (save-excursion
  21588. (goto-char (mark))
  21589. (goto-char (org-element-property :end (org-element-at-point)))))
  21590. (let ((element (org-element-at-point)))
  21591. (end-of-line)
  21592. (push-mark (org-element-property :end element) t t)
  21593. (goto-char (org-element-property :begin element))))))
  21594. (defun org-narrow-to-element ()
  21595. "Narrow buffer to current element."
  21596. (interactive)
  21597. (let ((elem (org-element-at-point)))
  21598. (cond
  21599. ((eq (car elem) 'headline)
  21600. (narrow-to-region
  21601. (org-element-property :begin elem)
  21602. (org-element-property :end elem)))
  21603. ((memq (car elem) org-element-greater-elements)
  21604. (narrow-to-region
  21605. (org-element-property :contents-begin elem)
  21606. (org-element-property :contents-end elem)))
  21607. (t
  21608. (narrow-to-region
  21609. (org-element-property :begin elem)
  21610. (org-element-property :end elem))))))
  21611. (defun org-transpose-element ()
  21612. "Transpose current and previous elements, keeping blank lines between.
  21613. Point is moved after both elements."
  21614. (interactive)
  21615. (org-skip-whitespace)
  21616. (let ((end (org-element-property :end (org-element-at-point))))
  21617. (org-drag-element-backward)
  21618. (goto-char end)))
  21619. (defun org-unindent-buffer ()
  21620. "Un-indent the visible part of the buffer.
  21621. Relative indentation (between items, inside blocks, etc.) isn't
  21622. modified."
  21623. (interactive)
  21624. (unless (eq major-mode 'org-mode)
  21625. (user-error "Cannot un-indent a buffer not in Org mode"))
  21626. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21627. (unindent-tree
  21628. (lambda (contents)
  21629. (dolist (element (reverse contents))
  21630. (if (memq (org-element-type element) '(headline section))
  21631. (funcall unindent-tree (org-element-contents element))
  21632. (save-excursion
  21633. (save-restriction
  21634. (narrow-to-region
  21635. (org-element-property :begin element)
  21636. (org-element-property :end element))
  21637. (org-do-remove-indentation))))))))
  21638. (funcall unindent-tree (org-element-contents parse-tree))))
  21639. (defun org-make-options-regexp (kwds &optional extra)
  21640. "Make a regular expression for keyword lines.
  21641. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21642. when non-nil, is a regexp matching keywords names."
  21643. (concat "^[ \t]*#\\+\\("
  21644. (regexp-opt kwds)
  21645. (and extra (concat (and kwds "\\|") extra))
  21646. "\\):[ \t]*\\(.*\\)"))
  21647. ;;; Conveniently switch to Info nodes
  21648. (defun org-info-find-node (&optional nodename)
  21649. "Find Info documentation NODENAME or Org documentation according context.
  21650. Started from `gnus-info-find-node'."
  21651. (interactive)
  21652. (Info-goto-node
  21653. (or nodename
  21654. (let ((default-org-info-node "(org) Top"))
  21655. (cond
  21656. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  21657. ((eq 'org-mode major-mode)
  21658. (let* ((context (org-element-at-point))
  21659. (element-info-nodes ; compare to `org-element-all-elements'.
  21660. `((babel-call . "(org) Evaluating Code Blocks")
  21661. (center-block . "(org) Paragraphs")
  21662. (clock . ,default-org-info-node)
  21663. (comment . "(org) Comment Lines")
  21664. (comment-block . "(org) Comment Lines")
  21665. (diary-sexp . ,default-org-info-node)
  21666. (drawer . "(org) Drawers")
  21667. (dynamic-block . "(org) Dynamic Blocks")
  21668. (example-block . "(org) Literal Examples")
  21669. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  21670. (fixed-width . ,default-org-info-node)
  21671. (footnote-definition . "(org) Creating Footnotes")
  21672. (headline . "(org) Document Structure")
  21673. (horizontal-rule . "(org) Built-in Table Editor")
  21674. (inlinetask . ,default-org-info-node)
  21675. (item . "(org) Plain Lists")
  21676. (keyword . "(org) Per-file keywords")
  21677. (latex-environment . "(org) LaTeX Export")
  21678. (node-property . "(org) Properties and Columns")
  21679. (paragraph . "(org) Paragraphs")
  21680. (plain-list . "(org) Plain Lists")
  21681. (planning . "(org) Deadlines and Scheduling")
  21682. (property-drawer . "(org) Properties and Columns")
  21683. (quote-block . "(org) Paragraphs")
  21684. (section . ,default-org-info-node)
  21685. (special-block . ,default-org-info-node)
  21686. (src-block . "(org) Working with Source Code")
  21687. (table . "(org) Tables")
  21688. (table-row . "(org) Tables")
  21689. (verse-block . "(org) Paragraphs"))))
  21690. (or (cdr (assoc (car context) element-info-nodes))
  21691. default-org-info-node)))
  21692. (t default-org-info-node))))))
  21693. ;;; Finish up
  21694. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21695. (lambda () (add-hook 'change-major-mode-hook
  21696. 'org-show-all 'append 'local)))
  21697. (provide 'org)
  21698. (run-hooks 'org-load-hook)
  21699. ;;; org.el ends here