org.el 911 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090
  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-2017 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: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocking-buffer "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function
  120. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  121. (declare-function org-element-at-point "org-element" ())
  122. (declare-function org-element-cache-refresh "org-element" (pos))
  123. (declare-function org-element-cache-reset "org-element" (&optional all))
  124. (declare-function org-element-contents "org-element" (element))
  125. (declare-function org-element-context "org-element" (&optional element))
  126. (declare-function org-element-copy "org-element" (datum))
  127. (declare-function org-element-interpret-data "org-element" (data))
  128. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  129. (declare-function org-element-link-parser "org-element" ())
  130. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  131. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  132. (declare-function org-element-property "org-element" (property element))
  133. (declare-function org-element-put-property "org-element" (element property value))
  134. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  135. (declare-function org-element-type "org-element" (element))
  136. (declare-function org-element-update-syntax "org-element" ())
  137. (declare-function org-id-find-id-file "org-id" (id))
  138. (declare-function org-id-get-create "org-id" (&optional force))
  139. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  140. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  141. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  142. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  143. (declare-function org-table-align "org-table" ())
  144. (declare-function org-table-begin "org-table" (&optional table-type))
  145. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  146. (declare-function org-table-blank-field "org-table" ())
  147. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  148. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  149. (declare-function org-table-cut-region "org-table" (beg end))
  150. (declare-function org-table-edit-field "org-table" (arg))
  151. (declare-function org-table-end "org-table" (&optional table-type))
  152. (declare-function org-table-end-of-field "org-table" (&optional n))
  153. (declare-function org-table-insert-row "org-table" (&optional arg))
  154. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  155. (declare-function org-table-maybe-eval-formula "org-table" ())
  156. (declare-function org-table-maybe-recalculate-line "org-table" ())
  157. (declare-function org-table-next-row "org-table" ())
  158. (declare-function org-table-paste-rectangle "org-table" ())
  159. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  160. (declare-function
  161. org-table-sort-lines "org-table"
  162. (&optional with-case sorting-type getkey-func compare-func interactive?))
  163. (declare-function org-table-shrink "org-table" (&optional begin end))
  164. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  165. (declare-function org-table-wrap-region "org-table" (arg))
  166. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  167. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  168. (declare-function orgtbl-mode "org-table" (&optional arg))
  169. (declare-function org-export-get-backend "ox" (name))
  170. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  171. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  172. (defvar ffap-url-regexp)
  173. (defvar org-element-paragraph-separate)
  174. ;; load languages based on value of `org-babel-load-languages'
  175. (defvar org-babel-load-languages)
  176. ;;;###autoload
  177. (defun org-babel-do-load-languages (sym value)
  178. "Load the languages defined in `org-babel-load-languages'."
  179. (set-default sym value)
  180. (dolist (pair org-babel-load-languages)
  181. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  182. (if active
  183. (require (intern (concat "ob-" lang)))
  184. (funcall 'fmakunbound
  185. (intern (concat "org-babel-execute:" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-expand-body:" lang)))))))
  188. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  189. ;;;###autoload
  190. (defun org-babel-load-file (file &optional compile)
  191. "Load Emacs Lisp source code blocks in the Org FILE.
  192. This function exports the source code using `org-babel-tangle'
  193. and then loads the resulting file using `load-file'. With prefix
  194. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  195. file to byte-code before it is loaded."
  196. (interactive "fFile to load: \nP")
  197. (let* ((age (lambda (file)
  198. (float-time
  199. (time-subtract (current-time)
  200. (nth 5 (or (file-attributes (file-truename file))
  201. (file-attributes file)))))))
  202. (base-name (file-name-sans-extension file))
  203. (exported-file (concat base-name ".el")))
  204. ;; tangle if the Org file is newer than the elisp file
  205. (unless (and (file-exists-p exported-file)
  206. (> (funcall age file) (funcall age exported-file)))
  207. ;; Tangle-file traversal returns reversed list of tangled files
  208. ;; and we want to evaluate the first target.
  209. (setq exported-file
  210. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  211. (message "%s %s"
  212. (if compile
  213. (progn (byte-compile-file exported-file 'load)
  214. "Compiled and loaded")
  215. (progn (load-file exported-file) "Loaded"))
  216. exported-file)))
  217. (defcustom org-babel-load-languages '((emacs-lisp . t))
  218. "Languages which can be evaluated in Org buffers.
  219. This list can be used to load support for any of the languages
  220. below, note that each language will depend on a different set of
  221. system executables and/or Emacs modes. When a language is
  222. \"loaded\", then code blocks in that language can be evaluated
  223. with `org-babel-execute-src-block' bound by default to C-c
  224. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  225. be set to remove code block evaluation from the C-c C-c
  226. keybinding. By default only Emacs Lisp (which has no
  227. requirements) is loaded."
  228. :group 'org-babel
  229. :set 'org-babel-do-load-languages
  230. :version "24.1"
  231. :type '(alist :tag "Babel Languages"
  232. :key-type
  233. (choice
  234. (const :tag "Awk" awk)
  235. (const :tag "C" C)
  236. (const :tag "R" R)
  237. (const :tag "Asymptote" asymptote)
  238. (const :tag "Calc" calc)
  239. (const :tag "Clojure" clojure)
  240. (const :tag "CSS" css)
  241. (const :tag "Ditaa" ditaa)
  242. (const :tag "Dot" dot)
  243. (const :tag "Ebnf2ps" ebnf2ps)
  244. (const :tag "Emacs Lisp" emacs-lisp)
  245. (const :tag "Forth" forth)
  246. (const :tag "Fortran" fortran)
  247. (const :tag "Gnuplot" gnuplot)
  248. (const :tag "Haskell" haskell)
  249. (const :tag "hledger" hledger)
  250. (const :tag "IO" io)
  251. (const :tag "J" J)
  252. (const :tag "Java" java)
  253. (const :tag "Javascript" js)
  254. (const :tag "LaTeX" latex)
  255. (const :tag "Ledger" ledger)
  256. (const :tag "Lilypond" lilypond)
  257. (const :tag "Lisp" lisp)
  258. (const :tag "Makefile" makefile)
  259. (const :tag "Maxima" maxima)
  260. (const :tag "Matlab" matlab)
  261. (const :tag "Mscgen" mscgen)
  262. (const :tag "Ocaml" ocaml)
  263. (const :tag "Octave" octave)
  264. (const :tag "Org" org)
  265. (const :tag "Perl" perl)
  266. (const :tag "Pico Lisp" picolisp)
  267. (const :tag "PlantUML" plantuml)
  268. (const :tag "Python" python)
  269. (const :tag "Ruby" ruby)
  270. (const :tag "Sass" sass)
  271. (const :tag "Scala" scala)
  272. (const :tag "Scheme" scheme)
  273. (const :tag "Screen" screen)
  274. (const :tag "Shell Script" shell)
  275. (const :tag "Shen" shen)
  276. (const :tag "Sql" sql)
  277. (const :tag "Sqlite" sqlite)
  278. (const :tag "Stan" stan)
  279. (const :tag "Vala" vala))
  280. :value-type (boolean :tag "Activate" :value t)))
  281. ;;;; Customization variables
  282. (defcustom org-clone-delete-id nil
  283. "Remove ID property of clones of a subtree.
  284. When non-nil, clones of a subtree don't inherit the ID property.
  285. Otherwise they inherit the ID property with a new unique
  286. identifier."
  287. :type 'boolean
  288. :version "24.1"
  289. :group 'org-id)
  290. ;;; Version
  291. (org-check-version)
  292. ;;;###autoload
  293. (defun org-version (&optional here full message)
  294. "Show the Org version.
  295. Interactively, or when MESSAGE is non-nil, show it in echo area.
  296. With prefix argument, or when HERE is non-nil, insert it at point.
  297. In non-interactive uses, a reduced version string is output unless
  298. FULL is given."
  299. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  300. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  301. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  302. (load-suffixes (list ".el"))
  303. (org-install-dir
  304. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  305. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  306. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  307. (let* ((load-suffixes save-load-suffixes)
  308. (release (org-release))
  309. (git-version (org-git-version))
  310. (version (format "Org mode version %s (%s @ %s)"
  311. release
  312. git-version
  313. (if org-install-dir
  314. (if (string= org-dir org-install-dir)
  315. org-install-dir
  316. (concat "mixed installation! "
  317. org-install-dir
  318. " and "
  319. org-dir))
  320. "org-loaddefs.el can not be found!")))
  321. (version1 (if full version release)))
  322. (when here (insert version1))
  323. (when message (message "%s" version1))
  324. version1)))
  325. (defconst org-version (org-version))
  326. ;;; Syntax Constants
  327. ;;;; Block
  328. (defconst org-block-regexp
  329. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  330. "Regular expression for hiding blocks.")
  331. (defconst org-dblock-start-re
  332. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  333. "Matches the start line of a dynamic block, with parameters.")
  334. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  335. "Matches the end of a dynamic block.")
  336. ;;;; Clock and Planning
  337. (defconst org-clock-string "CLOCK:"
  338. "String used as prefix for timestamps clocking work hours on an item.")
  339. (defvar org-closed-string "CLOSED:"
  340. "String used as the prefix for timestamps logging closing a TODO entry.")
  341. (defvar org-deadline-string "DEADLINE:"
  342. "String to mark deadline entries.
  343. \\<org-mode-map>
  344. A deadline is this string, followed by a time stamp. It must be
  345. a word, terminated by a colon. You can insert a schedule keyword
  346. and a timestamp with `\\[org-deadline]'.")
  347. (defvar org-scheduled-string "SCHEDULED:"
  348. "String to mark scheduled TODO entries.
  349. \\<org-mode-map>
  350. A schedule is this string, followed by a time stamp. It must be
  351. a word, terminated by a colon. You can insert a schedule keyword
  352. and a timestamp with `\\[org-schedule]'.")
  353. (defconst org-ds-keyword-length
  354. (+ 2
  355. (apply #'max
  356. (mapcar #'length
  357. (list org-deadline-string org-scheduled-string
  358. org-clock-string org-closed-string))))
  359. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  360. (defconst org-planning-line-re
  361. (concat "^[ \t]*"
  362. (regexp-opt
  363. (list org-closed-string org-deadline-string org-scheduled-string)
  364. t))
  365. "Matches a line with planning info.
  366. Matched keyword is in group 1.")
  367. (defconst org-clock-line-re
  368. (concat "^[ \t]*" org-clock-string)
  369. "Matches a line with clock info.")
  370. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  371. "Matches the DEADLINE keyword.")
  372. (defconst org-deadline-time-regexp
  373. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  374. "Matches the DEADLINE keyword together with a time stamp.")
  375. (defconst org-deadline-time-hour-regexp
  376. (concat "\\<" org-deadline-string
  377. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  378. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  379. (defconst org-deadline-line-regexp
  380. (concat "\\<\\(" org-deadline-string "\\).*")
  381. "Matches the DEADLINE keyword and the rest of the line.")
  382. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  383. "Matches the SCHEDULED keyword.")
  384. (defconst org-scheduled-time-regexp
  385. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  386. "Matches the SCHEDULED keyword together with a time stamp.")
  387. (defconst org-scheduled-time-hour-regexp
  388. (concat "\\<" org-scheduled-string
  389. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  390. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  391. (defconst org-closed-time-regexp
  392. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  393. "Matches the CLOSED keyword together with a time stamp.")
  394. (defconst org-keyword-time-regexp
  395. (concat "\\<"
  396. (regexp-opt
  397. (list org-scheduled-string org-deadline-string org-closed-string
  398. org-clock-string)
  399. t)
  400. " *[[<]\\([^]>]+\\)[]>]")
  401. "Matches any of the 4 keywords, together with the time stamp.")
  402. (defconst org-keyword-time-not-clock-regexp
  403. (concat
  404. "\\<"
  405. (regexp-opt
  406. (list org-scheduled-string org-deadline-string org-closed-string) t)
  407. " *[[<]\\([^]>]+\\)[]>]")
  408. "Matches any of the 3 keywords, together with the time stamp.")
  409. (defconst org-maybe-keyword-time-regexp
  410. (concat "\\(\\<"
  411. (regexp-opt
  412. (list org-scheduled-string org-deadline-string org-closed-string
  413. org-clock-string)
  414. t)
  415. "\\)?"
  416. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  417. "\\|"
  418. "<%%([^\r\n>]*>\\)")
  419. "Matches a timestamp, possibly preceded by a keyword.")
  420. (defconst org-all-time-keywords
  421. (mapcar (lambda (w) (substring w 0 -1))
  422. (list org-scheduled-string org-deadline-string
  423. org-clock-string org-closed-string))
  424. "List of time keywords.")
  425. ;;;; Drawer
  426. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  427. "Matches first or last line of a hidden block.
  428. Group 1 contains drawer's name or \"END\".")
  429. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  430. "Regular expression matching the first line of a property drawer.")
  431. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a property drawer.")
  433. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  434. "Regular expression matching the first line of a clock drawer.")
  435. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  436. "Regular expression matching the last line of a clock drawer.")
  437. (defconst org-property-drawer-re
  438. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  439. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  440. "[ \t]*:END:[ \t]*$")
  441. "Matches an entire property drawer.")
  442. (defconst org-clock-drawer-re
  443. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  444. org-clock-drawer-end-re "\\)\n?")
  445. "Matches an entire clock drawer.")
  446. ;;;; Headline
  447. (defconst org-heading-keyword-regexp-format
  448. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  449. "Printf format for a regexp matching a headline with some keyword.
  450. This regexp will match the headline of any node which has the
  451. exact keyword that is put into the format. The keyword isn't in
  452. any group by default, but the stars and the body are.")
  453. (defconst org-heading-keyword-maybe-regexp-format
  454. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  455. "Printf format for a regexp matching a headline, possibly with some keyword.
  456. This regexp can match any headline with the specified keyword, or
  457. without a keyword. The keyword isn't in any group by default,
  458. but the stars and the body are.")
  459. (defconst org-archive-tag "ARCHIVE"
  460. "The tag that marks a subtree as archived.
  461. An archived subtree does not open during visibility cycling, and does
  462. not contribute to the agenda listings.")
  463. (eval-and-compile
  464. (defconst org-comment-string "COMMENT"
  465. "Entries starting with this keyword will never be exported.
  466. \\<org-mode-map>
  467. An entry can be toggled between COMMENT and normal with
  468. `\\[org-toggle-comment]'."))
  469. ;;;; LaTeX Environments and Fragments
  470. (defconst org-latex-regexps
  471. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  472. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  473. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  474. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  475. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  476. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  477. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  478. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  479. "Regular expressions for matching embedded LaTeX.")
  480. ;;;; Node Property
  481. (defconst org-effort-property "Effort"
  482. "The property that is being used to keep track of effort estimates.
  483. Effort estimates given in this property need to have the format H:MM.")
  484. ;;;; Table
  485. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  486. "Detect an org-type or table-type table.")
  487. (defconst org-table-line-regexp "^[ \t]*|"
  488. "Detect an org-type table line.")
  489. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  490. "Detect an org-type table line.")
  491. (defconst org-table-hline-regexp "^[ \t]*|-"
  492. "Detect an org-type table hline.")
  493. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  494. "Detect a table-type table hline.")
  495. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  496. "Detect the first line outside a table when searching from within it.
  497. This works for both table types.")
  498. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  499. "Detect a #+TBLFM line.")
  500. ;;;; Timestamp
  501. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  502. "Regular expression for fast time stamp matching.")
  503. (defconst org-ts-regexp-inactive
  504. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  505. "Regular expression for fast inactive time stamp matching.")
  506. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  507. "Regular expression for fast time stamp matching.")
  508. (defconst org-ts-regexp0
  509. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.
  511. This one does not require the space after the date, so it can be used
  512. on a string that terminates immediately after the date.")
  513. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  514. "Regular expression matching time strings for analysis.")
  515. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  516. "Regular expression matching time stamps, with groups.")
  517. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  518. "Regular expression matching time stamps (also [..]), with groups.")
  519. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tr-regexp-both
  522. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  523. "Regular expression matching a time stamp range.")
  524. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  525. org-ts-regexp "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.")
  527. (defconst org-tsr-regexp-both
  528. (concat org-ts-regexp-both "\\(--?-?"
  529. org-ts-regexp-both "\\)?")
  530. "Regular expression matching a time stamp or time stamp range.
  531. The time stamps may be either active or inactive.")
  532. (defconst org-repeat-re
  533. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  534. "Regular expression for specifying repeated events.
  535. After a match, group 1 contains the repeat expression.")
  536. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  537. "Formats for `format-time-string' which are used for time stamps.")
  538. ;;; The custom variables
  539. (defgroup org nil
  540. "Outline-based notes management and organizer."
  541. :tag "Org"
  542. :group 'outlines
  543. :group 'calendar)
  544. (defcustom org-mode-hook nil
  545. "Mode hook for Org mode, run after the mode was turned on."
  546. :group 'org
  547. :type 'hook)
  548. (defcustom org-load-hook nil
  549. "Hook that is run after org.el has been loaded."
  550. :group 'org
  551. :type 'hook)
  552. (defcustom org-log-buffer-setup-hook nil
  553. "Hook that is run after an Org log buffer is created."
  554. :group 'org
  555. :version "24.1"
  556. :type 'hook)
  557. (defvar org-modules) ; defined below
  558. (defvar org-modules-loaded nil
  559. "Have the modules been loaded already?")
  560. (defun org-load-modules-maybe (&optional force)
  561. "Load all extensions listed in `org-modules'."
  562. (when (or force (not org-modules-loaded))
  563. (dolist (ext org-modules)
  564. (condition-case nil (require ext)
  565. (error (message "Problems while trying to load feature `%s'" ext))))
  566. (setq org-modules-loaded t)))
  567. (defun org-set-modules (var value)
  568. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  569. (set var value)
  570. (when (featurep 'org)
  571. (org-load-modules-maybe 'force)
  572. (org-element-cache-reset 'all)))
  573. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  574. "Modules that should always be loaded together with org.el.
  575. If a description starts with <C>, the file is not part of Emacs
  576. and loading it will require that you have downloaded and properly
  577. installed the Org mode distribution.
  578. You can also use this system to load external packages (i.e. neither Org
  579. core modules, nor modules from the CONTRIB directory). Just add symbols
  580. to the end of the list. If the package is called org-xyz.el, then you need
  581. to add the symbol `xyz', and the package must have a call to:
  582. (provide \\='org-xyz)
  583. For export specific modules, see also `org-export-backends'."
  584. :group 'org
  585. :set 'org-set-modules
  586. :version "24.4"
  587. :package-version '(Org . "8.0")
  588. :type
  589. '(set :greedy t
  590. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  591. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  592. (const :tag " crypt: Encryption of subtrees" org-crypt)
  593. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  594. (const :tag " docview: Links to doc-view buffers" org-docview)
  595. (const :tag " eww: Store link to url of eww" org-eww)
  596. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  597. (const :tag " habit: Track your consistency with habits" org-habit)
  598. (const :tag " id: Global IDs for identifying entries" org-id)
  599. (const :tag " info: Links to Info nodes" org-info)
  600. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  601. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  602. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  603. (const :tag " mouse: Additional mouse support" org-mouse)
  604. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  605. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  606. (const :tag " tempo: Fast completion for structures" org-tempo)
  607. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  608. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  609. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  610. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  611. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  612. (const :tag "C collector: Collect properties into tables" org-collector)
  613. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  614. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  615. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  616. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  617. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  618. (const :tag "C eval: Include command output as text" org-eval)
  619. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  620. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  621. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  622. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  623. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  624. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  625. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  626. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  627. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  628. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  629. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  630. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  631. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  632. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  633. (const :tag "C registry: A registry for Org links" org-registry)
  634. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  635. (const :tag "C secretary: Team management with org-mode" org-secretary)
  636. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  637. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  638. (const :tag "C track: Keep up with Org mode development" org-track)
  639. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  640. (const :tag "C vm: Links to VM folders/messages" org-vm)
  641. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  642. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  643. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  644. (defvar org-export-registered-backends) ; From ox.el.
  645. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  646. (declare-function org-export-backend-name "ox" (backend) t)
  647. (defcustom org-export-backends '(ascii html icalendar latex odt)
  648. "List of export back-ends that should be always available.
  649. If a description starts with <C>, the file is not part of Emacs
  650. and loading it will require that you have downloaded and properly
  651. installed the Org mode distribution.
  652. Unlike to `org-modules', libraries in this list will not be
  653. loaded along with Org, but only once the export framework is
  654. needed.
  655. This variable needs to be set before org.el is loaded. If you
  656. need to make a change while Emacs is running, use the customize
  657. interface or run the following code, where VAL stands for the new
  658. value of the variable, after updating it:
  659. (progn
  660. (setq org-export-registered-backends
  661. (cl-remove-if-not
  662. (lambda (backend)
  663. (let ((name (org-export-backend-name backend)))
  664. (or (memq name val)
  665. (catch \\='parentp
  666. (dolist (b val)
  667. (and (org-export-derived-backend-p b name)
  668. (throw \\='parentp t)))))))
  669. org-export-registered-backends))
  670. (let ((new-list (mapcar #\\='org-export-backend-name
  671. org-export-registered-backends)))
  672. (dolist (backend val)
  673. (cond
  674. ((not (load (format \"ox-%s\" backend) t t))
  675. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  676. backend))
  677. ((not (memq backend new-list)) (push backend new-list))))
  678. (set-default \\='org-export-backends new-list)))
  679. Adding a back-end to this list will also pull the back-end it
  680. depends on, if any."
  681. :group 'org
  682. :group 'org-export
  683. :version "26.1"
  684. :package-version '(Org . "9.0")
  685. :initialize 'custom-initialize-set
  686. :set (lambda (var val)
  687. (if (not (featurep 'ox)) (set-default var val)
  688. ;; Any back-end not required anymore (not present in VAL and not
  689. ;; a parent of any back-end in the new value) is removed from the
  690. ;; list of registered back-ends.
  691. (setq org-export-registered-backends
  692. (cl-remove-if-not
  693. (lambda (backend)
  694. (let ((name (org-export-backend-name backend)))
  695. (or (memq name val)
  696. (catch 'parentp
  697. (dolist (b val)
  698. (and (org-export-derived-backend-p b name)
  699. (throw 'parentp t)))))))
  700. org-export-registered-backends))
  701. ;; Now build NEW-LIST of both new back-ends and required
  702. ;; parents.
  703. (let ((new-list (mapcar #'org-export-backend-name
  704. org-export-registered-backends)))
  705. (dolist (backend val)
  706. (cond
  707. ((not (load (format "ox-%s" backend) t t))
  708. (message "Problems while trying to load export back-end `%s'"
  709. backend))
  710. ((not (memq backend new-list)) (push backend new-list))))
  711. ;; Set VAR to that list with fixed dependencies.
  712. (set-default var new-list))))
  713. :type '(set :greedy t
  714. (const :tag " ascii Export buffer to ASCII format" ascii)
  715. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  716. (const :tag " html Export buffer to HTML format" html)
  717. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  718. (const :tag " latex Export buffer to LaTeX format" latex)
  719. (const :tag " man Export buffer to MAN format" man)
  720. (const :tag " md Export buffer to Markdown format" md)
  721. (const :tag " odt Export buffer to ODT format" odt)
  722. (const :tag " org Export buffer to Org format" org)
  723. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  724. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  725. (const :tag "C deck Export buffer to deck.js presentations" deck)
  726. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  727. (const :tag "C groff Export buffer to Groff format" groff)
  728. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  729. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  730. (const :tag "C s5 Export buffer to s5 presentations" s5)
  731. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  732. (eval-after-load 'ox
  733. '(dolist (backend org-export-backends)
  734. (condition-case nil (require (intern (format "ox-%s" backend)))
  735. (error (message "Problems while trying to load export back-end `%s'"
  736. backend)))))
  737. (defcustom org-support-shift-select nil
  738. "Non-nil means make shift-cursor commands select text when possible.
  739. \\<org-mode-map>\
  740. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  741. start selecting a region, or enlarge regions started in this way.
  742. In Org mode, in special contexts, these same keys are used for
  743. other purposes, important enough to compete with shift selection.
  744. Org tries to balance these needs by supporting `shift-select-mode'
  745. outside these special contexts, under control of this variable.
  746. The default of this variable is nil, to avoid confusing behavior. Shifted
  747. cursor keys will then execute Org commands in the following contexts:
  748. - on a headline, changing TODO state (left/right) and priority (up/down)
  749. - on a time stamp, changing the time
  750. - in a plain list item, changing the bullet type
  751. - in a property definition line, switching between allowed values
  752. - in the BEGIN line of a clock table (changing the time block).
  753. Outside these contexts, the commands will throw an error.
  754. When this variable is t and the cursor is not in a special
  755. context, Org mode will support shift-selection for making and
  756. enlarging regions. To make this more effective, the bullet
  757. cycling will no longer happen anywhere in an item line, but only
  758. if the cursor is exactly on the bullet.
  759. If you set this variable to the symbol `always', then the keys
  760. will not be special in headlines, property lines, and item lines,
  761. to make shift selection work there as well. If this is what you
  762. want, you can use the following alternative commands:
  763. `\\[org-todo]' and `\\[org-priority]' \
  764. to change TODO state and priority,
  765. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  766. can be used to switch TODO sets,
  767. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  768. and properties can be edited by hand or in column view.
  769. However, when the cursor is on a timestamp, shift-cursor commands
  770. will still edit the time stamp - this is just too good to give up."
  771. :group 'org
  772. :type '(choice
  773. (const :tag "Never" nil)
  774. (const :tag "When outside special context" t)
  775. (const :tag "Everywhere except timestamps" always)))
  776. (defcustom org-loop-over-headlines-in-active-region nil
  777. "Shall some commands act upon headlines in the active region?
  778. When set to t, some commands will be performed in all headlines
  779. within the active region.
  780. When set to `start-level', some commands will be performed in all
  781. headlines within the active region, provided that these headlines
  782. are of the same level than the first one.
  783. When set to a string, those commands will be performed on the
  784. matching headlines within the active region. Such string must be
  785. a tags/property/todo match as it is used in the agenda tags view.
  786. The list of commands is: `org-schedule', `org-deadline',
  787. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  788. `org-archive-to-archive-sibling'. The archiving commands skip
  789. already archived entries."
  790. :type '(choice (const :tag "Don't loop" nil)
  791. (const :tag "All headlines in active region" t)
  792. (const :tag "In active region, headlines at the same level than the first one" start-level)
  793. (string :tag "Tags/Property/Todo matcher"))
  794. :version "24.1"
  795. :group 'org-todo
  796. :group 'org-archive)
  797. (defcustom org-startup-folded t
  798. "Non-nil means entering Org mode will switch to OVERVIEW.
  799. This can also be configured on a per-file basis by adding one of
  800. the following lines anywhere in the buffer:
  801. #+STARTUP: fold (or `overview', this is equivalent)
  802. #+STARTUP: nofold (or `showall', this is equivalent)
  803. #+STARTUP: content
  804. #+STARTUP: showeverything
  805. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  806. to ignore this option when Org opens agenda files for the first
  807. time."
  808. :group 'org-startup
  809. :type '(choice
  810. (const :tag "nofold: show all" nil)
  811. (const :tag "fold: overview" t)
  812. (const :tag "content: all headlines" content)
  813. (const :tag "show everything, even drawers" showeverything)))
  814. (defcustom org-startup-truncated t
  815. "Non-nil means entering Org mode will set `truncate-lines'.
  816. This is useful since some lines containing links can be very long and
  817. uninteresting. Also tables look terrible when wrapped.
  818. The variable `org-startup-truncated' allows to configure
  819. truncation for Org mode different to the other modes that use the
  820. variable `truncate-lines' and as a shortcut instead of putting
  821. the variable `truncate-lines' into the `org-mode-hook'. If one
  822. wants to configure truncation for Org mode not statically but
  823. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  824. the variable `truncate-lines' has to be used because in such a
  825. case it is too late to set the variable `org-startup-truncated'."
  826. :group 'org-startup
  827. :type 'boolean)
  828. (defcustom org-startup-indented nil
  829. "Non-nil means turn on `org-indent-mode' on startup.
  830. This can also be configured on a per-file basis by adding one of
  831. the following lines anywhere in the buffer:
  832. #+STARTUP: indent
  833. #+STARTUP: noindent"
  834. :group 'org-structure
  835. :type '(choice
  836. (const :tag "Not" nil)
  837. (const :tag "Globally (slow on startup in large files)" t)))
  838. (defcustom org-use-sub-superscripts t
  839. "Non-nil means interpret \"_\" and \"^\" for display.
  840. If you want to control how Org exports those characters, see
  841. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  842. used to be an alias for `org-export-with-sub-superscripts' in
  843. Org <8.0, it is not anymore.
  844. When this option is turned on, you can use TeX-like syntax for
  845. sub- and superscripts within the buffer. Several characters after
  846. \"_\" or \"^\" will be considered as a single item - so grouping
  847. with {} is normally not needed. For example, the following things
  848. will be parsed as single sub- or superscripts:
  849. 10^24 or 10^tau several digits will be considered 1 item.
  850. 10^-12 or 10^-tau a leading sign with digits or a word
  851. x^2-y^3 will be read as x^2 - y^3, because items are
  852. terminated by almost any nonword/nondigit char.
  853. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  854. Still, ambiguity is possible. So when in doubt, use {} to enclose
  855. the sub/superscript. If you set this variable to the symbol `{}',
  856. the braces are *required* in order to trigger interpretations as
  857. sub/superscript. This can be helpful in documents that need \"_\"
  858. frequently in plain text."
  859. :group 'org-startup
  860. :version "24.4"
  861. :package-version '(Org . "8.0")
  862. :type '(choice
  863. (const :tag "Always interpret" t)
  864. (const :tag "Only with braces" {})
  865. (const :tag "Never interpret" nil)))
  866. (defcustom org-startup-with-beamer-mode nil
  867. "Non-nil means turn on `org-beamer-mode' on startup.
  868. This can also be configured on a per-file basis by adding one of
  869. the following lines anywhere in the buffer:
  870. #+STARTUP: beamer"
  871. :group 'org-startup
  872. :version "24.1"
  873. :type 'boolean)
  874. (defcustom org-startup-align-all-tables nil
  875. "Non-nil means align all tables when visiting a file.
  876. This can also be configured on a per-file basis by adding one of
  877. the following lines anywhere in the buffer:
  878. #+STARTUP: align
  879. #+STARTUP: noalign"
  880. :group 'org-startup
  881. :type 'boolean)
  882. (defcustom org-startup-shrink-all-tables nil
  883. "Non-nil means shrink all table columns with a width cookie.
  884. This can also be configured on a per-file basis by adding one of
  885. the following lines anywhere in the buffer:
  886. #+STARTUP: shrink"
  887. :group 'org-startup
  888. :type 'boolean
  889. :version "27.1"
  890. :package-version '(Org . "9.2")
  891. :safe #'booleanp)
  892. (defcustom org-startup-with-inline-images nil
  893. "Non-nil means show inline images when loading a new Org file.
  894. This can also be configured on a per-file basis by adding one of
  895. the following lines anywhere in the buffer:
  896. #+STARTUP: inlineimages
  897. #+STARTUP: noinlineimages"
  898. :group 'org-startup
  899. :version "24.1"
  900. :type 'boolean)
  901. (defcustom org-startup-with-latex-preview nil
  902. "Non-nil means preview LaTeX fragments when loading a new Org file.
  903. This can also be configured on a per-file basis by adding one of
  904. the following lines anywhere in the buffer:
  905. #+STARTUP: latexpreview
  906. #+STARTUP: nolatexpreview"
  907. :group 'org-startup
  908. :version "24.4"
  909. :package-version '(Org . "8.0")
  910. :type 'boolean)
  911. (defcustom org-insert-mode-line-in-empty-file nil
  912. "Non-nil means insert the first line setting Org mode in empty files.
  913. When the function `org-mode' is called interactively in an empty file, this
  914. normally means that the file name does not automatically trigger Org mode.
  915. To ensure that the file will always be in Org mode in the future, a
  916. line enforcing Org mode will be inserted into the buffer, if this option
  917. has been set."
  918. :group 'org-startup
  919. :type 'boolean)
  920. (defcustom org-replace-disputed-keys nil
  921. "Non-nil means use alternative key bindings for some keys.
  922. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  923. These keys are also used by other packages like shift-selection-mode'
  924. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  925. If you want to use Org mode together with one of these other modes,
  926. or more generally if you would like to move some Org mode commands to
  927. other keys, set this variable and configure the keys with the variable
  928. `org-disputed-keys'.
  929. This option is only relevant at load-time of Org mode, and must be set
  930. *before* org.el is loaded. Changing it requires a restart of Emacs to
  931. become effective."
  932. :group 'org-startup
  933. :type 'boolean)
  934. (defcustom org-use-extra-keys nil
  935. "Non-nil means use extra key sequence definitions for certain commands.
  936. This happens automatically if `window-system' is nil. This
  937. variable lets you do the same manually. You must set it before
  938. loading Org."
  939. :group 'org-startup
  940. :type 'boolean)
  941. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  942. (defcustom org-disputed-keys
  943. '(([(shift up)] . [(meta p)])
  944. ([(shift down)] . [(meta n)])
  945. ([(shift left)] . [(meta -)])
  946. ([(shift right)] . [(meta +)])
  947. ([(control shift right)] . [(meta shift +)])
  948. ([(control shift left)] . [(meta shift -)]))
  949. "Keys for which Org mode and other modes compete.
  950. This is an alist, cars are the default keys, second element specifies
  951. the alternative to use when `org-replace-disputed-keys' is t.
  952. Keys can be specified in any syntax supported by `define-key'.
  953. The value of this option takes effect only at Org mode startup,
  954. therefore you'll have to restart Emacs to apply it after changing."
  955. :group 'org-startup
  956. :type 'alist)
  957. (defun org-key (key)
  958. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  959. Or return the original if not disputed."
  960. (when org-replace-disputed-keys
  961. (let* ((nkey (key-description key))
  962. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  963. org-disputed-keys)))
  964. (setq key (if x (cdr x) key))))
  965. key)
  966. (defun org-defkey (keymap key def)
  967. "Define a key, possibly translated, as returned by `org-key'."
  968. (define-key keymap (org-key key) def))
  969. (defcustom org-ellipsis nil
  970. "The ellipsis to use in the Org mode outline.
  971. When nil, just use the standard three dots. When a non-empty string,
  972. use that string instead.
  973. The change affects only Org mode (which will then use its own display table).
  974. Changing this requires executing `\\[org-mode]' in a buffer to become
  975. effective."
  976. :group 'org-startup
  977. :type '(choice (const :tag "Default" nil)
  978. (string :tag "String" :value "...#"))
  979. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  980. (defvar org-display-table nil
  981. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  982. (defgroup org-keywords nil
  983. "Keywords in Org mode."
  984. :tag "Org Keywords"
  985. :group 'org)
  986. (defcustom org-closed-keep-when-no-todo nil
  987. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  988. :group 'org-todo
  989. :group 'org-keywords
  990. :version "24.4"
  991. :package-version '(Org . "8.0")
  992. :type 'boolean)
  993. (defgroup org-structure nil
  994. "Options concerning the general structure of Org files."
  995. :tag "Org Structure"
  996. :group 'org)
  997. (defgroup org-reveal-location nil
  998. "Options about how to make context of a location visible."
  999. :tag "Org Reveal Location"
  1000. :group 'org-structure)
  1001. (defcustom org-show-context-detail '((agenda . local)
  1002. (bookmark-jump . lineage)
  1003. (isearch . lineage)
  1004. (default . ancestors))
  1005. "Alist between context and visibility span when revealing a location.
  1006. \\<org-mode-map>Some actions may move point into invisible
  1007. locations. As a consequence, Org always expose a neighborhood
  1008. around point. How much is shown depends on the initial action,
  1009. or context. Valid contexts are
  1010. agenda when exposing an entry from the agenda
  1011. org-goto when using the command `org-goto' (`\\[org-goto]')
  1012. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1013. tags-tree when constructing a sparse tree based on tags matches
  1014. link-search when exposing search matches associated with a link
  1015. mark-goto when exposing the jump goal of a mark
  1016. bookmark-jump when exposing a bookmark location
  1017. isearch when exiting from an incremental search
  1018. default default for all contexts not set explicitly
  1019. Allowed visibility spans are
  1020. minimal show current headline; if point is not on headline,
  1021. also show entry
  1022. local show current headline, entry and next headline
  1023. ancestors show current headline and its direct ancestors; if
  1024. point is not on headline, also show entry
  1025. lineage show current headline, its direct ancestors and all
  1026. their children; if point is not on headline, also show
  1027. entry and first child
  1028. tree show current headline, its direct ancestors and all
  1029. their children; if point is not on headline, also show
  1030. entry and all children
  1031. canonical show current headline, its direct ancestors along with
  1032. their entries and children; if point is not located on
  1033. the headline, also show current entry and all children
  1034. As special cases, a nil or t value means show all contexts in
  1035. `minimal' or `canonical' view, respectively.
  1036. Some views can make displayed information very compact, but also
  1037. make it harder to edit the location of the match. In such
  1038. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1039. more context."
  1040. :group 'org-reveal-location
  1041. :version "26.1"
  1042. :package-version '(Org . "9.0")
  1043. :type '(choice
  1044. (const :tag "Canonical" t)
  1045. (const :tag "Minimal" nil)
  1046. (repeat :greedy t :tag "Individual contexts"
  1047. (cons
  1048. (choice :tag "Context"
  1049. (const agenda)
  1050. (const org-goto)
  1051. (const occur-tree)
  1052. (const tags-tree)
  1053. (const link-search)
  1054. (const mark-goto)
  1055. (const bookmark-jump)
  1056. (const isearch)
  1057. (const default))
  1058. (choice :tag "Detail level"
  1059. (const minimal)
  1060. (const local)
  1061. (const ancestors)
  1062. (const lineage)
  1063. (const tree)
  1064. (const canonical))))))
  1065. (defcustom org-indirect-buffer-display 'other-window
  1066. "How should indirect tree buffers be displayed?
  1067. This applies to indirect buffers created with the commands
  1068. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1069. Valid values are:
  1070. current-window Display in the current window
  1071. other-window Just display in another window.
  1072. dedicated-frame Create one new frame, and re-use it each time.
  1073. new-frame Make a new frame each time. Note that in this case
  1074. previously-made indirect buffers are kept, and you need to
  1075. kill these buffers yourself."
  1076. :group 'org-structure
  1077. :group 'org-agenda-windows
  1078. :type '(choice
  1079. (const :tag "In current window" current-window)
  1080. (const :tag "In current frame, other window" other-window)
  1081. (const :tag "Each time a new frame" new-frame)
  1082. (const :tag "One dedicated frame" dedicated-frame)))
  1083. (defcustom org-use-speed-commands nil
  1084. "Non-nil means activate single letter commands at beginning of a headline.
  1085. This may also be a function to test for appropriate locations where speed
  1086. commands should be active.
  1087. For example, to activate speed commands when the point is on any
  1088. star at the beginning of the headline, you can do this:
  1089. (setq org-use-speed-commands
  1090. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1091. :group 'org-structure
  1092. :type '(choice
  1093. (const :tag "Never" nil)
  1094. (const :tag "At beginning of headline stars" t)
  1095. (function)))
  1096. (defcustom org-speed-commands-user nil
  1097. "Alist of additional speed commands.
  1098. This list will be checked before `org-speed-commands-default'
  1099. when the variable `org-use-speed-commands' is non-nil
  1100. and when the cursor is at the beginning of a headline.
  1101. The car of each entry is a string with a single letter, which must
  1102. be assigned to `self-insert-command' in the global map.
  1103. The cdr is either a command to be called interactively, a function
  1104. to be called, or a form to be evaluated.
  1105. An entry that is just a list with a single string will be interpreted
  1106. as a descriptive headline that will be added when listing the speed
  1107. commands in the Help buffer using the `?' speed command."
  1108. :group 'org-structure
  1109. :type '(repeat :value ("k" . ignore)
  1110. (choice :value ("k" . ignore)
  1111. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1112. (cons :tag "Letter and Command"
  1113. (string :tag "Command letter")
  1114. (choice
  1115. (function)
  1116. (sexp))))))
  1117. (defcustom org-bookmark-names-plist
  1118. '(:last-capture "org-capture-last-stored"
  1119. :last-refile "org-refile-last-stored"
  1120. :last-capture-marker "org-capture-last-stored-marker")
  1121. "Names for bookmarks automatically set by some Org commands.
  1122. This can provide strings as names for a number of bookmarks Org sets
  1123. automatically. The following keys are currently implemented:
  1124. :last-capture
  1125. :last-capture-marker
  1126. :last-refile
  1127. When a key does not show up in the property list, the corresponding bookmark
  1128. is not set."
  1129. :group 'org-structure
  1130. :type 'plist)
  1131. (defgroup org-cycle nil
  1132. "Options concerning visibility cycling in Org mode."
  1133. :tag "Org Cycle"
  1134. :group 'org-structure)
  1135. (defcustom org-cycle-skip-children-state-if-no-children t
  1136. "Non-nil means skip CHILDREN state in entries that don't have any."
  1137. :group 'org-cycle
  1138. :type 'boolean)
  1139. (defcustom org-cycle-max-level nil
  1140. "Maximum level which should still be subject to visibility cycling.
  1141. Levels higher than this will, for cycling, be treated as text, not a headline.
  1142. When `org-odd-levels-only' is set, a value of N in this variable actually
  1143. means 2N-1 stars as the limiting headline.
  1144. When nil, cycle all levels.
  1145. Note that the limiting level of cycling is also influenced by
  1146. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1147. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1148. than its value."
  1149. :group 'org-cycle
  1150. :type '(choice
  1151. (const :tag "No limit" nil)
  1152. (integer :tag "Maximum level")))
  1153. (defcustom org-hide-block-startup nil
  1154. "Non-nil means entering Org mode will fold all blocks.
  1155. This can also be set in on a per-file basis with
  1156. #+STARTUP: hideblocks
  1157. #+STARTUP: showblocks"
  1158. :group 'org-startup
  1159. :group 'org-cycle
  1160. :type 'boolean)
  1161. (defcustom org-cycle-global-at-bob nil
  1162. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1163. This makes it possible to do global cycling without having to use `S-TAB'
  1164. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1165. line of the buffer
  1166. must not be a headline -- it may be empty or some other text.
  1167. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1168. sure the cursor stays at the beginning of the buffer.
  1169. When this option is nil, don't do anything special at the beginning of
  1170. the buffer."
  1171. :group 'org-cycle
  1172. :type 'boolean)
  1173. (defcustom org-cycle-level-after-item/entry-creation t
  1174. "Non-nil means cycle entry level or item indentation in new empty entries.
  1175. When the cursor is at the end of an empty headline, i.e., with only stars
  1176. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1177. and then all possible ancestor states, before returning to the original state.
  1178. This makes data entry extremely fast: M-RET to create a new headline,
  1179. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1180. When the cursor is at the end of an empty plain list item, one TAB will
  1181. make it a subitem, two or more tabs will back up to make this an item
  1182. higher up in the item hierarchy."
  1183. :group 'org-cycle
  1184. :type 'boolean)
  1185. (defcustom org-cycle-emulate-tab t
  1186. "Where should `org-cycle' emulate TAB.
  1187. nil Never
  1188. white Only in completely white lines
  1189. whitestart Only at the beginning of lines, before the first non-white char
  1190. t Everywhere except in headlines
  1191. exc-hl-bol Everywhere except at the start of a headline
  1192. If TAB is used in a place where it does not emulate TAB, the current subtree
  1193. visibility is cycled."
  1194. :group 'org-cycle
  1195. :type '(choice (const :tag "Never" nil)
  1196. (const :tag "Only in completely white lines" white)
  1197. (const :tag "Before first char in a line" whitestart)
  1198. (const :tag "Everywhere except in headlines" t)
  1199. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1200. (defcustom org-cycle-separator-lines 2
  1201. "Number of empty lines needed to keep an empty line between collapsed trees.
  1202. If you leave an empty line between the end of a subtree and the following
  1203. headline, this empty line is hidden when the subtree is folded.
  1204. Org mode will leave (exactly) one empty line visible if the number of
  1205. empty lines is equal or larger to the number given in this variable.
  1206. So the default 2 means at least 2 empty lines after the end of a subtree
  1207. are needed to produce free space between a collapsed subtree and the
  1208. following headline.
  1209. If the number is negative, and the number of empty lines is at least -N,
  1210. all empty lines are shown.
  1211. Special case: when 0, never leave empty lines in collapsed view."
  1212. :group 'org-cycle
  1213. :type 'integer)
  1214. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1215. (defcustom org-pre-cycle-hook nil
  1216. "Hook that is run before visibility cycling is happening.
  1217. The function(s) in this hook must accept a single argument which indicates
  1218. the new state that will be set right after running this hook. The
  1219. argument is a symbol. Before a global state change, it can have the values
  1220. `overview', `content', or `all'. Before a local state change, it can have
  1221. the values `folded', `children', or `subtree'."
  1222. :group 'org-cycle
  1223. :type 'hook)
  1224. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1225. org-cycle-hide-drawers
  1226. org-cycle-show-empty-lines
  1227. org-optimize-window-after-visibility-change)
  1228. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1229. The function(s) in this hook must accept a single argument which indicates
  1230. the new state that was set by the most recent `org-cycle' command. The
  1231. argument is a symbol. After a global state change, it can have the values
  1232. `overview', `contents', or `all'. After a local state change, it can have
  1233. the values `folded', `children', or `subtree'."
  1234. :group 'org-cycle
  1235. :type 'hook
  1236. :version "26.1"
  1237. :package-version '(Org . "8.3"))
  1238. (defgroup org-edit-structure nil
  1239. "Options concerning structure editing in Org mode."
  1240. :tag "Org Edit Structure"
  1241. :group 'org-structure)
  1242. (defcustom org-odd-levels-only nil
  1243. "Non-nil means skip even levels and only use odd levels for the outline.
  1244. This has the effect that two stars are being added/taken away in
  1245. promotion/demotion commands. It also influences how levels are
  1246. handled by the exporters.
  1247. Changing it requires restart of `font-lock-mode' to become effective
  1248. for fontification also in regions already fontified.
  1249. You may also set this on a per-file basis by adding one of the following
  1250. lines to the buffer:
  1251. #+STARTUP: odd
  1252. #+STARTUP: oddeven"
  1253. :group 'org-edit-structure
  1254. :group 'org-appearance
  1255. :type 'boolean)
  1256. (defcustom org-adapt-indentation t
  1257. "Non-nil means adapt indentation to outline node level.
  1258. When this variable is set, Org assumes that you write outlines by
  1259. indenting text in each node to align with the headline (after the
  1260. stars). The following issues are influenced by this variable:
  1261. - The indentation is increased by one space in a demotion
  1262. command, and decreased by one in a promotion command. However,
  1263. in the latter case, if shifting some line in the entry body
  1264. would alter document structure (e.g., insert a new headline),
  1265. indentation is not changed at all.
  1266. - Property drawers and planning information is inserted indented
  1267. when this variable is set. When nil, they will not be indented.
  1268. - TAB indents a line relative to current level. The lines below
  1269. a headline will be indented when this variable is set.
  1270. Note that this is all about true indentation, by adding and
  1271. removing space characters. See also \"org-indent.el\" which does
  1272. level-dependent indentation in a virtual way, i.e. at display
  1273. time in Emacs."
  1274. :group 'org-edit-structure
  1275. :type 'boolean
  1276. :safe #'booleanp)
  1277. (defcustom org-special-ctrl-a/e nil
  1278. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1279. When t, `C-a' will bring back the cursor to the beginning of the
  1280. headline text, i.e. after the stars and after a possible TODO
  1281. keyword. In an item, this will be the position after bullet and
  1282. check-box, if any. When the cursor is already at that position,
  1283. another `C-a' will bring it to the beginning of the line.
  1284. `C-e' will jump to the end of the headline, ignoring the presence
  1285. of tags in the headline. A second `C-e' will then jump to the
  1286. true end of the line, after any tags. This also means that, when
  1287. this variable is non-nil, `C-e' also will never jump beyond the
  1288. end of the heading of a folded section, i.e. not after the
  1289. ellipses.
  1290. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1291. normally, going to the true line boundary first. Only a directly
  1292. following, identical keypress will bring the cursor to the
  1293. special positions.
  1294. This may also be a cons cell where the behavior for `C-a' and
  1295. `C-e' is set separately."
  1296. :group 'org-edit-structure
  1297. :type '(choice
  1298. (const :tag "off" nil)
  1299. (const :tag "on: after stars/bullet and before tags first" t)
  1300. (const :tag "reversed: true line boundary first" reversed)
  1301. (cons :tag "Set C-a and C-e separately"
  1302. (choice :tag "Special C-a"
  1303. (const :tag "off" nil)
  1304. (const :tag "on: after stars/bullet first" t)
  1305. (const :tag "reversed: before stars/bullet first" reversed))
  1306. (choice :tag "Special C-e"
  1307. (const :tag "off" nil)
  1308. (const :tag "on: before tags first" t)
  1309. (const :tag "reversed: after tags first" reversed)))))
  1310. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1311. (defcustom org-special-ctrl-k nil
  1312. "Non-nil means `C-k' will behave specially in headlines.
  1313. When nil, `C-k' will call the default `kill-line' command.
  1314. When t, the following will happen while the cursor is in the headline:
  1315. - When the cursor is at the beginning of a headline, kill the entire
  1316. line and possible the folded subtree below the line.
  1317. - When in the middle of the headline text, kill the headline up to the tags.
  1318. - When after the headline text, kill the tags."
  1319. :group 'org-edit-structure
  1320. :type 'boolean)
  1321. (defcustom org-ctrl-k-protect-subtree nil
  1322. "Non-nil means, do not delete a hidden subtree with C-k.
  1323. When set to the symbol `error', simply throw an error when C-k is
  1324. used to kill (part-of) a headline that has hidden text behind it.
  1325. Any other non-nil value will result in a query to the user, if it is
  1326. OK to kill that hidden subtree. When nil, kill without remorse."
  1327. :group 'org-edit-structure
  1328. :version "24.1"
  1329. :type '(choice
  1330. (const :tag "Do not protect hidden subtrees" nil)
  1331. (const :tag "Protect hidden subtrees with a security query" t)
  1332. (const :tag "Never kill a hidden subtree with C-k" error)))
  1333. (defcustom org-special-ctrl-o t
  1334. "Non-nil means, make `C-o' insert a row in tables."
  1335. :group 'org-edit-structure
  1336. :type 'boolean)
  1337. (defcustom org-catch-invisible-edits nil
  1338. "Check if in invisible region before inserting or deleting a character.
  1339. Valid values are:
  1340. nil Do not check, so just do invisible edits.
  1341. error Throw an error and do nothing.
  1342. show Make point visible, and do the requested edit.
  1343. show-and-error Make point visible, then throw an error and abort the edit.
  1344. smart Make point visible, and do insertion/deletion if it is
  1345. adjacent to visible text and the change feels predictable.
  1346. Never delete a previously invisible character or add in the
  1347. middle or right after an invisible region. Basically, this
  1348. allows insertion and backward-delete right before ellipses.
  1349. FIXME: maybe in this case we should not even show?"
  1350. :group 'org-edit-structure
  1351. :version "24.1"
  1352. :type '(choice
  1353. (const :tag "Do not check" nil)
  1354. (const :tag "Throw error when trying to edit" error)
  1355. (const :tag "Unhide, but do not do the edit" show-and-error)
  1356. (const :tag "Show invisible part and do the edit" show)
  1357. (const :tag "Be smart and do the right thing" smart)))
  1358. (defcustom org-yank-folded-subtrees t
  1359. "Non-nil means when yanking subtrees, fold them.
  1360. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1361. it starts with a heading and all other headings in it are either children
  1362. or siblings, then fold all the subtrees. However, do this only if no
  1363. text after the yank would be swallowed into a folded tree by this action."
  1364. :group 'org-edit-structure
  1365. :type 'boolean)
  1366. (defcustom org-yank-adjusted-subtrees nil
  1367. "Non-nil means when yanking subtrees, adjust the level.
  1368. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1369. this function for details."
  1370. :group 'org-edit-structure
  1371. :type 'boolean)
  1372. (defcustom org-M-RET-may-split-line '((default . t))
  1373. "Non-nil means M-RET will split the line at the cursor position.
  1374. When nil, it will go to the end of the line before making a
  1375. new line.
  1376. You may also set this option in a different way for different
  1377. contexts. Valid contexts are:
  1378. headline when creating a new headline
  1379. item when creating a new item
  1380. table in a table field
  1381. default the value to be used for all contexts not explicitly
  1382. customized"
  1383. :group 'org-structure
  1384. :group 'org-table
  1385. :type '(choice
  1386. (const :tag "Always" t)
  1387. (const :tag "Never" nil)
  1388. (repeat :greedy t :tag "Individual contexts"
  1389. (cons
  1390. (choice :tag "Context"
  1391. (const headline)
  1392. (const item)
  1393. (const table)
  1394. (const default))
  1395. (boolean)))))
  1396. (defcustom org-insert-heading-respect-content nil
  1397. "Non-nil means insert new headings after the current subtree.
  1398. \\<org-mode-map>
  1399. When nil, the new heading is created directly after the current line.
  1400. The commands `\\[org-insert-heading-respect-content]' and \
  1401. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1402. for the duration of the command."
  1403. :group 'org-structure
  1404. :type 'boolean)
  1405. (defcustom org-blank-before-new-entry '((heading . auto)
  1406. (plain-list-item . auto))
  1407. "Should `org-insert-heading' leave a blank line before new heading/item?
  1408. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1409. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1410. which case Org will look at the surrounding headings/items and try to
  1411. make an intelligent decision whether to insert a blank line or not."
  1412. :group 'org-edit-structure
  1413. :type '(list
  1414. (cons (const heading)
  1415. (choice (const :tag "Never" nil)
  1416. (const :tag "Always" t)
  1417. (const :tag "Auto" auto)))
  1418. (cons (const plain-list-item)
  1419. (choice (const :tag "Never" nil)
  1420. (const :tag "Always" t)
  1421. (const :tag "Auto" auto)))))
  1422. (defcustom org-insert-heading-hook nil
  1423. "Hook being run after inserting a new heading."
  1424. :group 'org-edit-structure
  1425. :type 'hook)
  1426. (defcustom org-enable-fixed-width-editor t
  1427. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1428. This currently only means they are never auto-wrapped.
  1429. When nil, such lines will be treated like ordinary lines."
  1430. :group 'org-edit-structure
  1431. :type 'boolean)
  1432. (defgroup org-sparse-trees nil
  1433. "Options concerning sparse trees in Org mode."
  1434. :tag "Org Sparse Trees"
  1435. :group 'org-structure)
  1436. (defcustom org-highlight-sparse-tree-matches t
  1437. "Non-nil means highlight all matches that define a sparse tree.
  1438. The highlights will automatically disappear the next time the buffer is
  1439. changed by an edit command."
  1440. :group 'org-sparse-trees
  1441. :type 'boolean)
  1442. (defcustom org-remove-highlights-with-change t
  1443. "Non-nil means any change to the buffer will remove temporary highlights.
  1444. \\<org-mode-map>\
  1445. Such highlights are created by `org-occur' and `org-clock-display'.
  1446. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1447. to get rid of the highlights.
  1448. The highlights created by `org-toggle-latex-fragment' always need
  1449. `\\[org-toggle-latex-fragment]' to be removed."
  1450. :group 'org-sparse-trees
  1451. :group 'org-time
  1452. :type 'boolean)
  1453. (defcustom org-occur-case-fold-search t
  1454. "Non-nil means `org-occur' should be case-insensitive.
  1455. If set to `smart' the search will be case-insensitive only if it
  1456. doesn't specify any upper case character."
  1457. :group 'org-sparse-trees
  1458. :version "26.1"
  1459. :type '(choice
  1460. (const :tag "Case-sensitive" nil)
  1461. (const :tag "Case-insensitive" t)
  1462. (const :tag "Case-insensitive for lower case searches only" smart)))
  1463. (defcustom org-occur-hook '(org-first-headline-recenter)
  1464. "Hook that is run after `org-occur' has constructed a sparse tree.
  1465. This can be used to recenter the window to show as much of the structure
  1466. as possible."
  1467. :group 'org-sparse-trees
  1468. :type 'hook)
  1469. (defgroup org-table nil
  1470. "Options concerning tables in Org mode."
  1471. :tag "Org Table"
  1472. :group 'org)
  1473. (defcustom org-self-insert-cluster-for-undo nil
  1474. "Non-nil means cluster self-insert commands for undo when possible.
  1475. If this is set, then, like in the Emacs command loop, 20 consecutive
  1476. characters will be undone together.
  1477. This is configurable, because there is some impact on typing performance."
  1478. :group 'org-table
  1479. :type 'boolean)
  1480. (defcustom org-table-tab-recognizes-table.el t
  1481. "Non-nil means TAB will automatically notice a table.el table.
  1482. When it sees such a table, it moves point into it and - if necessary -
  1483. calls `table-recognize-table'."
  1484. :group 'org-table-editing
  1485. :type 'boolean)
  1486. (defgroup org-link nil
  1487. "Options concerning links in Org mode."
  1488. :tag "Org Link"
  1489. :group 'org)
  1490. (defvar-local org-link-abbrev-alist-local nil
  1491. "Buffer-local version of `org-link-abbrev-alist', which see.
  1492. The value of this is taken from the #+LINK lines.")
  1493. (defcustom org-link-parameters
  1494. '(("doi" :follow org--open-doi-link)
  1495. ("elisp" :follow org--open-elisp-link)
  1496. ("file" :complete org-file-complete-link)
  1497. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1498. ("help" :follow org--open-help-link)
  1499. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1500. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1501. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1502. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1503. ("shell" :follow org--open-shell-link))
  1504. "An alist of properties that defines all the links in Org mode.
  1505. The key in each association is a string of the link type.
  1506. Subsequent optional elements make up a p-list of link properties.
  1507. :follow - A function that takes the link path as an argument.
  1508. :export - A function that takes the link path, description and
  1509. export-backend as arguments.
  1510. :store - A function responsible for storing the link. See the
  1511. function `org-store-link-functions'.
  1512. :complete - A function that inserts a link with completion. The
  1513. function takes one optional prefix arg.
  1514. :face - A face for the link, or a function that returns a face.
  1515. The function takes one argument which is the link path. The
  1516. default face is `org-link'.
  1517. :mouse-face - The mouse-face. The default is `highlight'.
  1518. :display - `full' will not fold the link in descriptive
  1519. display. Default is `org-link'.
  1520. :help-echo - A string or function that takes (window object position)
  1521. as arguments and returns a string.
  1522. :keymap - A keymap that is active on the link. The default is
  1523. `org-mouse-map'.
  1524. :htmlize-link - A function for the htmlize-link. Defaults
  1525. to (list :uri \"type:path\")
  1526. :activate-func - A function to run at the end of font-lock
  1527. activation. The function must accept (link-start link-end path bracketp)
  1528. as arguments."
  1529. :group 'org-link
  1530. :type '(alist :tag "Link display parameters"
  1531. :value-type plist)
  1532. :version "26.1"
  1533. :package-version '(Org . "9.1"))
  1534. (defun org-link-get-parameter (type key)
  1535. "Get TYPE link property for KEY.
  1536. TYPE is a string and KEY is a plist keyword."
  1537. (plist-get
  1538. (cdr (assoc type org-link-parameters))
  1539. key))
  1540. (defun org-link-set-parameters (type &rest parameters)
  1541. "Set link TYPE properties to PARAMETERS.
  1542. PARAMETERS should be :key val pairs."
  1543. (let ((data (assoc type org-link-parameters)))
  1544. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1545. (push (cons type parameters) org-link-parameters)
  1546. (org-make-link-regexps)
  1547. (org-element-update-syntax))))
  1548. (defun org-link-types ()
  1549. "Return a list of known link types."
  1550. (mapcar #'car org-link-parameters))
  1551. (defcustom org-link-abbrev-alist nil
  1552. "Alist of link abbreviations.
  1553. The car of each element is a string, to be replaced at the start of a link.
  1554. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1555. links in Org buffers can have an optional tag after a double colon, e.g.,
  1556. [[linkkey:tag][description]]
  1557. The `linkkey' must be a single word, starting with a letter, followed
  1558. by letters, numbers, `-' or `_'.
  1559. If REPLACE is a string, the tag will simply be appended to create the link.
  1560. If the string contains \"%s\", the tag will be inserted there. If the string
  1561. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1562. at that point (see the function `url-hexify-string'). If the string contains
  1563. the specifier \"%(my-function)\", then the custom function `my-function' will
  1564. be invoked: this function takes the tag as its only argument and must return
  1565. a string.
  1566. REPLACE may also be a function that will be called with the tag as the
  1567. only argument to create the link, which should be returned as a string.
  1568. See the manual for examples."
  1569. :group 'org-link
  1570. :type '(repeat
  1571. (cons
  1572. (string :tag "Protocol")
  1573. (choice
  1574. (string :tag "Format")
  1575. (function)))))
  1576. (defcustom org-descriptive-links t
  1577. "Non-nil means Org will display descriptive links.
  1578. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1579. \"Org Website\", hiding the link itself and just displaying its
  1580. description. When set to nil, Org will display the full links
  1581. literally.
  1582. You can interactively set the value of this variable by calling
  1583. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1584. :group 'org-link
  1585. :type 'boolean)
  1586. (defcustom org-link-file-path-type 'adaptive
  1587. "How the path name in file links should be stored.
  1588. Valid values are:
  1589. relative Relative to the current directory, i.e. the directory of the file
  1590. into which the link is being inserted.
  1591. absolute Absolute path, if possible with ~ for home directory.
  1592. noabbrev Absolute path, no abbreviation of home directory.
  1593. adaptive Use relative path for files in the current directory and sub-
  1594. directories of it. For other files, use an absolute path."
  1595. :group 'org-link
  1596. :type '(choice
  1597. (const relative)
  1598. (const absolute)
  1599. (const noabbrev)
  1600. (const adaptive)))
  1601. (defvaralias 'org-activate-links 'org-highlight-links)
  1602. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1603. "Types of links that should be highlighted in Org files.
  1604. This is a list of symbols, each one of them leading to the
  1605. highlighting of a certain link type.
  1606. You can still open links that are not highlighted.
  1607. In principle, it does not hurt to turn on highlighting for all
  1608. link types. There may be a small gain when turning off unused
  1609. link types. The types are:
  1610. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1611. angle Links in angular brackets that may contain whitespace like
  1612. <bbdb:Carsten Dominik>.
  1613. plain Plain links in normal text, no whitespace, like http://google.com.
  1614. radio Text that is matched by a radio target, see manual for details.
  1615. tag Tag settings in a headline (link to tag search).
  1616. date Time stamps (link to calendar).
  1617. footnote Footnote labels.
  1618. If you set this variable during an Emacs session, use `org-mode-restart'
  1619. in the Org buffer so that the change takes effect."
  1620. :group 'org-link
  1621. :group 'org-appearance
  1622. :type '(set :greedy t
  1623. (const :tag "Double bracket links" bracket)
  1624. (const :tag "Angular bracket links" angle)
  1625. (const :tag "Plain text links" plain)
  1626. (const :tag "Radio target matches" radio)
  1627. (const :tag "Tags" tag)
  1628. (const :tag "Timestamps" date)
  1629. (const :tag "Footnotes" footnote)))
  1630. (defcustom org-make-link-description-function nil
  1631. "Function to use for generating link descriptions from links.
  1632. This function must take two parameters: the first one is the
  1633. link, the second one is the description generated by
  1634. `org-insert-link'. The function should return the description to
  1635. use."
  1636. :group 'org-link
  1637. :type '(choice (const nil) (function)))
  1638. (defgroup org-link-store nil
  1639. "Options concerning storing links in Org mode."
  1640. :tag "Org Store Link"
  1641. :group 'org-link)
  1642. (defcustom org-url-hexify-p t
  1643. "When non-nil, hexify URL when creating a link."
  1644. :type 'boolean
  1645. :version "24.3"
  1646. :group 'org-link-store)
  1647. (defcustom org-email-link-description-format "Email %c: %.30s"
  1648. "Format of the description part of a link to an email or usenet message.
  1649. The following %-escapes will be replaced by corresponding information:
  1650. %F full \"From\" field
  1651. %f name, taken from \"From\" field, address if no name
  1652. %T full \"To\" field
  1653. %t first name in \"To\" field, address if no name
  1654. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1655. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1656. %s subject
  1657. %d date
  1658. %m message-id.
  1659. You may use normal field width specification between the % and the letter.
  1660. This is for example useful to limit the length of the subject.
  1661. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1662. :group 'org-link-store
  1663. :type 'string)
  1664. (defcustom org-from-is-user-regexp
  1665. (let (r1 r2)
  1666. (when (and user-mail-address (not (string= user-mail-address "")))
  1667. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1668. (when (and user-full-name (not (string= user-full-name "")))
  1669. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1670. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1671. "Regexp matched against the \"From:\" header of an email or usenet message.
  1672. It should match if the message is from the user him/herself."
  1673. :group 'org-link-store
  1674. :type 'regexp)
  1675. (defcustom org-context-in-file-links t
  1676. "Non-nil means file links from `org-store-link' contain context.
  1677. \\<org-mode-map>
  1678. A search string will be added to the file name with :: as separator
  1679. and used to find the context when the link is activated by the command
  1680. `org-open-at-point'. When this option is t, the entire active region
  1681. will be placed in the search string of the file link. If set to a
  1682. positive integer, only the first n lines of context will be stored.
  1683. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1684. \\[org-store-link]')
  1685. negates this setting for the duration of the command."
  1686. :group 'org-link-store
  1687. :type '(choice boolean integer))
  1688. (defcustom org-keep-stored-link-after-insertion nil
  1689. "Non-nil means keep link in list for entire session.
  1690. \\<org-mode-map>
  1691. The command `org-store-link' adds a link pointing to the current
  1692. location to an internal list. These links accumulate during a session.
  1693. The command `org-insert-link' can be used to insert links into any
  1694. Org file (offering completion for all stored links).
  1695. When this option is nil, every link which has been inserted once using
  1696. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1697. unused
  1698. links more efficient."
  1699. :group 'org-link-store
  1700. :type 'boolean)
  1701. (defgroup org-link-follow nil
  1702. "Options concerning following links in Org mode."
  1703. :tag "Org Follow Link"
  1704. :group 'org-link)
  1705. (defcustom org-link-translation-function nil
  1706. "Function to translate links with different syntax to Org syntax.
  1707. This can be used to translate links created for example by the Planner
  1708. or emacs-wiki packages to Org syntax.
  1709. The function must accept two parameters, a TYPE containing the link
  1710. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1711. which is everything after the link protocol. It should return a cons
  1712. with possibly modified values of type and path.
  1713. Org contains a function for this, so if you set this variable to
  1714. `org-translate-link-from-planner', you should be able follow many
  1715. links created by planner."
  1716. :group 'org-link-follow
  1717. :type '(choice (const nil) (function)))
  1718. (defcustom org-follow-link-hook nil
  1719. "Hook that is run after a link has been followed."
  1720. :group 'org-link-follow
  1721. :type 'hook)
  1722. (defcustom org-tab-follows-link nil
  1723. "Non-nil means on links TAB will follow the link.
  1724. Needs to be set before org.el is loaded.
  1725. This really should not be used, it does not make sense, and the
  1726. implementation is bad."
  1727. :group 'org-link-follow
  1728. :type 'boolean)
  1729. (defcustom org-return-follows-link nil
  1730. "Non-nil means on links RET will follow the link.
  1731. In tables, the special behavior of RET has precedence."
  1732. :group 'org-link-follow
  1733. :type 'boolean)
  1734. (defcustom org-mouse-1-follows-link
  1735. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1736. "Non-nil means mouse-1 on a link will follow the link.
  1737. A longer mouse click will still set point. Needs to be set
  1738. before org.el is loaded."
  1739. :group 'org-link-follow
  1740. :version "26.1"
  1741. :package-version '(Org . "8.3")
  1742. :type '(choice
  1743. (const :tag "A double click follows the link" double)
  1744. (const :tag "Unconditionally follow the link with mouse-1" t)
  1745. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1746. (defcustom org-mark-ring-length 4
  1747. "Number of different positions to be recorded in the ring.
  1748. Changing this requires a restart of Emacs to work correctly."
  1749. :group 'org-link-follow
  1750. :type 'integer)
  1751. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1752. "Non-nil means internal fuzzy links can only match headlines.
  1753. When nil, the a fuzzy link may point to a target or a named
  1754. construct in the document. When set to the special value
  1755. `query-to-create', offer to create a new headline when none
  1756. matched.
  1757. Spaces and statistics cookies are ignored during heading searches."
  1758. :group 'org-link-follow
  1759. :version "24.1"
  1760. :type '(choice
  1761. (const :tag "Use fuzzy text search" nil)
  1762. (const :tag "Match only exact headline" t)
  1763. (const :tag "Match exact headline or query to create it"
  1764. query-to-create))
  1765. :safe #'symbolp)
  1766. (defcustom org-link-frame-setup
  1767. '((vm . vm-visit-folder-other-frame)
  1768. (vm-imap . vm-visit-imap-folder-other-frame)
  1769. (gnus . org-gnus-no-new-news)
  1770. (file . find-file-other-window)
  1771. (wl . wl-other-frame))
  1772. "Setup the frame configuration for following links.
  1773. When following a link with Emacs, it may often be useful to display
  1774. this link in another window or frame. This variable can be used to
  1775. set this up for the different types of links.
  1776. For VM, use any of
  1777. `vm-visit-folder'
  1778. `vm-visit-folder-other-window'
  1779. `vm-visit-folder-other-frame'
  1780. For Gnus, use any of
  1781. `gnus'
  1782. `gnus-other-frame'
  1783. `org-gnus-no-new-news'
  1784. For FILE, use any of
  1785. `find-file'
  1786. `find-file-other-window'
  1787. `find-file-other-frame'
  1788. For Wanderlust use any of
  1789. `wl'
  1790. `wl-other-frame'
  1791. For the calendar, use the variable `calendar-setup'.
  1792. For BBDB, it is currently only possible to display the matches in
  1793. another window."
  1794. :group 'org-link-follow
  1795. :type '(list
  1796. (cons (const vm)
  1797. (choice
  1798. (const vm-visit-folder)
  1799. (const vm-visit-folder-other-window)
  1800. (const vm-visit-folder-other-frame)))
  1801. (cons (const vm-imap)
  1802. (choice
  1803. (const vm-visit-imap-folder)
  1804. (const vm-visit-imap-folder-other-window)
  1805. (const vm-visit-imap-folder-other-frame)))
  1806. (cons (const gnus)
  1807. (choice
  1808. (const gnus)
  1809. (const gnus-other-frame)
  1810. (const org-gnus-no-new-news)))
  1811. (cons (const file)
  1812. (choice
  1813. (const find-file)
  1814. (const find-file-other-window)
  1815. (const find-file-other-frame)))
  1816. (cons (const wl)
  1817. (choice
  1818. (const wl)
  1819. (const wl-other-frame)))))
  1820. (defcustom org-display-internal-link-with-indirect-buffer nil
  1821. "Non-nil means use indirect buffer to display infile links.
  1822. Activating internal links (from one location in a file to another location
  1823. in the same file) normally just jumps to the location. When the link is
  1824. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1825. is displayed in
  1826. another window. When this option is set, the other window actually displays
  1827. an indirect buffer clone of the current buffer, to avoid any visibility
  1828. changes to the current buffer."
  1829. :group 'org-link-follow
  1830. :type 'boolean)
  1831. (defcustom org-open-non-existing-files nil
  1832. "Non-nil means `org-open-file' will open non-existing files.
  1833. When nil, an error will be generated.
  1834. This variable applies only to external applications because they
  1835. might choke on non-existing files. If the link is to a file that
  1836. will be opened in Emacs, the variable is ignored."
  1837. :group 'org-link-follow
  1838. :type 'boolean)
  1839. (defcustom org-open-directory-means-index-dot-org nil
  1840. "Non-nil means a link to a directory really means to index.org.
  1841. When nil, following a directory link will run dired or open a finder/explorer
  1842. window on that directory."
  1843. :group 'org-link-follow
  1844. :type 'boolean)
  1845. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1846. "Non-nil means ask for confirmation before executing shell links.
  1847. Shell links can be dangerous: just think about a link
  1848. [[shell:rm -rf ~/*][Google Search]]
  1849. This link would show up in your Org document as \"Google Search\",
  1850. but really it would remove your entire home directory.
  1851. Therefore we advise against setting this variable to nil.
  1852. Just change it to `y-or-n-p' if you want to confirm with a
  1853. single keystroke rather than having to type \"yes\"."
  1854. :group 'org-link-follow
  1855. :type '(choice
  1856. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1857. (const :tag "with y-or-n (faster)" y-or-n-p)
  1858. (const :tag "no confirmation (dangerous)" nil)))
  1859. (put 'org-confirm-shell-link-function
  1860. 'safe-local-variable
  1861. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1862. (defcustom org-confirm-shell-link-not-regexp ""
  1863. "A regexp to skip confirmation for shell links."
  1864. :group 'org-link-follow
  1865. :version "24.1"
  1866. :type 'regexp)
  1867. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1868. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1869. Elisp links can be dangerous: just think about a link
  1870. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1871. This link would show up in your Org document as \"Google Search\",
  1872. but really it would remove your entire home directory.
  1873. Therefore we advise against setting this variable to nil.
  1874. Just change it to `y-or-n-p' if you want to confirm with a
  1875. single keystroke rather than having to type \"yes\"."
  1876. :group 'org-link-follow
  1877. :type '(choice
  1878. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1879. (const :tag "with y-or-n (faster)" y-or-n-p)
  1880. (const :tag "no confirmation (dangerous)" nil)))
  1881. (put 'org-confirm-shell-link-function
  1882. 'safe-local-variable
  1883. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1884. (defcustom org-confirm-elisp-link-not-regexp ""
  1885. "A regexp to skip confirmation for Elisp links."
  1886. :group 'org-link-follow
  1887. :version "24.1"
  1888. :type 'regexp)
  1889. (defconst org-file-apps-defaults-gnu
  1890. '((remote . emacs)
  1891. (system . mailcap)
  1892. (t . mailcap))
  1893. "Default file applications on a UNIX or GNU/Linux system.
  1894. See `org-file-apps'.")
  1895. (defconst org-file-apps-defaults-macosx
  1896. '((remote . emacs)
  1897. (system . "open %s")
  1898. ("ps.gz" . "gv %s")
  1899. ("eps.gz" . "gv %s")
  1900. ("dvi" . "xdvi %s")
  1901. ("fig" . "xfig %s")
  1902. (t . "open %s"))
  1903. "Default file applications on a macOS system.
  1904. The system \"open\" is known as a default, but we use X11 applications
  1905. for some files for which the OS does not have a good default.
  1906. See `org-file-apps'.")
  1907. (defconst org-file-apps-defaults-windowsnt
  1908. (list '(remote . emacs)
  1909. (cons 'system (lambda (file _path)
  1910. (with-no-warnings (w32-shell-execute "open" file))))
  1911. (cons t (lambda (file _path)
  1912. (with-no-warnings (w32-shell-execute "open" file)))))
  1913. "Default file applications on a Windows NT system.
  1914. The system \"open\" is used for most files.
  1915. See `org-file-apps'.")
  1916. (defcustom org-file-apps
  1917. '((auto-mode . emacs)
  1918. ("\\.mm\\'" . default)
  1919. ("\\.x?html?\\'" . default)
  1920. ("\\.pdf\\'" . default))
  1921. "External applications for opening `file:path' items in a document.
  1922. \\<org-mode-map>\
  1923. Org mode uses system defaults for different file types, but
  1924. you can use this variable to set the application for a given file
  1925. extension. The entries in this list are cons cells where the car identifies
  1926. files and the cdr the corresponding command.
  1927. Possible values for the file identifier are:
  1928. \"string\" A string as a file identifier can be interpreted in different
  1929. ways, depending on its contents:
  1930. - Alphanumeric characters only:
  1931. Match links with this file extension.
  1932. Example: (\"pdf\" . \"evince %s\")
  1933. to open PDFs with evince.
  1934. - Regular expression: Match links where the
  1935. filename matches the regexp. If you want to
  1936. use groups here, use shy groups.
  1937. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1938. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1939. to open *.html and *.xhtml with firefox.
  1940. - Regular expression which contains (non-shy) groups:
  1941. Match links where the whole link, including \"::\", and
  1942. anything after that, matches the regexp.
  1943. In a custom command string, %1, %2, etc. are replaced with
  1944. the parts of the link that were matched by the groups.
  1945. For backwards compatibility, if a command string is given
  1946. that does not use any of the group matches, this case is
  1947. handled identically to the second one (i.e. match against
  1948. file name only).
  1949. In a custom function, you can access the group matches with
  1950. (match-string n link).
  1951. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1952. \"evince -p %1 %s\")
  1953. to open [[file:document.pdf::5]] with evince at page 5.
  1954. `directory' Matches a directory
  1955. `remote' Matches a remote file, accessible through tramp or efs.
  1956. Remote files most likely should be visited through Emacs
  1957. because external applications cannot handle such paths.
  1958. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1959. so all files Emacs knows how to handle. Using this with
  1960. command `emacs' will open most files in Emacs. Beware that this
  1961. will also open html files inside Emacs, unless you add
  1962. (\"html\" . default) to the list as well.
  1963. `system' The system command to open files, like `open' on Windows
  1964. and macOS, and mailcap under GNU/Linux. This is the command
  1965. that will be selected if you call `org-open-at-point' with a
  1966. double prefix argument (`\\[universal-argument] \
  1967. \\[universal-argument] \\[org-open-at-point]').
  1968. t Default for files not matched by any of the other options.
  1969. Possible values for the command are:
  1970. `emacs' The file will be visited by the current Emacs process.
  1971. `default' Use the default application for this file type, which is the
  1972. association for t in the list, most likely in the system-specific
  1973. part. This can be used to overrule an unwanted setting in the
  1974. system-specific variable.
  1975. `system' Use the system command for opening files, like \"open\".
  1976. This command is specified by the entry whose car is `system'.
  1977. Most likely, the system-specific version of this variable
  1978. does define this command, but you can overrule/replace it
  1979. here.
  1980. `mailcap' Use command specified in the mailcaps.
  1981. string A command to be executed by a shell; %s will be replaced
  1982. by the path to the file.
  1983. function A Lisp function, which will be called with two arguments:
  1984. the file path and the original link string, without the
  1985. \"file:\" prefix.
  1986. For more examples, see the system specific constants
  1987. `org-file-apps-defaults-macosx'
  1988. `org-file-apps-defaults-windowsnt'
  1989. `org-file-apps-defaults-gnu'."
  1990. :group 'org-link-follow
  1991. :type '(repeat
  1992. (cons (choice :value ""
  1993. (string :tag "Extension")
  1994. (const :tag "System command to open files" system)
  1995. (const :tag "Default for unrecognized files" t)
  1996. (const :tag "Remote file" remote)
  1997. (const :tag "Links to a directory" directory)
  1998. (const :tag "Any files that have Emacs modes"
  1999. auto-mode))
  2000. (choice :value ""
  2001. (const :tag "Visit with Emacs" emacs)
  2002. (const :tag "Use default" default)
  2003. (const :tag "Use the system command" system)
  2004. (string :tag "Command")
  2005. (function :tag "Function")))))
  2006. (defcustom org-doi-server-url "http://dx.doi.org/"
  2007. "The URL of the DOI server."
  2008. :type 'string
  2009. :version "24.3"
  2010. :group 'org-link-follow)
  2011. (defgroup org-refile nil
  2012. "Options concerning refiling entries in Org mode."
  2013. :tag "Org Refile"
  2014. :group 'org)
  2015. (defcustom org-directory "~/org"
  2016. "Directory with Org files.
  2017. This is just a default location to look for Org files. There is no need
  2018. at all to put your files into this directory. It is used in the
  2019. following situations:
  2020. 1. When a capture template specifies a target file that is not an
  2021. absolute path. The path will then be interpreted relative to
  2022. `org-directory'
  2023. 2. When the value of variable `org-agenda-files' is a single file, any
  2024. relative paths in this file will be taken as relative to
  2025. `org-directory'."
  2026. :group 'org-refile
  2027. :group 'org-capture
  2028. :type 'directory)
  2029. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2030. "Default target for storing notes.
  2031. Used as a fall back file for org-capture.el, for templates that
  2032. do not specify a target file."
  2033. :group 'org-refile
  2034. :group 'org-capture
  2035. :type 'file)
  2036. (defcustom org-reverse-note-order nil
  2037. "Non-nil means store new notes at the beginning of a file or entry.
  2038. When nil, new notes will be filed to the end of a file or entry.
  2039. This can also be a list with cons cells of regular expressions that
  2040. are matched against file names, and values."
  2041. :group 'org-capture
  2042. :group 'org-refile
  2043. :type '(choice
  2044. (const :tag "Reverse always" t)
  2045. (const :tag "Reverse never" nil)
  2046. (repeat :tag "By file name regexp"
  2047. (cons regexp boolean))))
  2048. (defcustom org-log-refile nil
  2049. "Information to record when a task is refiled.
  2050. Possible values are:
  2051. nil Don't add anything
  2052. time Add a time stamp to the task
  2053. note Prompt for a note and add it with template `org-log-note-headings'
  2054. This option can also be set with on a per-file-basis with
  2055. #+STARTUP: nologrefile
  2056. #+STARTUP: logrefile
  2057. #+STARTUP: lognoterefile
  2058. You can have local logging settings for a subtree by setting the LOGGING
  2059. property to one or more of these keywords.
  2060. When bulk-refiling from the agenda, the value `note' is forbidden and
  2061. will temporarily be changed to `time'."
  2062. :group 'org-refile
  2063. :group 'org-progress
  2064. :version "24.1"
  2065. :type '(choice
  2066. (const :tag "No logging" nil)
  2067. (const :tag "Record timestamp" time)
  2068. (const :tag "Record timestamp with note." note)))
  2069. (defcustom org-refile-targets nil
  2070. "Targets for refiling entries with `\\[org-refile]'.
  2071. This is a list of cons cells. Each cell contains:
  2072. - a specification of the files to be considered, either a list of files,
  2073. or a symbol whose function or variable value will be used to retrieve
  2074. a file name or a list of file names. If you use `org-agenda-files' for
  2075. that, all agenda files will be scanned for targets. Nil means consider
  2076. headings in the current buffer.
  2077. - A specification of how to find candidate refile targets. This may be
  2078. any of:
  2079. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2080. This tag has to be present in all target headlines, inheritance will
  2081. not be considered.
  2082. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2083. todo keyword.
  2084. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2085. headlines that are refiling targets.
  2086. - a cons cell (:level . N). Any headline of level N is considered a target.
  2087. Note that, when `org-odd-levels-only' is set, level corresponds to
  2088. order in hierarchy, not to the number of stars.
  2089. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2090. Note that, when `org-odd-levels-only' is set, level corresponds to
  2091. order in hierarchy, not to the number of stars.
  2092. Each element of this list generates a set of possible targets.
  2093. The union of these sets is presented (with completion) to
  2094. the user by `org-refile'.
  2095. You can set the variable `org-refile-target-verify-function' to a function
  2096. to verify each headline found by the simple criteria above.
  2097. When this variable is nil, all top-level headlines in the current buffer
  2098. are used, equivalent to the value `((nil . (:level . 1))'."
  2099. :group 'org-refile
  2100. :type '(repeat
  2101. (cons
  2102. (choice :value org-agenda-files
  2103. (const :tag "All agenda files" org-agenda-files)
  2104. (const :tag "Current buffer" nil)
  2105. (function) (variable) (file))
  2106. (choice :tag "Identify target headline by"
  2107. (cons :tag "Specific tag" (const :value :tag) (string))
  2108. (cons :tag "TODO keyword" (const :value :todo) (string))
  2109. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2110. (cons :tag "Level number" (const :value :level) (integer))
  2111. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2112. (defcustom org-refile-target-verify-function nil
  2113. "Function to verify if the headline at point should be a refile target.
  2114. The function will be called without arguments, with point at the
  2115. beginning of the headline. It should return t and leave point
  2116. where it is if the headline is a valid target for refiling.
  2117. If the target should not be selected, the function must return nil.
  2118. In addition to this, it may move point to a place from where the search
  2119. should be continued. For example, the function may decide that the entire
  2120. subtree of the current entry should be excluded and move point to the end
  2121. of the subtree."
  2122. :group 'org-refile
  2123. :type '(choice
  2124. (const nil)
  2125. (function)))
  2126. (defcustom org-refile-use-cache nil
  2127. "Non-nil means cache refile targets to speed up the process.
  2128. \\<org-mode-map>\
  2129. The cache for a particular file will be updated automatically when
  2130. the buffer has been killed, or when any of the marker used for flagging
  2131. refile targets no longer points at a live buffer.
  2132. If you have added new entries to a buffer that might themselves be targets,
  2133. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2134. if you find that easier, \
  2135. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2136. \\[org-refile]'."
  2137. :group 'org-refile
  2138. :version "24.1"
  2139. :type 'boolean)
  2140. (defcustom org-refile-use-outline-path nil
  2141. "Non-nil means provide refile targets as paths.
  2142. So a level 3 headline will be available as level1/level2/level3.
  2143. When the value is `file', also include the file name (without directory)
  2144. into the path. In this case, you can also stop the completion after
  2145. the file name, to get entries inserted as top level in the file.
  2146. When `full-file-path', include the full file path.
  2147. When `buffer-name', use the buffer name."
  2148. :group 'org-refile
  2149. :type '(choice
  2150. (const :tag "Not" nil)
  2151. (const :tag "Yes" t)
  2152. (const :tag "Start with file name" file)
  2153. (const :tag "Start with full file path" full-file-path)
  2154. (const :tag "Start with buffer name" buffer-name)))
  2155. (defcustom org-outline-path-complete-in-steps t
  2156. "Non-nil means complete the outline path in hierarchical steps.
  2157. When Org uses the refile interface to select an outline path (see
  2158. `org-refile-use-outline-path'), the completion of the path can be
  2159. done in a single go, or it can be done in steps down the headline
  2160. hierarchy. Going in steps is probably the best if you do not use
  2161. a special completion package like `ido' or `icicles'. However,
  2162. when using these packages, going in one step can be very fast,
  2163. while still showing the whole path to the entry."
  2164. :group 'org-refile
  2165. :type 'boolean)
  2166. (defcustom org-refile-allow-creating-parent-nodes nil
  2167. "Non-nil means allow the creation of new nodes as refile targets.
  2168. New nodes are then created by adding \"/new node name\" to the completion
  2169. of an existing node. When the value of this variable is `confirm',
  2170. new node creation must be confirmed by the user (recommended).
  2171. When nil, the completion must match an existing entry.
  2172. Note that, if the new heading is not seen by the criteria
  2173. listed in `org-refile-targets', multiple instances of the same
  2174. heading would be created by trying again to file under the new
  2175. heading."
  2176. :group 'org-refile
  2177. :type '(choice
  2178. (const :tag "Never" nil)
  2179. (const :tag "Always" t)
  2180. (const :tag "Prompt for confirmation" confirm)))
  2181. (defcustom org-refile-active-region-within-subtree nil
  2182. "Non-nil means also refile active region within a subtree.
  2183. By default `org-refile' doesn't allow refiling regions if they
  2184. don't contain a set of subtrees, but it might be convenient to
  2185. do so sometimes: in that case, the first line of the region is
  2186. converted to a headline before refiling."
  2187. :group 'org-refile
  2188. :version "24.1"
  2189. :type 'boolean)
  2190. (defgroup org-todo nil
  2191. "Options concerning TODO items in Org mode."
  2192. :tag "Org TODO"
  2193. :group 'org)
  2194. (defgroup org-progress nil
  2195. "Options concerning Progress logging in Org mode."
  2196. :tag "Org Progress"
  2197. :group 'org-time)
  2198. (defvar org-todo-interpretation-widgets
  2199. '((:tag "Sequence (cycling hits every state)" sequence)
  2200. (:tag "Type (cycling directly to DONE)" type))
  2201. "The available interpretation symbols for customizing `org-todo-keywords'.
  2202. Interested libraries should add to this list.")
  2203. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2204. "List of TODO entry keyword sequences and their interpretation.
  2205. \\<org-mode-map>This is a list of sequences.
  2206. Each sequence starts with a symbol, either `sequence' or `type',
  2207. indicating if the keywords should be interpreted as a sequence of
  2208. action steps, or as different types of TODO items. The first
  2209. keywords are states requiring action - these states will select a headline
  2210. for inclusion into the global TODO list Org produces. If one of the
  2211. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2212. signify that no further action is necessary. If \"|\" is not found,
  2213. the last keyword is treated as the only DONE state of the sequence.
  2214. The command `\\[org-todo]' cycles an entry through these states, and one
  2215. additional state where no keyword is present. For details about this
  2216. cycling, see the manual.
  2217. TODO keywords and interpretation can also be set on a per-file basis with
  2218. the special #+SEQ_TODO and #+TYP_TODO lines.
  2219. Each keyword can optionally specify a character for fast state selection
  2220. \(in combination with the variable `org-use-fast-todo-selection')
  2221. and specifiers for state change logging, using the same syntax that
  2222. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2223. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2224. indicates to record a time stamp each time this state is selected.
  2225. Each keyword may also specify if a timestamp or a note should be
  2226. recorded when entering or leaving the state, by adding additional
  2227. characters in the parenthesis after the keyword. This looks like this:
  2228. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2229. record only the time of the state change. With X and Y being either
  2230. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2231. Y when leaving the state if and only if the *target* state does not
  2232. define X. You may omit any of the fast-selection key or X or /Y,
  2233. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2234. For backward compatibility, this variable may also be just a list
  2235. of keywords. In this case the interpretation (sequence or type) will be
  2236. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2237. :group 'org-todo
  2238. :group 'org-keywords
  2239. :type '(choice
  2240. (repeat :tag "Old syntax, just keywords"
  2241. (string :tag "Keyword"))
  2242. (repeat :tag "New syntax"
  2243. (cons
  2244. (choice
  2245. :tag "Interpretation"
  2246. ;;Quick and dirty way to see
  2247. ;;`org-todo-interpretations'. This takes the
  2248. ;;place of item arguments
  2249. :convert-widget
  2250. (lambda (widget)
  2251. (widget-put widget
  2252. :args (mapcar
  2253. (lambda (x)
  2254. (widget-convert
  2255. (cons 'const x)))
  2256. org-todo-interpretation-widgets))
  2257. widget))
  2258. (repeat
  2259. (string :tag "Keyword"))))))
  2260. (defvar-local org-todo-keywords-1 nil
  2261. "All TODO and DONE keywords active in a buffer.")
  2262. (defvar org-todo-keywords-for-agenda nil)
  2263. (defvar org-done-keywords-for-agenda nil)
  2264. (defvar org-todo-keyword-alist-for-agenda nil)
  2265. (defvar org-tag-alist-for-agenda nil
  2266. "Alist of all tags from all agenda files.")
  2267. (defvar org-tag-groups-alist-for-agenda nil
  2268. "Alist of all groups tags from all current agenda files.")
  2269. (defvar-local org-tag-groups-alist nil)
  2270. (defvar org-agenda-contributing-files nil)
  2271. (defvar-local org-current-tag-alist nil
  2272. "Alist of all tag groups in current buffer.
  2273. This variable takes into consideration `org-tag-alist',
  2274. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2275. (defvar-local org-not-done-keywords nil)
  2276. (defvar-local org-done-keywords nil)
  2277. (defvar-local org-todo-heads nil)
  2278. (defvar-local org-todo-sets nil)
  2279. (defvar-local org-todo-log-states nil)
  2280. (defvar-local org-todo-kwd-alist nil)
  2281. (defvar-local org-todo-key-alist nil)
  2282. (defvar-local org-todo-key-trigger nil)
  2283. (defcustom org-todo-interpretation 'sequence
  2284. "Controls how TODO keywords are interpreted.
  2285. This variable is in principle obsolete and is only used for
  2286. backward compatibility, if the interpretation of todo keywords is
  2287. not given already in `org-todo-keywords'. See that variable for
  2288. more information."
  2289. :group 'org-todo
  2290. :group 'org-keywords
  2291. :type '(choice (const sequence)
  2292. (const type)))
  2293. (defcustom org-use-fast-todo-selection t
  2294. "\\<org-mode-map>\
  2295. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2296. This variable describes if and under what circumstances the cycling
  2297. mechanism for TODO keywords will be replaced by a single-key, direct
  2298. selection scheme.
  2299. When nil, fast selection is never used.
  2300. When the symbol `prefix', it will be used when `org-todo' is called
  2301. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2302. in an Org buffer, and
  2303. `\\[universal-argument] t' in an agenda buffer.
  2304. When t, fast selection is used by default. In this case, the prefix
  2305. argument forces cycling instead.
  2306. In all cases, the special interface is only used if access keys have
  2307. actually been assigned by the user, i.e. if keywords in the configuration
  2308. are followed by a letter in parenthesis, like TODO(t)."
  2309. :group 'org-todo
  2310. :type '(choice
  2311. (const :tag "Never" nil)
  2312. (const :tag "By default" t)
  2313. (const :tag "Only with C-u C-c C-t" prefix)))
  2314. (defcustom org-provide-todo-statistics t
  2315. "Non-nil means update todo statistics after insert and toggle.
  2316. ALL-HEADLINES means update todo statistics by including headlines
  2317. with no TODO keyword as well, counting them as not done.
  2318. A list of TODO keywords means the same, but skip keywords that are
  2319. not in this list.
  2320. When set to a list of two lists, the first list contains keywords
  2321. to consider as TODO keywords, the second list contains keywords
  2322. to consider as DONE keywords.
  2323. When this is set, todo statistics is updated in the parent of the
  2324. current entry each time a todo state is changed."
  2325. :group 'org-todo
  2326. :type '(choice
  2327. (const :tag "Yes, only for TODO entries" t)
  2328. (const :tag "Yes, including all entries" all-headlines)
  2329. (repeat :tag "Yes, for TODOs in this list"
  2330. (string :tag "TODO keyword"))
  2331. (list :tag "Yes, for TODOs and DONEs in these lists"
  2332. (repeat (string :tag "TODO keyword"))
  2333. (repeat (string :tag "DONE keyword")))
  2334. (other :tag "No TODO statistics" nil)))
  2335. (defcustom org-hierarchical-todo-statistics t
  2336. "Non-nil means TODO statistics covers just direct children.
  2337. When nil, all entries in the subtree are considered.
  2338. This has only an effect if `org-provide-todo-statistics' is set.
  2339. To set this to nil for only a single subtree, use a COOKIE_DATA
  2340. property and include the word \"recursive\" into the value."
  2341. :group 'org-todo
  2342. :type 'boolean)
  2343. (defcustom org-after-todo-state-change-hook nil
  2344. "Hook which is run after the state of a TODO item was changed.
  2345. The new state (a string with a TODO keyword, or nil) is available in the
  2346. Lisp variable `org-state'."
  2347. :group 'org-todo
  2348. :type 'hook)
  2349. (defvar org-blocker-hook nil
  2350. "Hook for functions that are allowed to block a state change.
  2351. Functions in this hook should not modify the buffer.
  2352. Each function gets as its single argument a property list,
  2353. see `org-trigger-hook' for more information about this list.
  2354. If any of the functions in this hook returns nil, the state change
  2355. is blocked.")
  2356. (defvar org-trigger-hook nil
  2357. "Hook for functions that are triggered by a state change.
  2358. Each function gets as its single argument a property list with at
  2359. least the following elements:
  2360. (:type type-of-change :position pos-at-entry-start
  2361. :from old-state :to new-state)
  2362. Depending on the type, more properties may be present.
  2363. This mechanism is currently implemented for:
  2364. TODO state changes
  2365. ------------------
  2366. :type todo-state-change
  2367. :from previous state (keyword as a string), or nil, or a symbol
  2368. `todo' or `done', to indicate the general type of state.
  2369. :to new state, like in :from")
  2370. (defcustom org-enforce-todo-dependencies nil
  2371. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2372. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2373. be blocked if any prior sibling is not yet done.
  2374. Finally, if the parent is blocked because of ordered siblings of its own,
  2375. the child will also be blocked."
  2376. :set (lambda (var val)
  2377. (set var val)
  2378. (if val
  2379. (add-hook 'org-blocker-hook
  2380. 'org-block-todo-from-children-or-siblings-or-parent)
  2381. (remove-hook 'org-blocker-hook
  2382. 'org-block-todo-from-children-or-siblings-or-parent)))
  2383. :group 'org-todo
  2384. :type 'boolean)
  2385. (defcustom org-enforce-todo-checkbox-dependencies nil
  2386. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2387. When this is nil, checkboxes have no influence on switching TODO states.
  2388. When non-nil, you first need to check off all check boxes before the TODO
  2389. entry can be switched to DONE.
  2390. This variable needs to be set before org.el is loaded, and you need to
  2391. restart Emacs after a change to make the change effective. The only way
  2392. to change is while Emacs is running is through the customize interface."
  2393. :set (lambda (var val)
  2394. (set var val)
  2395. (if val
  2396. (add-hook 'org-blocker-hook
  2397. 'org-block-todo-from-checkboxes)
  2398. (remove-hook 'org-blocker-hook
  2399. 'org-block-todo-from-checkboxes)))
  2400. :group 'org-todo
  2401. :type 'boolean)
  2402. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2403. "Non-nil means inserting a TODO heading is treated as state change.
  2404. So when the command `\\[org-insert-todo-heading]' is used, state change
  2405. logging will apply if appropriate. When nil, the new TODO item will
  2406. be inserted directly, and no logging will take place."
  2407. :group 'org-todo
  2408. :type 'boolean)
  2409. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2410. "Non-nil means switching TODO states with S-cursor counts as state change.
  2411. This is the default behavior. However, setting this to nil allows a
  2412. convenient way to select a TODO state and bypass any logging associated
  2413. with that."
  2414. :group 'org-todo
  2415. :type 'boolean)
  2416. (defcustom org-todo-state-tags-triggers nil
  2417. "Tag changes that should be triggered by TODO state changes.
  2418. This is a list. Each entry is
  2419. (state-change (tag . flag) .......)
  2420. State-change can be a string with a state, and empty string to indicate the
  2421. state that has no TODO keyword, or it can be one of the symbols `todo'
  2422. or `done', meaning any not-done or done state, respectively."
  2423. :group 'org-todo
  2424. :group 'org-tags
  2425. :type '(repeat
  2426. (cons (choice :tag "When changing to"
  2427. (const :tag "Not-done state" todo)
  2428. (const :tag "Done state" done)
  2429. (string :tag "State"))
  2430. (repeat
  2431. (cons :tag "Tag action"
  2432. (string :tag "Tag")
  2433. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2434. (defcustom org-log-done nil
  2435. "Information to record when a task moves to the DONE state.
  2436. Possible values are:
  2437. nil Don't add anything, just change the keyword
  2438. time Add a time stamp to the task
  2439. note Prompt for a note and add it with template `org-log-note-headings'
  2440. This option can also be set with on a per-file-basis with
  2441. #+STARTUP: nologdone
  2442. #+STARTUP: logdone
  2443. #+STARTUP: lognotedone
  2444. You can have local logging settings for a subtree by setting the LOGGING
  2445. property to one or more of these keywords."
  2446. :group 'org-todo
  2447. :group 'org-progress
  2448. :type '(choice
  2449. (const :tag "No logging" nil)
  2450. (const :tag "Record CLOSED timestamp" time)
  2451. (const :tag "Record CLOSED timestamp with note." note)))
  2452. ;; Normalize old uses of org-log-done.
  2453. (cond
  2454. ((eq org-log-done t) (setq org-log-done 'time))
  2455. ((and (listp org-log-done) (memq 'done org-log-done))
  2456. (setq org-log-done 'note)))
  2457. (defcustom org-log-reschedule nil
  2458. "Information to record when the scheduling date of a tasks is modified.
  2459. Possible values are:
  2460. nil Don't add anything, just change the date
  2461. time Add a time stamp to the task
  2462. note Prompt for a note and add it with template `org-log-note-headings'
  2463. This option can also be set with on a per-file-basis with
  2464. #+STARTUP: nologreschedule
  2465. #+STARTUP: logreschedule
  2466. #+STARTUP: lognotereschedule"
  2467. :group 'org-todo
  2468. :group 'org-progress
  2469. :type '(choice
  2470. (const :tag "No logging" nil)
  2471. (const :tag "Record timestamp" time)
  2472. (const :tag "Record timestamp with note." note)))
  2473. (defcustom org-log-redeadline nil
  2474. "Information to record when the deadline date of a tasks is modified.
  2475. Possible values are:
  2476. nil Don't add anything, just change the date
  2477. time Add a time stamp to the task
  2478. note Prompt for a note and add it with template `org-log-note-headings'
  2479. This option can also be set with on a per-file-basis with
  2480. #+STARTUP: nologredeadline
  2481. #+STARTUP: logredeadline
  2482. #+STARTUP: lognoteredeadline
  2483. You can have local logging settings for a subtree by setting the LOGGING
  2484. property to one or more of these keywords."
  2485. :group 'org-todo
  2486. :group 'org-progress
  2487. :type '(choice
  2488. (const :tag "No logging" nil)
  2489. (const :tag "Record timestamp" time)
  2490. (const :tag "Record timestamp with note." note)))
  2491. (defcustom org-log-note-clock-out nil
  2492. "Non-nil means record a note when clocking out of an item.
  2493. This can also be configured on a per-file basis by adding one of
  2494. the following lines anywhere in the buffer:
  2495. #+STARTUP: lognoteclock-out
  2496. #+STARTUP: nolognoteclock-out"
  2497. :group 'org-todo
  2498. :group 'org-progress
  2499. :type 'boolean)
  2500. (defcustom org-log-done-with-time t
  2501. "Non-nil means the CLOSED time stamp will contain date and time.
  2502. When nil, only the date will be recorded."
  2503. :group 'org-progress
  2504. :type 'boolean)
  2505. (defcustom org-log-note-headings
  2506. '((done . "CLOSING NOTE %t")
  2507. (state . "State %-12s from %-12S %t")
  2508. (note . "Note taken on %t")
  2509. (reschedule . "Rescheduled from %S on %t")
  2510. (delschedule . "Not scheduled, was %S on %t")
  2511. (redeadline . "New deadline from %S on %t")
  2512. (deldeadline . "Removed deadline, was %S on %t")
  2513. (refile . "Refiled on %t")
  2514. (clock-out . ""))
  2515. "Headings for notes added to entries.
  2516. The value is an alist, with the car being a symbol indicating the
  2517. note context, and the cdr is the heading to be used. The heading
  2518. may also be the empty string. The following placeholders can be
  2519. used:
  2520. %t a time stamp.
  2521. %T an active time stamp instead the default inactive one
  2522. %d a short-format time stamp.
  2523. %D an active short-format time stamp.
  2524. %s the new TODO state or time stamp (inactive), in double quotes.
  2525. %S the old TODO state or time stamp (inactive), in double quotes.
  2526. %u the user name.
  2527. %U full user name.
  2528. In fact, it is not a good idea to change the `state' entry,
  2529. because Agenda Log mode depends on the format of these entries."
  2530. :group 'org-todo
  2531. :group 'org-progress
  2532. :type '(list :greedy t
  2533. (cons (const :tag "Heading when closing an item" done) string)
  2534. (cons (const :tag
  2535. "Heading when changing todo state (todo sequence only)"
  2536. state) string)
  2537. (cons (const :tag "Heading when just taking a note" note) string)
  2538. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2539. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2540. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2541. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2542. (cons (const :tag "Heading when refiling" refile) string)
  2543. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2544. (unless (assq 'note org-log-note-headings)
  2545. (push '(note . "%t") org-log-note-headings))
  2546. (defcustom org-log-into-drawer nil
  2547. "Non-nil means insert state change notes and time stamps into a drawer.
  2548. When nil, state changes notes will be inserted after the headline and
  2549. any scheduling and clock lines, but not inside a drawer.
  2550. The value of this variable should be the name of the drawer to use.
  2551. LOGBOOK is proposed as the default drawer for this purpose, you can
  2552. also set this to a string to define the drawer of your choice.
  2553. A value of t is also allowed, representing \"LOGBOOK\".
  2554. A value of t or nil can also be set with on a per-file-basis with
  2555. #+STARTUP: logdrawer
  2556. #+STARTUP: nologdrawer
  2557. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2558. will be ignored.
  2559. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2560. a subtree.
  2561. Do not check directly this variable in a Lisp program. Call
  2562. function `org-log-into-drawer' instead."
  2563. :group 'org-todo
  2564. :group 'org-progress
  2565. :type '(choice
  2566. (const :tag "Not into a drawer" nil)
  2567. (const :tag "LOGBOOK" t)
  2568. (string :tag "Other")))
  2569. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2570. (defun org-log-into-drawer ()
  2571. "Name of the log drawer, as a string, or nil.
  2572. This is the value of `org-log-into-drawer'. However, if the
  2573. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2574. be used instead of the default value."
  2575. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2576. (cond ((equal p "nil") nil)
  2577. ((equal p "t") "LOGBOOK")
  2578. ((stringp p) p)
  2579. (p "LOGBOOK")
  2580. ((stringp org-log-into-drawer) org-log-into-drawer)
  2581. (org-log-into-drawer "LOGBOOK"))))
  2582. (defcustom org-log-state-notes-insert-after-drawers nil
  2583. "Non-nil means insert state change notes after any drawers in entry.
  2584. Only the drawers that *immediately* follow the headline and the
  2585. deadline/scheduled line are skipped.
  2586. When nil, insert notes right after the heading and perhaps the line
  2587. with deadline/scheduling if present.
  2588. This variable will have no effect if `org-log-into-drawer' is
  2589. set."
  2590. :group 'org-todo
  2591. :group 'org-progress
  2592. :type 'boolean)
  2593. (defcustom org-log-states-order-reversed t
  2594. "Non-nil means the latest state note will be directly after heading.
  2595. When nil, the state change notes will be ordered according to time.
  2596. This option can also be set with on a per-file-basis with
  2597. #+STARTUP: logstatesreversed
  2598. #+STARTUP: nologstatesreversed"
  2599. :group 'org-todo
  2600. :group 'org-progress
  2601. :type 'boolean)
  2602. (defcustom org-todo-repeat-to-state nil
  2603. "The TODO state to which a repeater should return the repeating task.
  2604. By default this is the first task in a TODO sequence, or the previous state
  2605. in a TODO_TYP set. But you can specify another task here.
  2606. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2607. :group 'org-todo
  2608. :version "24.1"
  2609. :type '(choice (const :tag "Head of sequence" nil)
  2610. (string :tag "Specific state")))
  2611. (defcustom org-log-repeat 'time
  2612. "Non-nil means record moving through the DONE state when triggering repeat.
  2613. An auto-repeating task is immediately switched back to TODO when
  2614. marked DONE. If you are not logging state changes (by adding \"@\"
  2615. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2616. record a closing note, there will be no record of the task moving
  2617. through DONE. This variable forces taking a note anyway.
  2618. nil Don't force a record
  2619. time Record a time stamp
  2620. note Prompt for a note and add it with template `org-log-note-headings'
  2621. This option can also be set with on a per-file-basis with
  2622. #+STARTUP: nologrepeat
  2623. #+STARTUP: logrepeat
  2624. #+STARTUP: lognoterepeat
  2625. You can have local logging settings for a subtree by setting the LOGGING
  2626. property to one or more of these keywords."
  2627. :group 'org-todo
  2628. :group 'org-progress
  2629. :type '(choice
  2630. (const :tag "Don't force a record" nil)
  2631. (const :tag "Force recording the DONE state" time)
  2632. (const :tag "Force recording a note with the DONE state" note)))
  2633. (defgroup org-priorities nil
  2634. "Priorities in Org mode."
  2635. :tag "Org Priorities"
  2636. :group 'org-todo)
  2637. (defcustom org-enable-priority-commands t
  2638. "Non-nil means priority commands are active.
  2639. When nil, these commands will be disabled, so that you never accidentally
  2640. set a priority."
  2641. :group 'org-priorities
  2642. :type 'boolean)
  2643. (defcustom org-highest-priority ?A
  2644. "The highest priority of TODO items. A character like ?A, ?B etc.
  2645. Must have a smaller ASCII number than `org-lowest-priority'."
  2646. :group 'org-priorities
  2647. :type 'character)
  2648. (defcustom org-lowest-priority ?C
  2649. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2650. Must have a larger ASCII number than `org-highest-priority'."
  2651. :group 'org-priorities
  2652. :type 'character)
  2653. (defcustom org-default-priority ?B
  2654. "The default priority of TODO items.
  2655. This is the priority an item gets if no explicit priority is given.
  2656. When starting to cycle on an empty priority the first step in the cycle
  2657. depends on `org-priority-start-cycle-with-default'. The resulting first
  2658. step priority must not exceed the range from `org-highest-priority' to
  2659. `org-lowest-priority' which means that `org-default-priority' has to be
  2660. in this range exclusive or inclusive the range boundaries. Else the
  2661. first step refuses to set the default and the second will fall back
  2662. to (depending on the command used) the highest or lowest priority."
  2663. :group 'org-priorities
  2664. :type 'character)
  2665. (defcustom org-priority-start-cycle-with-default t
  2666. "Non-nil means start with default priority when starting to cycle.
  2667. When this is nil, the first step in the cycle will be (depending on the
  2668. command used) one higher or lower than the default priority.
  2669. See also `org-default-priority'."
  2670. :group 'org-priorities
  2671. :type 'boolean)
  2672. (defcustom org-get-priority-function nil
  2673. "Function to extract the priority from a string.
  2674. The string is normally the headline. If this is nil Org computes the
  2675. priority from the priority cookie like [#A] in the headline. It returns
  2676. an integer, increasing by 1000 for each priority level.
  2677. The user can set a different function here, which should take a string
  2678. as an argument and return the numeric priority."
  2679. :group 'org-priorities
  2680. :version "24.1"
  2681. :type '(choice
  2682. (const nil)
  2683. (function)))
  2684. (defgroup org-time nil
  2685. "Options concerning time stamps and deadlines in Org mode."
  2686. :tag "Org Time"
  2687. :group 'org)
  2688. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2689. "Number of minutes to round time stamps to.
  2690. \\<org-mode-map>\
  2691. These are two values, the first applies when first creating a time stamp.
  2692. The second applies when changing it with the commands `S-up' and `S-down'.
  2693. When changing the time stamp, this means that it will change in steps
  2694. of N minutes, as given by the second value.
  2695. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2696. numbers should be factors of 60, so for example 5, 10, 15.
  2697. When this is larger than 1, you can still force an exact time stamp by using
  2698. a double prefix argument to a time stamp command like \
  2699. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2700. and by using a prefix arg to `S-up/down' to specify the exact number
  2701. of minutes to shift."
  2702. :group 'org-time
  2703. :get (lambda (var) ; Make sure both elements are there
  2704. (if (integerp (default-value var))
  2705. (list (default-value var) 5)
  2706. (default-value var)))
  2707. :type '(list
  2708. (integer :tag "when inserting times")
  2709. (integer :tag "when modifying times")))
  2710. ;; Normalize old customizations of this variable.
  2711. (when (integerp org-time-stamp-rounding-minutes)
  2712. (setq org-time-stamp-rounding-minutes
  2713. (list org-time-stamp-rounding-minutes
  2714. org-time-stamp-rounding-minutes)))
  2715. (defcustom org-display-custom-times nil
  2716. "Non-nil means overlay custom formats over all time stamps.
  2717. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2718. To turn this on on a per-file basis, insert anywhere in the file:
  2719. #+STARTUP: customtime"
  2720. :group 'org-time
  2721. :set 'set-default
  2722. :type 'sexp)
  2723. (make-variable-buffer-local 'org-display-custom-times)
  2724. (defcustom org-time-stamp-custom-formats
  2725. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2726. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2727. These are overlaid over the default ISO format if the variable
  2728. `org-display-custom-times' is set. Time like %H:%M should be at the
  2729. end of the second format. The custom formats are also honored by export
  2730. commands, if custom time display is turned on at the time of export."
  2731. :group 'org-time
  2732. :type 'sexp)
  2733. (defun org-time-stamp-format (&optional long inactive)
  2734. "Get the right format for a time string."
  2735. (let ((f (if long (cdr org-time-stamp-formats)
  2736. (car org-time-stamp-formats))))
  2737. (if inactive
  2738. (concat "[" (substring f 1 -1) "]")
  2739. f)))
  2740. (defcustom org-deadline-warning-days 14
  2741. "Number of days before expiration during which a deadline becomes active.
  2742. This variable governs the display in sparse trees and in the agenda.
  2743. When 0 or negative, it means use this number (the absolute value of it)
  2744. even if a deadline has a different individual lead time specified.
  2745. Custom commands can set this variable in the options section."
  2746. :group 'org-time
  2747. :group 'org-agenda-daily/weekly
  2748. :type 'integer)
  2749. (defcustom org-scheduled-delay-days 0
  2750. "Number of days before a scheduled item becomes active.
  2751. This variable governs the display in sparse trees and in the agenda.
  2752. The default value (i.e. 0) means: don't delay scheduled item.
  2753. When negative, it means use this number (the absolute value of it)
  2754. even if a scheduled item has a different individual delay time
  2755. specified.
  2756. Custom commands can set this variable in the options section."
  2757. :group 'org-time
  2758. :group 'org-agenda-daily/weekly
  2759. :version "24.4"
  2760. :package-version '(Org . "8.0")
  2761. :type 'integer)
  2762. (defcustom org-read-date-prefer-future t
  2763. "Non-nil means assume future for incomplete date input from user.
  2764. This affects the following situations:
  2765. 1. The user gives a month but not a year.
  2766. For example, if it is April and you enter \"feb 2\", this will be read
  2767. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2768. 2. The user gives a day, but no month.
  2769. For example, if today is the 15th, and you enter \"3\", Org will read
  2770. this as the third of *next* month. However, if you enter \"17\",
  2771. it will be considered as *this* month.
  2772. If you set this variable to the symbol `time', then also the following
  2773. will work:
  2774. 3. If the user gives a time.
  2775. If the time is before now, it will be interpreted as tomorrow.
  2776. Currently none of this works for ISO week specifications.
  2777. When this option is nil, the current day, month and year will always be
  2778. used as defaults.
  2779. See also `org-agenda-jump-prefer-future'."
  2780. :group 'org-time
  2781. :type '(choice
  2782. (const :tag "Never" nil)
  2783. (const :tag "Check month and day" t)
  2784. (const :tag "Check month, day, and time" time)))
  2785. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2786. "Should the agenda jump command prefer the future for incomplete dates?
  2787. The default is to do the same as configured in `org-read-date-prefer-future'.
  2788. But you can also set a deviating value here.
  2789. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2790. :group 'org-agenda
  2791. :group 'org-time
  2792. :version "24.1"
  2793. :type '(choice
  2794. (const :tag "Use org-read-date-prefer-future"
  2795. org-read-date-prefer-future)
  2796. (const :tag "Never" nil)
  2797. (const :tag "Always" t)))
  2798. (defcustom org-read-date-force-compatible-dates t
  2799. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2800. Depending on the system Emacs is running on, certain dates cannot
  2801. be represented with the type used internally to represent time.
  2802. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2803. correctly. Some systems allow for earlier dates, some for later,
  2804. some for both. One way to find out it to insert any date into an
  2805. Org buffer, putting the cursor on the year and hitting S-up and
  2806. S-down to test the range.
  2807. When this variable is set to t, the date/time prompt will not let
  2808. you specify dates outside the 1970-2037 range, so it is certain that
  2809. these dates will work in whatever version of Emacs you are
  2810. running, and also that you can move a file from one Emacs implementation
  2811. to another. WHenever Org is forcing the year for you, it will display
  2812. a message and beep.
  2813. When this variable is nil, Org will check if the date is
  2814. representable in the specific Emacs implementation you are using.
  2815. If not, it will force a year, usually the current year, and beep
  2816. to remind you. Currently this setting is not recommended because
  2817. the likelihood that you will open your Org files in an Emacs that
  2818. has limited date range is not negligible.
  2819. A workaround for this problem is to use diary sexp dates for time
  2820. stamps outside of this range."
  2821. :group 'org-time
  2822. :version "24.1"
  2823. :type 'boolean)
  2824. (defcustom org-read-date-display-live t
  2825. "Non-nil means display current interpretation of date prompt live.
  2826. This display will be in an overlay, in the minibuffer."
  2827. :group 'org-time
  2828. :type 'boolean)
  2829. (defcustom org-read-date-popup-calendar t
  2830. "Non-nil means pop up a calendar when prompting for a date.
  2831. In the calendar, the date can be selected with mouse-1. However, the
  2832. minibuffer will also be active, and you can simply enter the date as well.
  2833. When nil, only the minibuffer will be available."
  2834. :group 'org-time
  2835. :type 'boolean)
  2836. (defvaralias 'org-popup-calendar-for-date-prompt
  2837. 'org-read-date-popup-calendar)
  2838. (defcustom org-extend-today-until 0
  2839. "The hour when your day really ends. Must be an integer.
  2840. This has influence for the following applications:
  2841. - When switching the agenda to \"today\". It it is still earlier than
  2842. the time given here, the day recognized as TODAY is actually yesterday.
  2843. - When a date is read from the user and it is still before the time given
  2844. here, the current date and time will be assumed to be yesterday, 23:59.
  2845. Also, timestamps inserted in capture templates follow this rule.
  2846. IMPORTANT: This is a feature whose implementation is and likely will
  2847. remain incomplete. Really, it is only here because past midnight seems to
  2848. be the favorite working time of John Wiegley :-)"
  2849. :group 'org-time
  2850. :type 'integer)
  2851. (defcustom org-use-effective-time nil
  2852. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2853. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2854. \"effective time\" of any timestamps between midnight and 8am will be
  2855. 23:59 of the previous day."
  2856. :group 'org-time
  2857. :version "24.1"
  2858. :type 'boolean)
  2859. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2860. "When non-nil, use the last clock out time for `org-todo'.
  2861. Note that this option has precedence over the combined use of
  2862. `org-use-effective-time' and `org-extend-today-until'."
  2863. :group 'org-time
  2864. :version "24.4"
  2865. :package-version '(Org . "8.0")
  2866. :type 'boolean)
  2867. (defcustom org-edit-timestamp-down-means-later nil
  2868. "Non-nil means S-down will increase the time in a time stamp.
  2869. When nil, S-up will increase."
  2870. :group 'org-time
  2871. :type 'boolean)
  2872. (defcustom org-calendar-follow-timestamp-change t
  2873. "Non-nil means make the calendar window follow timestamp changes.
  2874. When a timestamp is modified and the calendar window is visible, it will be
  2875. moved to the new date."
  2876. :group 'org-time
  2877. :type 'boolean)
  2878. (defgroup org-tags nil
  2879. "Options concerning tags in Org mode."
  2880. :tag "Org Tags"
  2881. :group 'org)
  2882. (defcustom org-tag-alist nil
  2883. "Default tags available in Org files.
  2884. The value of this variable is an alist. Associations either:
  2885. (TAG)
  2886. (TAG . SELECT)
  2887. (SPECIAL)
  2888. where TAG is a tag as a string, SELECT is character, used to
  2889. select that tag through the fast tag selection interface, and
  2890. SPECIAL is one of the following keywords: `:startgroup',
  2891. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2892. `:newline'. These keywords are used to define a hierarchy of
  2893. tags. See manual for details.
  2894. When this variable is nil, Org mode bases tag input on what is
  2895. already in the buffer. The value can be overridden locally by
  2896. using a TAGS keyword, e.g.,
  2897. #+TAGS: tag1 tag2
  2898. See also `org-tag-persistent-alist' to sidestep this behavior."
  2899. :group 'org-tags
  2900. :type '(repeat
  2901. (choice
  2902. (cons :tag "Tag with key"
  2903. (string :tag "Tag name")
  2904. (character :tag "Access char"))
  2905. (list :tag "Tag" (string :tag "Tag name"))
  2906. (const :tag "Start radio group" (:startgroup))
  2907. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2908. (const :tag "Group tags delimiter" (:grouptags))
  2909. (const :tag "End radio group" (:endgroup))
  2910. (const :tag "End tag group, non distinct" (:endgrouptag))
  2911. (const :tag "New line" (:newline)))))
  2912. (defcustom org-tag-persistent-alist nil
  2913. "Tags always available in Org files.
  2914. The value of this variable is an alist. Associations either:
  2915. (TAG)
  2916. (TAG . SELECT)
  2917. (SPECIAL)
  2918. where TAG is a tag as a string, SELECT is a character, used to
  2919. select that tag through the fast tag selection interface, and
  2920. SPECIAL is one of the following keywords: `:startgroup',
  2921. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2922. `:newline'. These keywords are used to define a hierarchy of
  2923. tags. See manual for details.
  2924. Unlike to `org-tag-alist', tags defined in this variable do not
  2925. depend on a local TAGS keyword. Instead, to disable these tags
  2926. on a per-file basis, insert anywhere in the file:
  2927. #+STARTUP: noptag"
  2928. :group 'org-tags
  2929. :type '(repeat
  2930. (choice
  2931. (cons :tag "Tag with key"
  2932. (string :tag "Tag name")
  2933. (character :tag "Access char"))
  2934. (list :tag "Tag" (string :tag "Tag name"))
  2935. (const :tag "Start radio group" (:startgroup))
  2936. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2937. (const :tag "Group tags delimiter" (:grouptags))
  2938. (const :tag "End radio group" (:endgroup))
  2939. (const :tag "End tag group, non distinct" (:endgrouptag))
  2940. (const :tag "New line" (:newline)))))
  2941. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2942. "If non-nil, always offer completion for all tags of all agenda files.
  2943. Instead of customizing this variable directly, you might want to
  2944. set it locally for capture buffers, because there no list of
  2945. tags in that file can be created dynamically (there are none).
  2946. (add-hook \\='org-capture-mode-hook
  2947. (lambda ()
  2948. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2949. :group 'org-tags
  2950. :version "24.1"
  2951. :type 'boolean)
  2952. (defvar org-file-tags nil
  2953. "List of tags that can be inherited by all entries in the file.
  2954. The tags will be inherited if the variable `org-use-tag-inheritance'
  2955. says they should be.
  2956. This variable is populated from #+FILETAGS lines.")
  2957. (defcustom org-use-fast-tag-selection 'auto
  2958. "Non-nil means use fast tag selection scheme.
  2959. This is a special interface to select and deselect tags with single keys.
  2960. When nil, fast selection is never used.
  2961. When the symbol `auto', fast selection is used if and only if selection
  2962. characters for tags have been configured, either through the variable
  2963. `org-tag-alist' or through a #+TAGS line in the buffer.
  2964. When t, fast selection is always used and selection keys are assigned
  2965. automatically if necessary."
  2966. :group 'org-tags
  2967. :type '(choice
  2968. (const :tag "Always" t)
  2969. (const :tag "Never" nil)
  2970. (const :tag "When selection characters are configured" auto)))
  2971. (defcustom org-fast-tag-selection-single-key nil
  2972. "Non-nil means fast tag selection exits after first change.
  2973. When nil, you have to press RET to exit it.
  2974. During fast tag selection, you can toggle this flag with `C-c'.
  2975. This variable can also have the value `expert'. In this case, the window
  2976. displaying the tags menu is not even shown, until you press C-c again."
  2977. :group 'org-tags
  2978. :type '(choice
  2979. (const :tag "No" nil)
  2980. (const :tag "Yes" t)
  2981. (const :tag "Expert" expert)))
  2982. (defvar org-fast-tag-selection-include-todo nil
  2983. "Non-nil means fast tags selection interface will also offer TODO states.
  2984. This is an undocumented feature, you should not rely on it.")
  2985. (defcustom org-tags-column -77
  2986. "The column to which tags should be indented in a headline.
  2987. If this number is positive, it specifies the column. If it is negative,
  2988. it means that the tags should be flushright to that column. For example,
  2989. -80 works well for a normal 80 character screen.
  2990. When 0, place tags directly after headline text, with only one space in
  2991. between."
  2992. :group 'org-tags
  2993. :type 'integer)
  2994. (defcustom org-auto-align-tags t
  2995. "Non-nil keeps tags aligned when modifying headlines.
  2996. Some operations (i.e. demoting) change the length of a headline and
  2997. therefore shift the tags around. With this option turned on, after
  2998. each such operation the tags are again aligned to `org-tags-column'."
  2999. :group 'org-tags
  3000. :type 'boolean)
  3001. (defcustom org-use-tag-inheritance t
  3002. "Non-nil means tags in levels apply also for sublevels.
  3003. When nil, only the tags directly given in a specific line apply there.
  3004. This may also be a list of tags that should be inherited, or a regexp that
  3005. matches tags that should be inherited. Additional control is possible
  3006. with the variable `org-tags-exclude-from-inheritance' which gives an
  3007. explicit list of tags to be excluded from inheritance, even if the value of
  3008. `org-use-tag-inheritance' would select it for inheritance.
  3009. If this option is t, a match early-on in a tree can lead to a large
  3010. number of matches in the subtree when constructing the agenda or creating
  3011. a sparse tree. If you only want to see the first match in a tree during
  3012. a search, check out the variable `org-tags-match-list-sublevels'."
  3013. :group 'org-tags
  3014. :type '(choice
  3015. (const :tag "Not" nil)
  3016. (const :tag "Always" t)
  3017. (repeat :tag "Specific tags" (string :tag "Tag"))
  3018. (regexp :tag "Tags matched by regexp")))
  3019. (defcustom org-tags-exclude-from-inheritance nil
  3020. "List of tags that should never be inherited.
  3021. This is a way to exclude a few tags from inheritance. For way to do
  3022. the opposite, to actively allow inheritance for selected tags,
  3023. see the variable `org-use-tag-inheritance'."
  3024. :group 'org-tags
  3025. :type '(repeat (string :tag "Tag")))
  3026. (defun org-tag-inherit-p (tag)
  3027. "Check if TAG is one that should be inherited."
  3028. (cond
  3029. ((member tag org-tags-exclude-from-inheritance) nil)
  3030. ((eq org-use-tag-inheritance t) t)
  3031. ((not org-use-tag-inheritance) nil)
  3032. ((stringp org-use-tag-inheritance)
  3033. (string-match org-use-tag-inheritance tag))
  3034. ((listp org-use-tag-inheritance)
  3035. (member tag org-use-tag-inheritance))
  3036. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3037. (defcustom org-tags-match-list-sublevels t
  3038. "Non-nil means list also sublevels of headlines matching a search.
  3039. This variable applies to tags/property searches, and also to stuck
  3040. projects because this search is based on a tags match as well.
  3041. When set to the symbol `indented', sublevels are indented with
  3042. leading dots.
  3043. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3044. the sublevels of a headline matching a tag search often also match
  3045. the same search. Listing all of them can create very long lists.
  3046. Setting this variable to nil causes subtrees of a match to be skipped.
  3047. This variable is semi-obsolete and probably should always be true. It
  3048. is better to limit inheritance to certain tags using the variables
  3049. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3050. :group 'org-tags
  3051. :type '(choice
  3052. (const :tag "No, don't list them" nil)
  3053. (const :tag "Yes, do list them" t)
  3054. (const :tag "List them, indented with leading dots" indented)))
  3055. (defcustom org-tags-sort-function nil
  3056. "When set, tags are sorted using this function as a comparator."
  3057. :group 'org-tags
  3058. :type '(choice
  3059. (const :tag "No sorting" nil)
  3060. (const :tag "Alphabetical" string<)
  3061. (const :tag "Reverse alphabetical" string>)
  3062. (function :tag "Custom function" nil)))
  3063. (defvar org-tags-history nil
  3064. "History of minibuffer reads for tags.")
  3065. (defvar org-last-tags-completion-table nil
  3066. "The last used completion table for tags.")
  3067. (defvar org-after-tags-change-hook nil
  3068. "Hook that is run after the tags in a line have changed.")
  3069. (defgroup org-properties nil
  3070. "Options concerning properties in Org mode."
  3071. :tag "Org Properties"
  3072. :group 'org)
  3073. (defcustom org-property-format "%-10s %s"
  3074. "How property key/value pairs should be formatted by `indent-line'.
  3075. When `indent-line' hits a property definition, it will format the line
  3076. according to this format, mainly to make sure that the values are
  3077. lined-up with respect to each other."
  3078. :group 'org-properties
  3079. :type 'string)
  3080. (defcustom org-properties-postprocess-alist nil
  3081. "Alist of properties and functions to adjust inserted values.
  3082. Elements of this alist must be of the form
  3083. ([string] [function])
  3084. where [string] must be a property name and [function] must be a
  3085. lambda expression: this lambda expression must take one argument,
  3086. the value to adjust, and return the new value as a string.
  3087. For example, this element will allow the property \"Remaining\"
  3088. to be updated wrt the relation between the \"Effort\" property
  3089. and the clock summary:
  3090. ((\"Remaining\" (lambda(value)
  3091. (let ((clocksum (org-clock-sum-current-item))
  3092. (effort (org-duration-to-minutes
  3093. (org-entry-get (point) \"Effort\"))))
  3094. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3095. :group 'org-properties
  3096. :version "24.1"
  3097. :type '(alist :key-type (string :tag "Property")
  3098. :value-type (function :tag "Function")))
  3099. (defcustom org-use-property-inheritance nil
  3100. "Non-nil means properties apply also for sublevels.
  3101. This setting is chiefly used during property searches. Turning it on can
  3102. cause significant overhead when doing a search, which is why it is not
  3103. on by default.
  3104. When nil, only the properties directly given in the current entry count.
  3105. When t, every property is inherited. The value may also be a list of
  3106. properties that should have inheritance, or a regular expression matching
  3107. properties that should be inherited.
  3108. However, note that some special properties use inheritance under special
  3109. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3110. and the properties ending in \"_ALL\" when they are used as descriptor
  3111. for valid values of a property.
  3112. Note for programmers:
  3113. When querying an entry with `org-entry-get', you can control if inheritance
  3114. should be used. By default, `org-entry-get' looks only at the local
  3115. properties. You can request inheritance by setting the inherit argument
  3116. to t (to force inheritance) or to `selective' (to respect the setting
  3117. in this variable)."
  3118. :group 'org-properties
  3119. :type '(choice
  3120. (const :tag "Not" nil)
  3121. (const :tag "Always" t)
  3122. (repeat :tag "Specific properties" (string :tag "Property"))
  3123. (regexp :tag "Properties matched by regexp")))
  3124. (defun org-property-inherit-p (property)
  3125. "Return a non-nil value if PROPERTY should be inherited."
  3126. (cond
  3127. ((eq org-use-property-inheritance t) t)
  3128. ((not org-use-property-inheritance) nil)
  3129. ((stringp org-use-property-inheritance)
  3130. (string-match org-use-property-inheritance property))
  3131. ((listp org-use-property-inheritance)
  3132. (member-ignore-case property org-use-property-inheritance))
  3133. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3134. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3135. "The default column format, if no other format has been defined.
  3136. This variable can be set on the per-file basis by inserting a line
  3137. #+COLUMNS: %25ITEM ....."
  3138. :group 'org-properties
  3139. :type 'string)
  3140. (defcustom org-columns-ellipses ".."
  3141. "The ellipses to be used when a field in column view is truncated.
  3142. When this is the empty string, as many characters as possible are shown,
  3143. but then there will be no visual indication that the field has been truncated.
  3144. When this is a string of length N, the last N characters of a truncated
  3145. field are replaced by this string. If the column is narrower than the
  3146. ellipses string, only part of the ellipses string will be shown."
  3147. :group 'org-properties
  3148. :type 'string)
  3149. (defconst org-global-properties-fixed
  3150. '(("VISIBILITY_ALL" . "folded children content all")
  3151. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3152. "List of property/value pairs that can be inherited by any entry.
  3153. These are fixed values, for the preset properties. The user variable
  3154. that can be used to add to this list is `org-global-properties'.
  3155. The entries in this list are cons cells where the car is a property
  3156. name and cdr is a string with the value. If the value represents
  3157. multiple items like an \"_ALL\" property, separate the items by
  3158. spaces.")
  3159. (defcustom org-global-properties nil
  3160. "List of property/value pairs that can be inherited by any entry.
  3161. This list will be combined with the constant `org-global-properties-fixed'.
  3162. The entries in this list are cons cells where the car is a property
  3163. name and cdr is a string with the value.
  3164. You can set buffer-local values for the same purpose in the variable
  3165. `org-file-properties' this by adding lines like
  3166. #+PROPERTY: NAME VALUE"
  3167. :group 'org-properties
  3168. :type '(repeat
  3169. (cons (string :tag "Property")
  3170. (string :tag "Value"))))
  3171. (defvar-local org-file-properties nil
  3172. "List of property/value pairs that can be inherited by any entry.
  3173. Valid for the current buffer.
  3174. This variable is populated from #+PROPERTY lines.")
  3175. (defgroup org-agenda nil
  3176. "Options concerning agenda views in Org mode."
  3177. :tag "Org Agenda"
  3178. :group 'org)
  3179. (defvar-local org-category nil
  3180. "Variable used by org files to set a category for agenda display.
  3181. Such files should use a file variable to set it, for example
  3182. # -*- mode: org; org-category: \"ELisp\"
  3183. or contain a special line
  3184. #+CATEGORY: ELisp
  3185. If the file does not specify a category, then file's base name
  3186. is used instead.")
  3187. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3188. (defcustom org-agenda-files nil
  3189. "The files to be used for agenda display.
  3190. If an entry is a directory, all files in that directory that are matched
  3191. by `org-agenda-file-regexp' will be part of the file list.
  3192. If the value of the variable is not a list but a single file name, then
  3193. the list of agenda files is actually stored and maintained in that file,
  3194. one agenda file per line. In this file paths can be given relative to
  3195. `org-directory'. Tilde expansion and environment variable substitution
  3196. are also made.
  3197. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3198. and removed with `\\[org-remove-file]'."
  3199. :group 'org-agenda
  3200. :type '(choice
  3201. (repeat :tag "List of files and directories" file)
  3202. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3203. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3204. "Regular expression to match files for `org-agenda-files'.
  3205. If any element in the list in that variable contains a directory instead
  3206. of a normal file, all files in that directory that are matched by this
  3207. regular expression will be included."
  3208. :group 'org-agenda
  3209. :type 'regexp)
  3210. (defcustom org-agenda-text-search-extra-files nil
  3211. "List of extra files to be searched by text search commands.
  3212. These files will be searched in addition to the agenda files by the
  3213. commands `org-search-view' (`\\[org-agenda] s') \
  3214. and `org-occur-in-agenda-files'.
  3215. Note that these files will only be searched for text search commands,
  3216. not for the other agenda views like todo lists, tag searches or the weekly
  3217. agenda. This variable is intended to list notes and possibly archive files
  3218. that should also be searched by these two commands.
  3219. In fact, if the first element in the list is the symbol `agenda-archives',
  3220. then all archive files of all agenda files will be added to the search
  3221. scope."
  3222. :group 'org-agenda
  3223. :type '(set :greedy t
  3224. (const :tag "Agenda Archives" agenda-archives)
  3225. (repeat :inline t (file))))
  3226. (defvaralias 'org-agenda-multi-occur-extra-files
  3227. 'org-agenda-text-search-extra-files)
  3228. (defcustom org-agenda-skip-unavailable-files nil
  3229. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3230. A nil value means to remove them, after a query, from the list."
  3231. :group 'org-agenda
  3232. :type 'boolean)
  3233. (defcustom org-calendar-to-agenda-key [?c]
  3234. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3235. The command `org-calendar-goto-agenda' will be bound to this key. The
  3236. default is the character `c' because then `c' can be used to switch back and
  3237. forth between agenda and calendar."
  3238. :group 'org-agenda
  3239. :type 'sexp)
  3240. (defcustom org-calendar-insert-diary-entry-key [?i]
  3241. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3242. This option is irrelevant until `org-agenda-diary-file' has been configured
  3243. to point to an Org file. When that is the case, the command
  3244. `org-agenda-diary-entry' will be bound to the key given here, by default
  3245. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3246. if you want to continue doing this, you need to change this to a different
  3247. key."
  3248. :group 'org-agenda
  3249. :type 'sexp)
  3250. (defcustom org-agenda-diary-file 'diary-file
  3251. "File to which to add new entries with the `i' key in agenda and calendar.
  3252. When this is the symbol `diary-file', the functionality in the Emacs
  3253. calendar will be used to add entries to the `diary-file'. But when this
  3254. points to a file, `org-agenda-diary-entry' will be used instead."
  3255. :group 'org-agenda
  3256. :type '(choice
  3257. (const :tag "The standard Emacs diary file" diary-file)
  3258. (file :tag "Special Org file diary entries")))
  3259. (eval-after-load "calendar"
  3260. '(progn
  3261. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3262. 'org-calendar-goto-agenda)
  3263. (add-hook 'calendar-mode-hook
  3264. (lambda ()
  3265. (unless (eq org-agenda-diary-file 'diary-file)
  3266. (define-key calendar-mode-map
  3267. org-calendar-insert-diary-entry-key
  3268. 'org-agenda-diary-entry))))))
  3269. (defgroup org-latex nil
  3270. "Options for embedding LaTeX code into Org mode."
  3271. :tag "Org LaTeX"
  3272. :group 'org)
  3273. (defcustom org-format-latex-options
  3274. '(:foreground default :background default :scale 1.0
  3275. :html-foreground "Black" :html-background "Transparent"
  3276. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3277. "Options for creating images from LaTeX fragments.
  3278. This is a property list with the following properties:
  3279. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3280. `default' means use the foreground of the default face.
  3281. `auto' means use the foreground from the text face.
  3282. :background the background color, or \"Transparent\".
  3283. `default' means use the background of the default face.
  3284. `auto' means use the background from the text face.
  3285. :scale a scaling factor for the size of the images, to get more pixels
  3286. :html-foreground, :html-background, :html-scale
  3287. the same numbers for HTML export.
  3288. :matchers a list indicating which matchers should be used to
  3289. find LaTeX fragments. Valid members of this list are:
  3290. \"begin\" find environments
  3291. \"$1\" find single characters surrounded by $.$
  3292. \"$\" find math expressions surrounded by $...$
  3293. \"$$\" find math expressions surrounded by $$....$$
  3294. \"\\(\" find math expressions surrounded by \\(...\\)
  3295. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3296. :group 'org-latex
  3297. :type 'plist)
  3298. (defcustom org-format-latex-signal-error t
  3299. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3300. When nil, just push out a message."
  3301. :group 'org-latex
  3302. :version "24.1"
  3303. :type 'boolean)
  3304. (defcustom org-latex-to-mathml-jar-file nil
  3305. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3306. Use this to specify additional executable file say a jar file.
  3307. When using MathToWeb as the converter, specify the full-path to
  3308. your mathtoweb.jar file."
  3309. :group 'org-latex
  3310. :version "24.1"
  3311. :type '(choice
  3312. (const :tag "None" nil)
  3313. (file :tag "JAR file" :must-match t)))
  3314. (defcustom org-latex-to-mathml-convert-command nil
  3315. "Command to convert LaTeX fragments to MathML.
  3316. Replace format-specifiers in the command as noted below and use
  3317. `shell-command' to convert LaTeX to MathML.
  3318. %j: Executable file in fully expanded form as specified by
  3319. `org-latex-to-mathml-jar-file'.
  3320. %I: Input LaTeX file in fully expanded form.
  3321. %i: The latex fragment to be converted.
  3322. %o: Output MathML file.
  3323. This command is used by `org-create-math-formula'.
  3324. When using MathToWeb as the converter, set this option to
  3325. \"java -jar %j -unicode -force -df %o %I\".
  3326. When using LaTeXML set this option to
  3327. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3328. :group 'org-latex
  3329. :version "24.1"
  3330. :type '(choice
  3331. (const :tag "None" nil)
  3332. (string :tag "\nShell command")))
  3333. (defcustom org-preview-latex-default-process 'dvipng
  3334. "The default process to convert LaTeX fragments to image files.
  3335. All available processes and theirs documents can be found in
  3336. `org-preview-latex-process-alist', which see."
  3337. :group 'org-latex
  3338. :version "26.1"
  3339. :package-version '(Org . "9.0")
  3340. :type 'symbol)
  3341. (defcustom org-preview-latex-process-alist
  3342. '((dvipng
  3343. :programs ("latex" "dvipng")
  3344. :description "dvi > png"
  3345. :message "you need to install the programs: latex and dvipng."
  3346. :image-input-type "dvi"
  3347. :image-output-type "png"
  3348. :image-size-adjust (1.0 . 1.0)
  3349. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3350. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3351. (dvisvgm
  3352. :programs ("latex" "dvisvgm")
  3353. :description "dvi > svg"
  3354. :message "you need to install the programs: latex and dvisvgm."
  3355. :use-xcolor t
  3356. :image-input-type "dvi"
  3357. :image-output-type "svg"
  3358. :image-size-adjust (1.7 . 1.5)
  3359. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3360. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3361. (imagemagick
  3362. :programs ("latex" "convert")
  3363. :description "pdf > png"
  3364. :message "you need to install the programs: latex and imagemagick."
  3365. :use-xcolor t
  3366. :image-input-type "pdf"
  3367. :image-output-type "png"
  3368. :image-size-adjust (1.0 . 1.0)
  3369. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3370. :image-converter
  3371. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3372. "Definitions of external processes for LaTeX previewing.
  3373. Org mode can use some external commands to generate TeX snippet's images for
  3374. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3375. `org-create-formula-image' how to call them.
  3376. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3377. PROPERTIES accepts the following attributes:
  3378. :programs list of strings, required programs.
  3379. :description string, describe the process.
  3380. :message string, message it when required programs cannot be found.
  3381. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3382. :image-output-type string, output file type of image converter (e.g., \"png\").
  3383. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3384. deal with background and foreground color of image.
  3385. Otherwise, dvipng style background and foreground color
  3386. format are generated. You may then refer to them in
  3387. command options with \"%F\" and \"%B\".
  3388. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3389. image size showed in buffer and the cdr element is for
  3390. HTML file. This option is only useful for process
  3391. developers, users should use variable
  3392. `org-format-latex-options' instead.
  3393. :post-clean list of strings, files matched are to be cleaned up once
  3394. the image is generated. When nil, the files with \".dvi\",
  3395. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3396. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3397. be cleaned up.
  3398. :latex-header list of strings, the LaTeX header of the snippet file.
  3399. When nil, the fallback value is used instead, which is
  3400. controlled by `org-format-latex-header',
  3401. `org-latex-default-packages-alist' and
  3402. `org-latex-packages-alist', which see.
  3403. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3404. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3405. replaced with values defined below.
  3406. :image-converter list of image converter commands strings. Each of them is
  3407. given to the shell and supports any of the following
  3408. place-holders defined below.
  3409. Place-holders used by `:image-converter' and `:latex-compiler':
  3410. %f input file name
  3411. %b base name of input file
  3412. %o base directory of input file
  3413. %O absolute output file name
  3414. Place-holders only used by `:image-converter':
  3415. %F foreground of image
  3416. %B background of image
  3417. %D dpi, which is used to adjust image size by some processing commands.
  3418. %S the image size scale ratio, which is used to adjust image size by some
  3419. processing commands."
  3420. :group 'org-latex
  3421. :version "26.1"
  3422. :package-version '(Org . "9.0")
  3423. :type '(alist :tag "LaTeX to image backends"
  3424. :value-type (plist)))
  3425. (defcustom org-preview-latex-image-directory "ltximg/"
  3426. "Path to store latex preview images.
  3427. A relative path here creates many directories relative to the
  3428. processed org files paths. An absolute path puts all preview
  3429. images at the same place."
  3430. :group 'org-latex
  3431. :version "26.1"
  3432. :package-version '(Org . "9.0")
  3433. :type 'string)
  3434. (defun org-format-latex-mathml-available-p ()
  3435. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3436. (save-match-data
  3437. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3438. org-latex-to-mathml-convert-command)
  3439. (let ((executable (car (split-string
  3440. org-latex-to-mathml-convert-command))))
  3441. (when (executable-find executable)
  3442. (if (string-match
  3443. "%j" org-latex-to-mathml-convert-command)
  3444. (file-readable-p org-latex-to-mathml-jar-file)
  3445. t))))))
  3446. (defcustom org-format-latex-header "\\documentclass{article}
  3447. \\usepackage[usenames]{color}
  3448. \[PACKAGES]
  3449. \[DEFAULT-PACKAGES]
  3450. \\pagestyle{empty} % do not remove
  3451. % The settings below are copied from fullpage.sty
  3452. \\setlength{\\textwidth}{\\paperwidth}
  3453. \\addtolength{\\textwidth}{-3cm}
  3454. \\setlength{\\oddsidemargin}{1.5cm}
  3455. \\addtolength{\\oddsidemargin}{-2.54cm}
  3456. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3457. \\setlength{\\textheight}{\\paperheight}
  3458. \\addtolength{\\textheight}{-\\headheight}
  3459. \\addtolength{\\textheight}{-\\headsep}
  3460. \\addtolength{\\textheight}{-\\footskip}
  3461. \\addtolength{\\textheight}{-3cm}
  3462. \\setlength{\\topmargin}{1.5cm}
  3463. \\addtolength{\\topmargin}{-2.54cm}"
  3464. "The document header used for processing LaTeX fragments.
  3465. It is imperative that this header make sure that no page number
  3466. appears on the page. The package defined in the variables
  3467. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3468. will either replace the placeholder \"[PACKAGES]\" in this
  3469. header, or they will be appended."
  3470. :group 'org-latex
  3471. :type 'string)
  3472. (defun org-set-packages-alist (var val)
  3473. "Set the packages alist and make sure it has 3 elements per entry."
  3474. (set var (mapcar (lambda (x)
  3475. (if (and (consp x) (= (length x) 2))
  3476. (list (car x) (nth 1 x) t)
  3477. x))
  3478. val)))
  3479. (defun org-get-packages-alist (var)
  3480. "Get the packages alist and make sure it has 3 elements per entry."
  3481. (mapcar (lambda (x)
  3482. (if (and (consp x) (= (length x) 2))
  3483. (list (car x) (nth 1 x) t)
  3484. x))
  3485. (default-value var)))
  3486. (defcustom org-latex-default-packages-alist
  3487. '(("AUTO" "inputenc" t ("pdflatex"))
  3488. ("T1" "fontenc" t ("pdflatex"))
  3489. ("" "graphicx" t)
  3490. ("" "grffile" t)
  3491. ("" "longtable" nil)
  3492. ("" "wrapfig" nil)
  3493. ("" "rotating" nil)
  3494. ("normalem" "ulem" t)
  3495. ("" "amsmath" t)
  3496. ("" "textcomp" t)
  3497. ("" "amssymb" t)
  3498. ("" "capt-of" nil)
  3499. ("" "hyperref" nil))
  3500. "Alist of default packages to be inserted in the header.
  3501. Change this only if one of the packages here causes an
  3502. incompatibility with another package you are using.
  3503. The packages in this list are needed by one part or another of
  3504. Org mode to function properly:
  3505. - inputenc, fontenc: for basic font and character selection
  3506. - graphicx: for including images
  3507. - grffile: allow periods and spaces in graphics file names
  3508. - longtable: For multipage tables
  3509. - wrapfig: for figure placement
  3510. - rotating: for sideways figures and tables
  3511. - ulem: for underline and strike-through
  3512. - amsmath: for subscript and superscript and math environments
  3513. - textcomp, amssymb: for various symbols used
  3514. for interpreting the entities in `org-entities'. You can skip
  3515. some of these packages if you don't use any of their symbols.
  3516. - capt-of: for captions outside of floats
  3517. - hyperref: for cross references
  3518. Therefore you should not modify this variable unless you know
  3519. what you are doing. The one reason to change it anyway is that
  3520. you might be loading some other package that conflicts with one
  3521. of the default packages. Each element is either a cell or
  3522. a string.
  3523. A cell is of the format
  3524. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3525. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3526. when compiling LaTeX snippets into images for inclusion into
  3527. non-LaTeX output. COMPILERS is a list of compilers that should
  3528. include the package, see `org-latex-compiler'. If the document
  3529. compiler is not in the list, and the list is non-nil, the package
  3530. will not be inserted in the final document.
  3531. A string will be inserted as-is in the header of the document."
  3532. :group 'org-latex
  3533. :group 'org-export-latex
  3534. :set 'org-set-packages-alist
  3535. :get 'org-get-packages-alist
  3536. :version "26.1"
  3537. :package-version '(Org . "8.3")
  3538. :type '(repeat
  3539. (choice
  3540. (list :tag "options/package pair"
  3541. (string :tag "options")
  3542. (string :tag "package")
  3543. (boolean :tag "Snippet")
  3544. (choice
  3545. (const :tag "For all compilers" nil)
  3546. (repeat :tag "Allowed compiler" string)))
  3547. (string :tag "A line of LaTeX"))))
  3548. (defcustom org-latex-packages-alist nil
  3549. "Alist of packages to be inserted in every LaTeX header.
  3550. These will be inserted after `org-latex-default-packages-alist'.
  3551. Each element is either a cell or a string.
  3552. A cell is of the format:
  3553. (\"options\" \"package\" SNIPPET-FLAG)
  3554. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3555. needed when turning LaTeX snippets into images for inclusion into
  3556. non-LaTeX output.
  3557. A string will be inserted as-is in the header of the document.
  3558. Make sure that you only list packages here which:
  3559. - you want in every file;
  3560. - do not conflict with the setup in `org-format-latex-header';
  3561. - do not conflict with the default packages in
  3562. `org-latex-default-packages-alist'."
  3563. :group 'org-latex
  3564. :group 'org-export-latex
  3565. :set 'org-set-packages-alist
  3566. :get 'org-get-packages-alist
  3567. :type '(repeat
  3568. (choice
  3569. (list :tag "options/package pair"
  3570. (string :tag "options")
  3571. (string :tag "package")
  3572. (boolean :tag "Snippet"))
  3573. (string :tag "A line of LaTeX"))))
  3574. (defgroup org-appearance nil
  3575. "Settings for Org mode appearance."
  3576. :tag "Org Appearance"
  3577. :group 'org)
  3578. (defcustom org-level-color-stars-only nil
  3579. "Non-nil means fontify only the stars in each headline.
  3580. When nil, the entire headline is fontified.
  3581. Changing it requires restart of `font-lock-mode' to become effective
  3582. also in regions already fontified."
  3583. :group 'org-appearance
  3584. :type 'boolean)
  3585. (defcustom org-hide-leading-stars nil
  3586. "Non-nil means hide the first N-1 stars in a headline.
  3587. This works by using the face `org-hide' for these stars. This
  3588. face is white for a light background, and black for a dark
  3589. background. You may have to customize the face `org-hide' to
  3590. make this work.
  3591. Changing it requires restart of `font-lock-mode' to become effective
  3592. also in regions already fontified.
  3593. You may also set this on a per-file basis by adding one of the following
  3594. lines to the buffer:
  3595. #+STARTUP: hidestars
  3596. #+STARTUP: showstars"
  3597. :group 'org-appearance
  3598. :type 'boolean)
  3599. (defcustom org-hidden-keywords nil
  3600. "List of symbols corresponding to keywords to be hidden the org buffer.
  3601. For example, a value \\='(title) for this list will make the document's title
  3602. appear in the buffer without the initial #+TITLE: keyword."
  3603. :group 'org-appearance
  3604. :version "24.1"
  3605. :type '(set (const :tag "#+AUTHOR" author)
  3606. (const :tag "#+DATE" date)
  3607. (const :tag "#+EMAIL" email)
  3608. (const :tag "#+TITLE" title)))
  3609. (defcustom org-custom-properties nil
  3610. "List of properties (as strings) with a special meaning.
  3611. The default use of these custom properties is to let the user
  3612. hide them with `org-toggle-custom-properties-visibility'."
  3613. :group 'org-properties
  3614. :group 'org-appearance
  3615. :version "24.3"
  3616. :type '(repeat (string :tag "Property Name")))
  3617. (defcustom org-fontify-done-headline nil
  3618. "Non-nil means change the face of a headline if it is marked DONE.
  3619. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3620. When this is non-nil, the headline after the keyword is set to the
  3621. `org-headline-done' as an additional indication."
  3622. :group 'org-appearance
  3623. :type 'boolean)
  3624. (defcustom org-fontify-emphasized-text t
  3625. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3626. Changing this variable requires a restart of Emacs to take effect."
  3627. :group 'org-appearance
  3628. :type 'boolean)
  3629. (defcustom org-fontify-whole-heading-line nil
  3630. "Non-nil means fontify the whole line for headings.
  3631. This is useful when setting a background color for the
  3632. org-level-* faces."
  3633. :group 'org-appearance
  3634. :type 'boolean)
  3635. (defcustom org-highlight-latex-and-related nil
  3636. "Non-nil means highlight LaTeX related syntax in the buffer.
  3637. When non nil, the value should be a list containing any of the
  3638. following symbols:
  3639. `latex' Highlight LaTeX snippets and environments.
  3640. `script' Highlight subscript and superscript.
  3641. `entities' Highlight entities."
  3642. :group 'org-appearance
  3643. :version "24.4"
  3644. :package-version '(Org . "8.0")
  3645. :type '(choice
  3646. (const :tag "No highlighting" nil)
  3647. (set :greedy t :tag "Highlight"
  3648. (const :tag "LaTeX snippets and environments" latex)
  3649. (const :tag "Subscript and superscript" script)
  3650. (const :tag "Entities" entities))))
  3651. (defcustom org-hide-emphasis-markers nil
  3652. "Non-nil mean font-lock should hide the emphasis marker characters."
  3653. :group 'org-appearance
  3654. :type 'boolean)
  3655. (defcustom org-hide-macro-markers nil
  3656. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3657. :group 'org-appearance
  3658. :type 'boolean)
  3659. (defcustom org-pretty-entities nil
  3660. "Non-nil means show entities as UTF8 characters.
  3661. When nil, the \\name form remains in the buffer."
  3662. :group 'org-appearance
  3663. :version "24.1"
  3664. :type 'boolean)
  3665. (defcustom org-pretty-entities-include-sub-superscripts t
  3666. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3667. :group 'org-appearance
  3668. :version "24.1"
  3669. :type 'boolean)
  3670. (defvar org-emph-re nil
  3671. "Regular expression for matching emphasis.
  3672. After a match, the match groups contain these elements:
  3673. 0 The match of the full regular expression, including the characters
  3674. before and after the proper match
  3675. 1 The character before the proper match, or empty at beginning of line
  3676. 2 The proper match, including the leading and trailing markers
  3677. 3 The leading marker like * or /, indicating the type of highlighting
  3678. 4 The text between the emphasis markers, not including the markers
  3679. 5 The character after the match, empty at the end of a line")
  3680. (defvar org-verbatim-re nil
  3681. "Regular expression for matching verbatim text.")
  3682. (defvar org-emphasis-regexp-components) ; defined just below
  3683. (defvar org-emphasis-alist) ; defined just below
  3684. (defun org-set-emph-re (var val)
  3685. "Set variable and compute the emphasis regular expression."
  3686. (set var val)
  3687. (when (and (boundp 'org-emphasis-alist)
  3688. (boundp 'org-emphasis-regexp-components)
  3689. org-emphasis-alist org-emphasis-regexp-components)
  3690. (pcase-let*
  3691. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3692. (body (if (<= nl 0) body
  3693. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3694. (template
  3695. (format (concat "\\([%s]\\|^\\)" ;before markers
  3696. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3697. "\\([%s]\\|$\\)") ;after markers
  3698. pre border border body border post)))
  3699. (setq org-emph-re (format template "*/_+"))
  3700. (setq org-verbatim-re (format template "=~")))))
  3701. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3702. ;; set this option proved cumbersome. See this message/thread:
  3703. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3704. (defvar org-emphasis-regexp-components
  3705. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3706. "Components used to build the regular expression for emphasis.
  3707. This is a list with five entries. Terminology: In an emphasis string
  3708. like \" *strong word* \", we call the initial space PREMATCH, the final
  3709. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3710. and \"trong wor\" is the body. The different components in this variable
  3711. specify what is allowed/forbidden in each part:
  3712. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3713. post Chars allowed as postmatch. End of line will be allowed too.
  3714. border The chars *forbidden* as border characters.
  3715. body-regexp A regexp like \".\" to match a body character. Don't use
  3716. non-shy groups here, and don't allow newline here.
  3717. newline The maximum number of newlines allowed in an emphasis exp.
  3718. You need to reload Org or to restart Emacs after setting this.")
  3719. (defcustom org-emphasis-alist
  3720. '(("*" bold)
  3721. ("/" italic)
  3722. ("_" underline)
  3723. ("=" org-verbatim verbatim)
  3724. ("~" org-code verbatim)
  3725. ("+" (:strike-through t)))
  3726. "Alist of characters and faces to emphasize text.
  3727. Text starting and ending with a special character will be emphasized,
  3728. for example *bold*, _underlined_ and /italic/. This variable sets the
  3729. marker characters and the face to be used by font-lock for highlighting
  3730. in Org buffers.
  3731. You need to reload Org or to restart Emacs after customizing this."
  3732. :group 'org-appearance
  3733. :set 'org-set-emph-re
  3734. :version "24.4"
  3735. :package-version '(Org . "8.0")
  3736. :type '(repeat
  3737. (list
  3738. (string :tag "Marker character")
  3739. (choice
  3740. (face :tag "Font-lock-face")
  3741. (plist :tag "Face property list"))
  3742. (option (const verbatim)))))
  3743. (defvar org-protecting-blocks '("src" "example" "export")
  3744. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3745. This is needed for font-lock setup.")
  3746. ;;; Functions and variables from their packages
  3747. ;; Declared here to avoid compiler warnings
  3748. (defvar mark-active)
  3749. ;; Various packages
  3750. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3751. (declare-function calendar-forward-day "cal-move" (arg))
  3752. (declare-function calendar-goto-date "cal-move" (date))
  3753. (declare-function calendar-goto-today "cal-move" ())
  3754. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3755. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3756. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3757. (declare-function cdlatex-tab "ext:cdlatex" ())
  3758. (declare-function dired-get-filename
  3759. "dired"
  3760. (&optional localp no-error-if-not-filep))
  3761. (declare-function iswitchb-read-buffer
  3762. "iswitchb"
  3763. (prompt &optional
  3764. default require-match _predicate start matches-set))
  3765. (declare-function org-agenda-change-all-lines
  3766. "org-agenda"
  3767. (newhead hdmarker &optional fixface just-this))
  3768. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3769. "org-agenda"
  3770. (&optional end))
  3771. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3772. (declare-function org-agenda-format-item
  3773. "org-agenda"
  3774. (extra txt &optional level category tags dotime
  3775. remove-re habitp))
  3776. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3777. (declare-function org-agenda-save-markers-for-cut-and-paste
  3778. "org-agenda"
  3779. (beg end))
  3780. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3781. (declare-function org-agenda-skip "org-agenda" ())
  3782. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3783. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3784. (declare-function org-indent-mode "org-indent" (&optional arg))
  3785. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3786. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3787. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3788. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3789. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3790. (declare-function parse-time-string "parse-time" (string))
  3791. (defvar align-mode-rules-list)
  3792. (defvar calc-embedded-close-formula)
  3793. (defvar calc-embedded-open-formula)
  3794. (defvar calc-embedded-open-mode)
  3795. (defvar font-lock-unfontify-region-function)
  3796. (defvar iswitchb-temp-buflist)
  3797. (defvar org-agenda-tags-todo-honor-ignore-options)
  3798. (defvar remember-data-file)
  3799. (defvar texmathp-why)
  3800. ;;;###autoload
  3801. (defun turn-on-orgtbl ()
  3802. "Unconditionally turn on `orgtbl-mode'."
  3803. (require 'org-table)
  3804. (orgtbl-mode 1))
  3805. (defun org-at-table-p (&optional table-type)
  3806. "Non-nil if the cursor is inside an Org table.
  3807. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3808. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3809. (or (not (derived-mode-p 'org-mode))
  3810. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3811. (and e (or table-type
  3812. (eq 'org (org-element-property :type e))))))))
  3813. (defun org-at-table.el-p ()
  3814. "Non-nil when point is at a table.el table."
  3815. (and (org-match-line "[ \t]*[|+]")
  3816. (let ((element (org-element-at-point)))
  3817. (and (eq (org-element-type element) 'table)
  3818. (eq (org-element-property :type element) 'table.el)))))
  3819. (defun org-at-table-hline-p ()
  3820. "Non-nil when point is inside a hline in a table.
  3821. Assume point is already in a table."
  3822. (org-match-line org-table-hline-regexp))
  3823. (defun org-table-map-tables (function &optional quietly)
  3824. "Apply FUNCTION to the start of all tables in the buffer."
  3825. (org-with-wide-buffer
  3826. (goto-char (point-min))
  3827. (while (re-search-forward org-table-any-line-regexp nil t)
  3828. (unless quietly
  3829. (message "Mapping tables: %d%%"
  3830. (floor (* 100.0 (point)) (buffer-size))))
  3831. (beginning-of-line 1)
  3832. (when (and (looking-at org-table-line-regexp)
  3833. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3834. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3835. (save-excursion (funcall function))
  3836. (or (looking-at org-table-line-regexp)
  3837. (forward-char 1)))
  3838. (re-search-forward org-table-any-border-regexp nil 1)))
  3839. (unless quietly (message "Mapping tables: done")))
  3840. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3841. (declare-function org-clock-update-mode-line "org-clock" ())
  3842. (declare-function org-resolve-clocks "org-clock"
  3843. (&optional also-non-dangling-p prompt last-valid))
  3844. (defun org-at-TBLFM-p (&optional pos)
  3845. "Non-nil when point (or POS) is in #+TBLFM line."
  3846. (save-excursion
  3847. (goto-char (or pos (point)))
  3848. (beginning-of-line)
  3849. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3850. (eq (org-element-type (org-element-at-point)) 'table))))
  3851. (defvar org-clock-start-time)
  3852. (defvar org-clock-marker (make-marker)
  3853. "Marker recording the last clock-in.")
  3854. (defvar org-clock-hd-marker (make-marker)
  3855. "Marker recording the last clock-in, but the headline position.")
  3856. (defvar org-clock-heading ""
  3857. "The heading of the current clock entry.")
  3858. (defun org-clock-is-active ()
  3859. "Return the buffer where the clock is currently running.
  3860. Return nil if no clock is running."
  3861. (marker-buffer org-clock-marker))
  3862. (defun org-check-running-clock ()
  3863. "Check if the current buffer contains the running clock.
  3864. If yes, offer to stop it and to save the buffer with the changes."
  3865. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3866. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3867. (buffer-name))))
  3868. (org-clock-out)
  3869. (when (y-or-n-p "Save changed buffer?")
  3870. (save-buffer))))
  3871. (defun org-clocktable-try-shift (dir n)
  3872. "Check if this line starts a clock table, if yes, shift the time block."
  3873. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3874. (org-clocktable-shift dir n)))
  3875. ;;;###autoload
  3876. (defun org-clock-persistence-insinuate ()
  3877. "Set up hooks for clock persistence."
  3878. (require 'org-clock)
  3879. (add-hook 'org-mode-hook 'org-clock-load)
  3880. (add-hook 'kill-emacs-hook 'org-clock-save))
  3881. (defgroup org-archive nil
  3882. "Options concerning archiving in Org mode."
  3883. :tag "Org Archive"
  3884. :group 'org-structure)
  3885. (defcustom org-archive-location "%s_archive::"
  3886. "The location where subtrees should be archived.
  3887. The value of this variable is a string, consisting of two parts,
  3888. separated by a double-colon. The first part is a filename and
  3889. the second part is a headline.
  3890. When the filename is omitted, archiving happens in the same file.
  3891. %s in the filename will be replaced by the current file
  3892. name (without the directory part). Archiving to a different file
  3893. is useful to keep archived entries from contributing to the
  3894. Org Agenda.
  3895. The archived entries will be filed as subtrees of the specified
  3896. headline. When the headline is omitted, the subtrees are simply
  3897. filed away at the end of the file, as top-level entries. Also in
  3898. the heading you can use %s to represent the file name, this can be
  3899. useful when using the same archive for a number of different files.
  3900. Here are a few examples:
  3901. \"%s_archive::\"
  3902. If the current file is Projects.org, archive in file
  3903. Projects.org_archive, as top-level trees. This is the default.
  3904. \"::* Archived Tasks\"
  3905. Archive in the current file, under the top-level headline
  3906. \"* Archived Tasks\".
  3907. \"~/org/archive.org::\"
  3908. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3909. \"~/org/archive.org::* From %s\"
  3910. Archive in file ~/org/archive.org (absolute path), under headlines
  3911. \"From FILENAME\" where file name is the current file name.
  3912. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3913. The \"datetree/\" string is special, signifying to archive
  3914. items to the datetree. Items are placed in either the CLOSED
  3915. date of the item, or the current date if there is no CLOSED date.
  3916. The heading will be a subentry to the current date. There doesn't
  3917. need to be a heading, but there always needs to be a slash after
  3918. datetree. For example, to store archived items directly in the
  3919. datetree, use \"~/org/datetree.org::datetree/\".
  3920. \"basement::** Finished Tasks\"
  3921. Archive in file ./basement (relative path), as level 3 trees
  3922. below the level 2 heading \"** Finished Tasks\".
  3923. You may set this option on a per-file basis by adding to the buffer a
  3924. line like
  3925. #+ARCHIVE: basement::** Finished Tasks
  3926. You may also define it locally for a subtree by setting an ARCHIVE property
  3927. in the entry. If such a property is found in an entry, or anywhere up
  3928. the hierarchy, it will be used."
  3929. :group 'org-archive
  3930. :type 'string)
  3931. (defcustom org-agenda-skip-archived-trees t
  3932. "Non-nil means the agenda will skip any items located in archived trees.
  3933. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3934. variable is no longer recommended, you should leave it at the value t.
  3935. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3936. :group 'org-archive
  3937. :group 'org-agenda-skip
  3938. :type 'boolean)
  3939. (defcustom org-columns-skip-archived-trees t
  3940. "Non-nil means ignore archived trees when creating column view."
  3941. :group 'org-archive
  3942. :group 'org-properties
  3943. :type 'boolean)
  3944. (defcustom org-cycle-open-archived-trees nil
  3945. "Non-nil means `org-cycle' will open archived trees.
  3946. An archived tree is a tree marked with the tag ARCHIVE.
  3947. When nil, archived trees will stay folded. You can still open them with
  3948. normal outline commands like `show-all', but not with the cycling commands."
  3949. :group 'org-archive
  3950. :group 'org-cycle
  3951. :type 'boolean)
  3952. (defcustom org-sparse-tree-open-archived-trees nil
  3953. "Non-nil means sparse tree construction shows matches in archived trees.
  3954. When nil, matches in these trees are highlighted, but the trees are kept in
  3955. collapsed state."
  3956. :group 'org-archive
  3957. :group 'org-sparse-trees
  3958. :type 'boolean)
  3959. (defcustom org-sparse-tree-default-date-type nil
  3960. "The default date type when building a sparse tree.
  3961. When this is nil, a date is a scheduled or a deadline timestamp.
  3962. Otherwise, these types are allowed:
  3963. all: all timestamps
  3964. active: only active timestamps (<...>)
  3965. inactive: only inactive timestamps ([...])
  3966. scheduled: only scheduled timestamps
  3967. deadline: only deadline timestamps"
  3968. :type '(choice (const :tag "Scheduled or deadline" nil)
  3969. (const :tag "All timestamps" all)
  3970. (const :tag "Only active timestamps" active)
  3971. (const :tag "Only inactive timestamps" inactive)
  3972. (const :tag "Only scheduled timestamps" scheduled)
  3973. (const :tag "Only deadline timestamps" deadline)
  3974. (const :tag "Only closed timestamps" closed))
  3975. :version "26.1"
  3976. :package-version '(Org . "8.3")
  3977. :group 'org-sparse-trees)
  3978. (defun org-cycle-hide-archived-subtrees (state)
  3979. "Re-hide all archived subtrees after a visibility state change.
  3980. STATE should be one of the symbols listed in the docstring of
  3981. `org-cycle-hook'."
  3982. (when (and (not org-cycle-open-archived-trees)
  3983. (not (memq state '(overview folded))))
  3984. (save-excursion
  3985. (let* ((globalp (memq state '(contents all)))
  3986. (beg (if globalp (point-min) (point)))
  3987. (end (if globalp (point-max) (org-end-of-subtree t))))
  3988. (org-hide-archived-subtrees beg end)
  3989. (goto-char beg)
  3990. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3991. (message "%s" (substitute-command-keys
  3992. "Subtree is archived and stays closed. Use \
  3993. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3994. (defun org-force-cycle-archived ()
  3995. "Cycle subtree even if it is archived."
  3996. (interactive)
  3997. (setq this-command 'org-cycle)
  3998. (let ((org-cycle-open-archived-trees t))
  3999. (call-interactively 'org-cycle)))
  4000. (defun org-hide-archived-subtrees (beg end)
  4001. "Re-hide all archived subtrees after a visibility state change."
  4002. (org-with-wide-buffer
  4003. (let ((case-fold-search nil)
  4004. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4005. (goto-char beg)
  4006. ;; Include headline point is currently on.
  4007. (beginning-of-line)
  4008. (while (and (< (point) end) (re-search-forward re end t))
  4009. (when (member org-archive-tag (org-get-tags))
  4010. (org-flag-subtree t)
  4011. (org-end-of-subtree t))))))
  4012. (declare-function outline-end-of-heading "outline" ())
  4013. (declare-function outline-flag-region "outline" (from to flag))
  4014. (defun org-flag-subtree (flag)
  4015. (save-excursion
  4016. (org-back-to-heading t)
  4017. (outline-end-of-heading)
  4018. (outline-flag-region (point)
  4019. (progn (org-end-of-subtree t) (point))
  4020. flag)))
  4021. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4022. ;; Declare Column View Code
  4023. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4024. (declare-function org-columns-compute "org-colview" (property))
  4025. ;; Declare ID code
  4026. (declare-function org-id-store-link "org-id")
  4027. (declare-function org-id-locations-load "org-id")
  4028. (declare-function org-id-locations-save "org-id")
  4029. (defvar org-id-track-globally)
  4030. ;;; Variables for pre-computed regular expressions, all buffer local
  4031. (defvar-local org-todo-regexp nil
  4032. "Matches any of the TODO state keywords.
  4033. Since TODO keywords are case-sensitive, `case-fold-search' is
  4034. expected to be bound to nil when matching against this regexp.")
  4035. (defvar-local org-not-done-regexp nil
  4036. "Matches any of the TODO state keywords except the last one.
  4037. Since TODO keywords are case-sensitive, `case-fold-search' is
  4038. expected to be bound to nil when matching against this regexp.")
  4039. (defvar-local org-not-done-heading-regexp nil
  4040. "Matches a TODO headline that is not done.
  4041. Since TODO keywords are case-sensitive, `case-fold-search' is
  4042. expected to be bound to nil when matching against this regexp.")
  4043. (defvar-local org-todo-line-regexp nil
  4044. "Matches a headline and puts TODO state into group 2 if present.
  4045. Since TODO keywords are case-sensitive, `case-fold-search' is
  4046. expected to be bound to nil when matching against this regexp.")
  4047. (defvar-local org-complex-heading-regexp nil
  4048. "Matches a headline and puts everything into groups:
  4049. group 1: Stars
  4050. group 2: The TODO keyword, maybe
  4051. group 3: Priority cookie
  4052. group 4: True headline
  4053. group 5: Tags
  4054. Since TODO keywords are case-sensitive, `case-fold-search' is
  4055. expected to be bound to nil when matching against this regexp.")
  4056. (defvar-local org-complex-heading-regexp-format nil
  4057. "Printf format to make regexp to match an exact headline.
  4058. This regexp will match the headline of any node which has the
  4059. exact headline text that is put into the format, but may have any
  4060. TODO state, priority and tags.")
  4061. (defvar-local org-todo-line-tags-regexp nil
  4062. "Matches a headline and puts TODO state into group 2 if present.
  4063. Also put tags into group 4 if tags are present.")
  4064. (defconst org-plain-time-of-day-regexp
  4065. (concat
  4066. "\\(\\<[012]?[0-9]"
  4067. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4068. "\\(--?"
  4069. "\\(\\<[012]?[0-9]"
  4070. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4071. "\\)?")
  4072. "Regular expression to match a plain time or time range.
  4073. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4074. groups carry important information:
  4075. 0 the full match
  4076. 1 the first time, range or not
  4077. 8 the second time, if it is a range.")
  4078. (defconst org-plain-time-extension-regexp
  4079. (concat
  4080. "\\(\\<[012]?[0-9]"
  4081. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4082. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4083. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4084. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4085. groups carry important information:
  4086. 0 the full match
  4087. 7 hours of duration
  4088. 9 minutes of duration")
  4089. (defconst org-stamp-time-of-day-regexp
  4090. (concat
  4091. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4092. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4093. "\\(--?"
  4094. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4095. "Regular expression to match a timestamp time or time range.
  4096. After a match, the following groups carry important information:
  4097. 0 the full match
  4098. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4099. 2 the first time, range or not
  4100. 4 the second time, if it is a range.")
  4101. (defconst org-startup-options
  4102. '(("fold" org-startup-folded t)
  4103. ("overview" org-startup-folded t)
  4104. ("nofold" org-startup-folded nil)
  4105. ("showall" org-startup-folded nil)
  4106. ("showeverything" org-startup-folded showeverything)
  4107. ("content" org-startup-folded content)
  4108. ("indent" org-startup-indented t)
  4109. ("noindent" org-startup-indented nil)
  4110. ("hidestars" org-hide-leading-stars t)
  4111. ("showstars" org-hide-leading-stars nil)
  4112. ("odd" org-odd-levels-only t)
  4113. ("oddeven" org-odd-levels-only nil)
  4114. ("align" org-startup-align-all-tables t)
  4115. ("noalign" org-startup-align-all-tables nil)
  4116. ("shrink" org-startup-shrink-all-tables t)
  4117. ("inlineimages" org-startup-with-inline-images t)
  4118. ("noinlineimages" org-startup-with-inline-images nil)
  4119. ("latexpreview" org-startup-with-latex-preview t)
  4120. ("nolatexpreview" org-startup-with-latex-preview nil)
  4121. ("customtime" org-display-custom-times t)
  4122. ("logdone" org-log-done time)
  4123. ("lognotedone" org-log-done note)
  4124. ("nologdone" org-log-done nil)
  4125. ("lognoteclock-out" org-log-note-clock-out t)
  4126. ("nolognoteclock-out" org-log-note-clock-out nil)
  4127. ("logrepeat" org-log-repeat state)
  4128. ("lognoterepeat" org-log-repeat note)
  4129. ("logdrawer" org-log-into-drawer t)
  4130. ("nologdrawer" org-log-into-drawer nil)
  4131. ("logstatesreversed" org-log-states-order-reversed t)
  4132. ("nologstatesreversed" org-log-states-order-reversed nil)
  4133. ("nologrepeat" org-log-repeat nil)
  4134. ("logreschedule" org-log-reschedule time)
  4135. ("lognotereschedule" org-log-reschedule note)
  4136. ("nologreschedule" org-log-reschedule nil)
  4137. ("logredeadline" org-log-redeadline time)
  4138. ("lognoteredeadline" org-log-redeadline note)
  4139. ("nologredeadline" org-log-redeadline nil)
  4140. ("logrefile" org-log-refile time)
  4141. ("lognoterefile" org-log-refile note)
  4142. ("nologrefile" org-log-refile nil)
  4143. ("fninline" org-footnote-define-inline t)
  4144. ("nofninline" org-footnote-define-inline nil)
  4145. ("fnlocal" org-footnote-section nil)
  4146. ("fnauto" org-footnote-auto-label t)
  4147. ("fnprompt" org-footnote-auto-label nil)
  4148. ("fnconfirm" org-footnote-auto-label confirm)
  4149. ("fnplain" org-footnote-auto-label plain)
  4150. ("fnadjust" org-footnote-auto-adjust t)
  4151. ("nofnadjust" org-footnote-auto-adjust nil)
  4152. ("constcgs" constants-unit-system cgs)
  4153. ("constSI" constants-unit-system SI)
  4154. ("noptag" org-tag-persistent-alist nil)
  4155. ("hideblocks" org-hide-block-startup t)
  4156. ("nohideblocks" org-hide-block-startup nil)
  4157. ("beamer" org-startup-with-beamer-mode t)
  4158. ("entitiespretty" org-pretty-entities t)
  4159. ("entitiesplain" org-pretty-entities nil))
  4160. "Variable associated with STARTUP options for org-mode.
  4161. Each element is a list of three items: the startup options (as written
  4162. in the #+STARTUP line), the corresponding variable, and the value to set
  4163. this variable to if the option is found. An optional forth element PUSH
  4164. means to push this value onto the list in the variable.")
  4165. (defcustom org-group-tags t
  4166. "When non-nil (the default), use group tags.
  4167. This can be turned on/off through `org-toggle-tags-groups'."
  4168. :group 'org-tags
  4169. :group 'org-startup
  4170. :type 'boolean)
  4171. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4172. (defun org-toggle-tags-groups ()
  4173. "Toggle support for group tags.
  4174. Support for group tags is controlled by the option
  4175. `org-group-tags', which is non-nil by default."
  4176. (interactive)
  4177. (setq org-group-tags (not org-group-tags))
  4178. (cond ((and (derived-mode-p 'org-agenda-mode)
  4179. org-group-tags)
  4180. (org-agenda-redo))
  4181. ((derived-mode-p 'org-mode)
  4182. (let ((org-inhibit-startup t)) (org-mode))))
  4183. (message "Groups tags support has been turned %s"
  4184. (if org-group-tags "on" "off")))
  4185. (defun org-set-regexps-and-options (&optional tags-only)
  4186. "Precompute regular expressions used in the current buffer.
  4187. When optional argument TAGS-ONLY is non-nil, only compute tags
  4188. related expressions."
  4189. (when (derived-mode-p 'org-mode)
  4190. (let ((alist (org--setup-collect-keywords
  4191. (org-make-options-regexp
  4192. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4193. (and (not tags-only)
  4194. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4195. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4196. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4197. ;; Startup options. Get this early since it does change
  4198. ;; behavior for other options (e.g., tags).
  4199. (let ((startup (cdr (assq 'startup alist))))
  4200. (dolist (option startup)
  4201. (let ((entry (assoc-string option org-startup-options t)))
  4202. (when entry
  4203. (let ((var (nth 1 entry))
  4204. (val (nth 2 entry)))
  4205. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4206. (unless (listp (symbol-value var))
  4207. (set (make-local-variable var) nil))
  4208. (add-to-list var val)))))))
  4209. (setq-local org-file-tags
  4210. (mapcar #'org-add-prop-inherited
  4211. (cdr (assq 'filetags alist))))
  4212. (setq org-current-tag-alist
  4213. (append org-tag-persistent-alist
  4214. (let ((tags (cdr (assq 'tags alist))))
  4215. (if tags (org-tag-string-to-alist tags)
  4216. org-tag-alist))))
  4217. (setq org-tag-groups-alist
  4218. (org-tag-alist-to-groups org-current-tag-alist))
  4219. (unless tags-only
  4220. ;; File properties.
  4221. (setq-local org-file-properties (cdr (assq 'property alist)))
  4222. ;; Archive location.
  4223. (let ((archive (cdr (assq 'archive alist))))
  4224. (when archive (setq-local org-archive-location archive)))
  4225. ;; Category.
  4226. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4227. (when cat
  4228. (setq-local org-category (intern cat))
  4229. (setq-local org-file-properties
  4230. (org--update-property-plist
  4231. "CATEGORY" cat org-file-properties))))
  4232. ;; Columns.
  4233. (let ((column (cdr (assq 'columns alist))))
  4234. (when column (setq-local org-columns-default-format column)))
  4235. ;; Constants.
  4236. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4237. ;; Link abbreviations.
  4238. (let ((links (cdr (assq 'link alist))))
  4239. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4240. ;; Priorities.
  4241. (let ((priorities (cdr (assq 'priorities alist))))
  4242. (when priorities
  4243. (setq-local org-highest-priority (nth 0 priorities))
  4244. (setq-local org-lowest-priority (nth 1 priorities))
  4245. (setq-local org-default-priority (nth 2 priorities))))
  4246. ;; Scripts.
  4247. (let ((scripts (assq 'scripts alist)))
  4248. (when scripts
  4249. (setq-local org-use-sub-superscripts (cdr scripts))))
  4250. ;; TODO keywords.
  4251. (setq-local org-todo-kwd-alist nil)
  4252. (setq-local org-todo-key-alist nil)
  4253. (setq-local org-todo-key-trigger nil)
  4254. (setq-local org-todo-keywords-1 nil)
  4255. (setq-local org-done-keywords nil)
  4256. (setq-local org-todo-heads nil)
  4257. (setq-local org-todo-sets nil)
  4258. (setq-local org-todo-log-states nil)
  4259. (let ((todo-sequences
  4260. (or (nreverse (cdr (assq 'todo alist)))
  4261. (let ((d (default-value 'org-todo-keywords)))
  4262. (if (not (stringp (car d))) d
  4263. ;; XXX: Backward compatibility code.
  4264. (list (cons org-todo-interpretation d)))))))
  4265. (dolist (sequence todo-sequences)
  4266. (let* ((sequence (or (run-hook-with-args-until-success
  4267. 'org-todo-setup-filter-hook sequence)
  4268. sequence))
  4269. (sequence-type (car sequence))
  4270. (keywords (cdr sequence))
  4271. (sep (member "|" keywords))
  4272. names alist)
  4273. (dolist (k (remove "|" keywords))
  4274. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4275. k)
  4276. (error "Invalid TODO keyword %s" k))
  4277. (let ((name (match-string 1 k))
  4278. (key (match-string 2 k))
  4279. (log (org-extract-log-state-settings k)))
  4280. (push name names)
  4281. (push (cons name (and key (string-to-char key))) alist)
  4282. (when log (push log org-todo-log-states))))
  4283. (let* ((names (nreverse names))
  4284. (done (if sep (org-remove-keyword-keys (cdr sep))
  4285. (last names)))
  4286. (head (car names))
  4287. (tail (list sequence-type head (car done) (org-last done))))
  4288. (add-to-list 'org-todo-heads head 'append)
  4289. (push names org-todo-sets)
  4290. (setq org-done-keywords (append org-done-keywords done nil))
  4291. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4292. (setq org-todo-key-alist
  4293. (append org-todo-key-alist
  4294. (and alist
  4295. (append '((:startgroup))
  4296. (nreverse alist)
  4297. '((:endgroup))))))
  4298. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4299. (setq org-todo-sets (nreverse org-todo-sets)
  4300. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4301. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4302. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4303. ;; Compute the regular expressions and other local variables.
  4304. ;; Using `org-outline-regexp-bol' would complicate them much,
  4305. ;; because of the fixed white space at the end of that string.
  4306. (unless org-done-keywords
  4307. (setq org-done-keywords
  4308. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4309. (setq org-not-done-keywords
  4310. (org-delete-all org-done-keywords
  4311. (copy-sequence org-todo-keywords-1))
  4312. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4313. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4314. org-not-done-heading-regexp
  4315. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4316. org-todo-line-regexp
  4317. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4318. org-complex-heading-regexp
  4319. (concat "^\\(\\*+\\)"
  4320. "\\(?: +" org-todo-regexp "\\)?"
  4321. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4322. "\\(?: +\\(.*?\\)\\)??"
  4323. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4324. "[ \t]*$")
  4325. org-complex-heading-regexp-format
  4326. (concat "^\\(\\*+\\)"
  4327. "\\(?: +" org-todo-regexp "\\)?"
  4328. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4329. "\\(?: +"
  4330. ;; Stats cookies can be stuck to body.
  4331. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4332. "\\(%s\\)"
  4333. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4334. "\\)"
  4335. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4336. "[ \t]*$")
  4337. org-todo-line-tags-regexp
  4338. (concat "^\\(\\*+\\)"
  4339. "\\(?: +" org-todo-regexp "\\)?"
  4340. "\\(?: +\\(.*?\\)\\)??"
  4341. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4342. "[ \t]*$"))
  4343. (org-compute-latex-and-related-regexp)))))
  4344. (defun org--setup-collect-keywords (regexp &optional files alist)
  4345. "Return setup keywords values as an alist.
  4346. REGEXP matches a subset of setup keywords. FILES is a list of
  4347. file names already visited. It is used to avoid circular setup
  4348. files. ALIST, when non-nil, is the alist computed so far.
  4349. Return value contains the following keys: `archive', `category',
  4350. `columns', `constants', `filetags', `link', `priorities',
  4351. `property', `scripts', `startup', `tags' and `todo'."
  4352. (org-with-wide-buffer
  4353. (goto-char (point-min))
  4354. (let ((case-fold-search t))
  4355. (while (re-search-forward regexp nil t)
  4356. (let ((element (org-element-at-point)))
  4357. (when (eq (org-element-type element) 'keyword)
  4358. (let ((key (org-element-property :key element))
  4359. (value (org-element-property :value element)))
  4360. (cond
  4361. ((equal key "ARCHIVE")
  4362. (when (org-string-nw-p value)
  4363. (push (cons 'archive value) alist)))
  4364. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4365. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4366. ((equal key "CONSTANTS")
  4367. (let* ((constants (assq 'constants alist))
  4368. (store (cdr constants)))
  4369. (dolist (pair (split-string value))
  4370. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4371. pair)
  4372. (let* ((name (match-string 1 pair))
  4373. (value (match-string 2 pair))
  4374. (old (assoc name store)))
  4375. (if old (setcdr old value)
  4376. (push (cons name value) store)))))
  4377. (if constants (setcdr constants store)
  4378. (push (cons 'constants store) alist))))
  4379. ((equal key "FILETAGS")
  4380. (when (org-string-nw-p value)
  4381. (let ((old (assq 'filetags alist))
  4382. (new (apply #'nconc
  4383. (mapcar (lambda (x) (org-split-string x ":"))
  4384. (split-string value)))))
  4385. (if old (setcdr old (append new (cdr old)))
  4386. (push (cons 'filetags new) alist)))))
  4387. ((equal key "LINK")
  4388. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4389. (let ((links (assq 'link alist))
  4390. (pair (cons (match-string-no-properties 1 value)
  4391. (match-string-no-properties 2 value))))
  4392. (if links (push pair (cdr links))
  4393. (push (list 'link pair) alist)))))
  4394. ((equal key "OPTIONS")
  4395. (when (and (org-string-nw-p value)
  4396. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4397. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4398. ((equal key "PRIORITIES")
  4399. (push (cons 'priorities
  4400. (let ((prio (split-string value)))
  4401. (if (< (length prio) 3) '(?A ?C ?B)
  4402. (mapcar #'string-to-char prio))))
  4403. alist))
  4404. ((equal key "PROPERTY")
  4405. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4406. (let* ((property (assq 'property alist))
  4407. (value (org--update-property-plist
  4408. (match-string-no-properties 1 value)
  4409. (match-string-no-properties 2 value)
  4410. (cdr property))))
  4411. (if property (setcdr property value)
  4412. (push (cons 'property value) alist)))))
  4413. ((equal key "STARTUP")
  4414. (let ((startup (assq 'startup alist)))
  4415. (if startup
  4416. (setcdr startup
  4417. (append (cdr startup) (split-string value)))
  4418. (push (cons 'startup (split-string value)) alist))))
  4419. ((equal key "TAGS")
  4420. (let ((tag-cell (assq 'tags alist)))
  4421. (if tag-cell
  4422. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4423. (push (cons 'tags value) alist))))
  4424. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4425. (let ((todo (assq 'todo alist))
  4426. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4427. (split-string value))))
  4428. (if todo (push value (cdr todo))
  4429. (push (list 'todo value) alist))))
  4430. ((equal key "SETUPFILE")
  4431. (unless buffer-read-only ; Do not check in Gnus messages.
  4432. (let ((f (and (org-string-nw-p value)
  4433. (expand-file-name
  4434. (org-unbracket-string "\"" "\"" value)))))
  4435. (when (and f (file-readable-p f) (not (member f files)))
  4436. (with-temp-buffer
  4437. (setq default-directory (file-name-directory f))
  4438. (insert-file-contents f)
  4439. (setq alist
  4440. ;; Fake Org mode to benefit from cache
  4441. ;; without recurring needlessly.
  4442. (let ((major-mode 'org-mode))
  4443. (org--setup-collect-keywords
  4444. regexp (cons f files) alist)))))))))))))))
  4445. alist)
  4446. (defun org-tag-string-to-alist (s)
  4447. "Return tag alist associated to string S.
  4448. S is a value for TAGS keyword or produced with
  4449. `org-tag-alist-to-string'. Return value is an alist suitable for
  4450. `org-tag-alist' or `org-tag-persistent-alist'."
  4451. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4452. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4453. "\\|{.+?}\\)" ; regular expression
  4454. "\\(?:(\\(.\\))\\)?\\'"))
  4455. alist group-flag)
  4456. (dolist (tokens lines (cdr (nreverse alist)))
  4457. (push '(:newline) alist)
  4458. (while tokens
  4459. (let ((token (pop tokens)))
  4460. (pcase token
  4461. ("{"
  4462. (push '(:startgroup) alist)
  4463. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4464. ("}"
  4465. (push '(:endgroup) alist)
  4466. (setq group-flag nil))
  4467. ("["
  4468. (push '(:startgrouptag) alist)
  4469. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4470. ("]"
  4471. (push '(:endgrouptag) alist)
  4472. (setq group-flag nil))
  4473. (":"
  4474. (push '(:grouptags) alist))
  4475. ((guard (string-match tag-re token))
  4476. (let ((tag (match-string 1 token))
  4477. (key (and (match-beginning 2)
  4478. (string-to-char (match-string 2 token)))))
  4479. ;; Push all tags in groups, no matter if they already
  4480. ;; appear somewhere else in the list.
  4481. (when (or group-flag (not (assoc tag alist)))
  4482. (push (cons tag key) alist))))))))))
  4483. (defun org-tag-alist-to-string (alist &optional skip-key)
  4484. "Return tag string associated to ALIST.
  4485. ALIST is an alist, as defined in `org-tag-alist' or
  4486. `org-tag-persistent-alist', or produced with
  4487. `org-tag-string-to-alist'.
  4488. Return value is a string suitable as a value for \"TAGS\"
  4489. keyword.
  4490. When optional argument SKIP-KEY is non-nil, skip selection keys
  4491. next to tags."
  4492. (mapconcat (lambda (token)
  4493. (pcase token
  4494. (`(:startgroup) "{")
  4495. (`(:endgroup) "}")
  4496. (`(:startgrouptag) "[")
  4497. (`(:endgrouptag) "]")
  4498. (`(:grouptags) ":")
  4499. (`(:newline) "\\n")
  4500. ((and
  4501. (guard (not skip-key))
  4502. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4503. (format "%s(%c)" tag key))
  4504. (`(,(and tag (pred stringp)) . ,_) tag)
  4505. (_ (user-error "Invalid tag token: %S" token))))
  4506. alist
  4507. " "))
  4508. (defun org-tag-alist-to-groups (alist)
  4509. "Return group alist from tag ALIST.
  4510. ALIST is an alist, as defined in `org-tag-alist' or
  4511. `org-tag-persistent-alist', or produced with
  4512. `org-tag-string-to-alist'. Return value is an alist following
  4513. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4514. a string, summarizing TAGS, as a list of strings."
  4515. (let (groups group-status current-group)
  4516. (dolist (token alist (nreverse groups))
  4517. (pcase token
  4518. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4519. (`(,(or :endgroup :endgrouptag))
  4520. (when (eq group-status 'append)
  4521. (push (nreverse current-group) groups))
  4522. (setq group-status nil))
  4523. (`(:grouptags) (setq group-status 'append))
  4524. ((and `(,tag . ,_) (guard group-status))
  4525. (if (eq group-status 'append) (push tag current-group)
  4526. (setq current-group (list tag))))
  4527. (_ nil)))))
  4528. (defvar org--file-cache (make-hash-table :test #'equal)
  4529. "Hash table to store contents of files referenced via a URL.
  4530. This is the cache of file URLs read using `org-file-contents'.")
  4531. (defun org-reset-file-cache ()
  4532. "Reset the cache of files downloaded by `org-file-contents'."
  4533. (clrhash org--file-cache))
  4534. (defun org-file-url-p (file)
  4535. "Non-nil if FILE is a URL."
  4536. (require 'ffap)
  4537. (string-match-p ffap-url-regexp file))
  4538. (defun org-file-contents (file &optional noerror nocache)
  4539. "Return the contents of FILE, as a string.
  4540. FILE can be a file name or URL.
  4541. If FILE is a URL, download the contents. If the URL contents are
  4542. already cached in the `org--file-cache' hash table, the download step
  4543. is skipped.
  4544. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4545. from file or URL.
  4546. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4547. is available. This option applies only if FILE is a URL."
  4548. (let* ((is-url (org-file-url-p file))
  4549. (cache (and is-url
  4550. (not nocache)
  4551. (gethash file org--file-cache))))
  4552. (cond
  4553. (cache)
  4554. (is-url
  4555. (with-current-buffer (url-retrieve-synchronously file)
  4556. (goto-char (point-min))
  4557. ;; Move point to after the url-retrieve header.
  4558. (search-forward "\n\n" nil :move)
  4559. ;; Search for the success code only in the url-retrieve header.
  4560. (if (save-excursion
  4561. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4562. ;; Update the cache `org--file-cache' and return contents.
  4563. (puthash file
  4564. (buffer-substring-no-properties (point) (point-max))
  4565. org--file-cache)
  4566. (funcall (if noerror #'message #'user-error)
  4567. "Unable to fetch file from %S"
  4568. file))))
  4569. (t
  4570. (with-temp-buffer
  4571. (condition-case nil
  4572. (progn
  4573. (insert-file-contents file)
  4574. (buffer-string))
  4575. (file-error
  4576. (funcall (if noerror #'message #'user-error)
  4577. "Unable to read file %S"
  4578. file))))))))
  4579. (defun org-extract-log-state-settings (x)
  4580. "Extract the log state setting from a TODO keyword string.
  4581. This will extract info from a string like \"WAIT(w@/!)\"."
  4582. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4583. (let ((kw (match-string 1 x))
  4584. (log1 (and (match-end 3) (match-string 3 x)))
  4585. (log2 (and (match-end 4) (match-string 4 x))))
  4586. (and (or log1 log2)
  4587. (list kw
  4588. (and log1 (if (equal log1 "!") 'time 'note))
  4589. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4590. (defun org-remove-keyword-keys (list)
  4591. "Remove a pair of parenthesis at the end of each string in LIST."
  4592. (mapcar (lambda (x)
  4593. (if (string-match "(.*)$" x)
  4594. (substring x 0 (match-beginning 0))
  4595. x))
  4596. list))
  4597. (defun org-assign-fast-keys (alist)
  4598. "Assign fast keys to a keyword-key alist.
  4599. Respect keys that are already there."
  4600. (let (new e (alt ?0))
  4601. (while (setq e (pop alist))
  4602. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4603. (cdr e)) ;; Key already assigned.
  4604. (push e new)
  4605. (let ((clist (string-to-list (downcase (car e))))
  4606. (used (append new alist)))
  4607. (when (= (car clist) ?@)
  4608. (pop clist))
  4609. (while (and clist (rassoc (car clist) used))
  4610. (pop clist))
  4611. (unless clist
  4612. (while (rassoc alt used)
  4613. (cl-incf alt)))
  4614. (push (cons (car e) (or (car clist) alt)) new))))
  4615. (nreverse new)))
  4616. ;;; Some variables used in various places
  4617. (defvar org-window-configuration nil
  4618. "Used in various places to store a window configuration.")
  4619. (defvar org-selected-window nil
  4620. "Used in various places to store a window configuration.")
  4621. (defvar org-finish-function nil
  4622. "Function to be called when `C-c C-c' is used.
  4623. This is for getting out of special buffers like capture.")
  4624. (defvar org-last-state)
  4625. ;; Defined somewhere in this file, but used before definition.
  4626. (defvar org-entities) ;; defined in org-entities.el
  4627. (defvar org-struct-menu)
  4628. (defvar org-org-menu)
  4629. (defvar org-tbl-menu)
  4630. ;;;; Define the Org mode
  4631. ;; We use a before-change function to check if a table might need
  4632. ;; an update.
  4633. (defvar org-table-may-need-update t
  4634. "Indicates that a table might need an update.
  4635. This variable is set by `org-before-change-function'.
  4636. `org-table-align' sets it back to nil.")
  4637. (defun org-before-change-function (_beg _end)
  4638. "Every change indicates that a table might need an update."
  4639. (setq org-table-may-need-update t))
  4640. (defvar org-mode-map)
  4641. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4642. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4643. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4644. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4645. (defvar org-table-buffer-is-an nil)
  4646. (defvar bidi-paragraph-direction)
  4647. (defvar buffer-face-mode-face)
  4648. (require 'outline)
  4649. ;; Other stuff we need.
  4650. (require 'time-date)
  4651. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4652. (require 'easymenu)
  4653. (autoload 'easy-menu-add "easymenu")
  4654. (require 'overlay)
  4655. ;; (require 'org-macs) moved higher up in the file before it is first used
  4656. (require 'org-entities)
  4657. ;; (require 'org-compat) moved higher up in the file before it is first used
  4658. (require 'org-faces)
  4659. (require 'org-list)
  4660. (require 'org-pcomplete)
  4661. (require 'org-src)
  4662. (require 'org-footnote)
  4663. (require 'org-macro)
  4664. ;; babel
  4665. (require 'ob)
  4666. ;;;###autoload
  4667. (define-derived-mode org-mode outline-mode "Org"
  4668. "Outline-based notes management and organizer, alias
  4669. \"Carsten's outline-mode for keeping track of everything.\"
  4670. Org mode develops organizational tasks around a NOTES file which
  4671. contains information about projects as plain text. Org mode is
  4672. implemented on top of Outline mode, which is ideal to keep the content
  4673. of large files well structured. It supports ToDo items, deadlines and
  4674. time stamps, which magically appear in the diary listing of the Emacs
  4675. calendar. Tables are easily created with a built-in table editor.
  4676. Plain text URL-like links connect to websites, emails (VM), Usenet
  4677. messages (Gnus), BBDB entries, and any files related to the project.
  4678. For printing and sharing of notes, an Org file (or a part of it)
  4679. can be exported as a structured ASCII or HTML file.
  4680. The following commands are available:
  4681. \\{org-mode-map}"
  4682. ;; Get rid of Outline menus, they are not needed
  4683. ;; Need to do this here because define-derived-mode sets up
  4684. ;; the keymap so late. Still, it is a waste to call this each time
  4685. ;; we switch another buffer into Org mode.
  4686. (define-key org-mode-map [menu-bar headings] 'undefined)
  4687. (define-key org-mode-map [menu-bar hide] 'undefined)
  4688. (define-key org-mode-map [menu-bar show] 'undefined)
  4689. (org-load-modules-maybe)
  4690. (org-install-agenda-files-menu)
  4691. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4692. (add-to-invisibility-spec '(org-hide-block . t))
  4693. (setq-local outline-regexp org-outline-regexp)
  4694. (setq-local outline-level 'org-outline-level)
  4695. (setq bidi-paragraph-direction 'left-to-right)
  4696. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4697. (unless org-display-table
  4698. (setq org-display-table (make-display-table)))
  4699. (set-display-table-slot
  4700. org-display-table 4
  4701. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4702. org-ellipsis)))
  4703. (setq buffer-display-table org-display-table))
  4704. (org-set-regexps-and-options)
  4705. (org-set-font-lock-defaults)
  4706. (when (and org-tag-faces (not org-tags-special-faces-re))
  4707. ;; tag faces set outside customize.... force initialization.
  4708. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4709. ;; Calc embedded
  4710. (setq-local calc-embedded-open-mode "# ")
  4711. ;; Modify a few syntax entries
  4712. (modify-syntax-entry ?@ "w")
  4713. (modify-syntax-entry ?\" "\"")
  4714. (modify-syntax-entry ?\\ "_")
  4715. (modify-syntax-entry ?~ "_")
  4716. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4717. ;; Activate before-change-function
  4718. (setq-local org-table-may-need-update t)
  4719. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4720. ;; Check for running clock before killing a buffer
  4721. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4722. ;; Initialize macros templates.
  4723. (org-macro-initialize-templates)
  4724. ;; Initialize radio targets.
  4725. (org-update-radio-target-regexp)
  4726. ;; Indentation.
  4727. (setq-local indent-line-function 'org-indent-line)
  4728. (setq-local indent-region-function 'org-indent-region)
  4729. ;; Filling and auto-filling.
  4730. (org-setup-filling)
  4731. ;; Comments.
  4732. (org-setup-comments-handling)
  4733. ;; Initialize cache.
  4734. (org-element-cache-reset)
  4735. ;; Beginning/end of defun
  4736. (setq-local beginning-of-defun-function 'org-backward-element)
  4737. (setq-local end-of-defun-function
  4738. (lambda ()
  4739. (if (not (org-at-heading-p))
  4740. (org-forward-element)
  4741. (org-forward-element)
  4742. (forward-char -1))))
  4743. ;; Next error for sparse trees
  4744. (setq-local next-error-function 'org-occur-next-match)
  4745. ;; Make sure dependence stuff works reliably, even for users who set it
  4746. ;; too late :-(
  4747. (if org-enforce-todo-dependencies
  4748. (add-hook 'org-blocker-hook
  4749. 'org-block-todo-from-children-or-siblings-or-parent)
  4750. (remove-hook 'org-blocker-hook
  4751. 'org-block-todo-from-children-or-siblings-or-parent))
  4752. (if org-enforce-todo-checkbox-dependencies
  4753. (add-hook 'org-blocker-hook
  4754. 'org-block-todo-from-checkboxes)
  4755. (remove-hook 'org-blocker-hook
  4756. 'org-block-todo-from-checkboxes))
  4757. ;; Align options lines
  4758. (setq-local
  4759. align-mode-rules-list
  4760. '((org-in-buffer-settings
  4761. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4762. (modes . '(org-mode)))))
  4763. ;; Imenu
  4764. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4765. ;; Make isearch reveal context
  4766. (setq-local outline-isearch-open-invisible-function
  4767. (lambda (&rest _) (org-show-context 'isearch)))
  4768. ;; Setup the pcomplete hooks
  4769. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4770. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4771. (setq-local pcomplete-default-completion-function 'ignore)
  4772. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4773. (setq-local pcomplete-termination-string "")
  4774. (setq-local buffer-face-mode-face 'org-default)
  4775. ;; If empty file that did not turn on Org mode automatically, make
  4776. ;; it to.
  4777. (when (and org-insert-mode-line-in-empty-file
  4778. (called-interactively-p 'any)
  4779. (= (point-min) (point-max)))
  4780. (insert "# -*- mode: org -*-\n\n"))
  4781. (unless org-inhibit-startup
  4782. (org-unmodified
  4783. (when org-startup-with-beamer-mode (org-beamer-mode))
  4784. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4785. (org-table-map-tables
  4786. (cond ((and org-startup-align-all-tables
  4787. org-startup-shrink-all-tables)
  4788. (lambda () (org-table-align) (org-table-shrink)))
  4789. (org-startup-align-all-tables #'org-table-align)
  4790. (t #'org-table-shrink))
  4791. t))
  4792. (when org-startup-with-inline-images (org-display-inline-images))
  4793. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4794. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4795. (when org-startup-truncated (setq truncate-lines t))
  4796. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4797. (org-refresh-effort-properties)))
  4798. ;; Try to set `org-hide' face correctly.
  4799. (let ((foreground (org-find-invisible-foreground)))
  4800. (when foreground
  4801. (set-face-foreground 'org-hide foreground))))
  4802. ;; Update `customize-package-emacs-version-alist'
  4803. (add-to-list 'customize-package-emacs-version-alist
  4804. '(Org ("8.0" . "24.4")
  4805. ("8.1" . "24.4")
  4806. ("8.2" . "24.4")
  4807. ("8.2.7" . "24.4")
  4808. ("8.3" . "26.1")
  4809. ("9.0" . "26.1")
  4810. ("9.1" . "26.1")
  4811. ("9.2" . "27.1")))
  4812. (defvar org-mode-transpose-word-syntax-table
  4813. (let ((st (make-syntax-table text-mode-syntax-table)))
  4814. (dolist (c org-emphasis-alist st)
  4815. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4816. (when (fboundp 'abbrev-table-put)
  4817. (abbrev-table-put org-mode-abbrev-table
  4818. :parents (list text-mode-abbrev-table)))
  4819. (defun org-find-invisible-foreground ()
  4820. (let ((candidates (remove
  4821. "unspecified-bg"
  4822. (nconc
  4823. (list (face-background 'default)
  4824. (face-background 'org-default))
  4825. (mapcar
  4826. (lambda (alist)
  4827. (when (boundp alist)
  4828. (cdr (assq 'background-color (symbol-value alist)))))
  4829. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4830. (list (face-foreground 'org-hide))))))
  4831. (car (remove nil candidates))))
  4832. (defun org-current-time (&optional rounding-minutes past)
  4833. "Current time, possibly rounded to ROUNDING-MINUTES.
  4834. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4835. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4836. the rounding returns a past time."
  4837. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4838. (car org-time-stamp-rounding-minutes)))
  4839. (time (decode-time)) res)
  4840. (if (< r 1)
  4841. (current-time)
  4842. (setq res
  4843. (apply 'encode-time
  4844. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4845. (nthcdr 2 time))))
  4846. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4847. (seconds-to-time (- (float-time res) (* r 60)))
  4848. res))))
  4849. (defun org-today ()
  4850. "Return today date, considering `org-extend-today-until'."
  4851. (time-to-days
  4852. (time-subtract (current-time)
  4853. (list 0 (* 3600 org-extend-today-until) 0))))
  4854. ;;;; Font-Lock stuff, including the activators
  4855. (defvar org-mouse-map (make-sparse-keymap))
  4856. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4857. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4858. (when org-mouse-1-follows-link
  4859. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4860. (when org-tab-follows-link
  4861. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4862. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4863. (require 'font-lock)
  4864. (defconst org-non-link-chars "]\t\n\r<>")
  4865. (defvar org-link-types-re nil
  4866. "Matches a link that has a url-like prefix like \"http:\"")
  4867. (defvar org-link-re-with-space nil
  4868. "Matches a link with spaces, optional angular brackets around it.")
  4869. (defvar org-link-re-with-space2 nil
  4870. "Matches a link with spaces, optional angular brackets around it.")
  4871. (defvar org-link-re-with-space3 nil
  4872. "Matches a link with spaces, only for internal part in bracket links.")
  4873. (defvar org-angle-link-re nil
  4874. "Matches link with angular brackets, spaces are allowed.")
  4875. (defvar org-plain-link-re nil
  4876. "Matches plain link, without spaces.")
  4877. (defvar org-bracket-link-regexp nil
  4878. "Matches a link in double brackets.")
  4879. (defvar org-bracket-link-analytic-regexp nil
  4880. "Regular expression used to analyze links.
  4881. Here is what the match groups contain after a match:
  4882. 1: http:
  4883. 2: http
  4884. 3: path
  4885. 4: [desc]
  4886. 5: desc")
  4887. (defvar org-bracket-link-analytic-regexp++ nil
  4888. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4889. (defvar org-any-link-re nil
  4890. "Regular expression matching any link.")
  4891. (defconst org-match-sexp-depth 3
  4892. "Number of stacked braces for sub/superscript matching.")
  4893. (defun org-create-multibrace-regexp (left right n)
  4894. "Create a regular expression which will match a balanced sexp.
  4895. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4896. as single character strings.
  4897. The regexp returned will match the entire expression including the
  4898. delimiters. It will also define a single group which contains the
  4899. match except for the outermost delimiters. The maximum depth of
  4900. stacked delimiters is N. Escaping delimiters is not possible."
  4901. (let* ((nothing (concat "[^" left right "]*?"))
  4902. (or "\\|")
  4903. (re nothing)
  4904. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4905. (while (> n 1)
  4906. (setq n (1- n)
  4907. re (concat re or next)
  4908. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4909. (concat left "\\(" re "\\)" right)))
  4910. (defconst org-match-substring-regexp
  4911. (concat
  4912. "\\(\\S-\\)\\([_^]\\)\\("
  4913. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4914. "\\|"
  4915. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4916. "\\|"
  4917. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4918. "The regular expression matching a sub- or superscript.")
  4919. (defconst org-match-substring-with-braces-regexp
  4920. (concat
  4921. "\\(\\S-\\)\\([_^]\\)"
  4922. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4923. "The regular expression matching a sub- or superscript, forcing braces.")
  4924. (defun org-make-link-regexps ()
  4925. "Update the link regular expressions.
  4926. This should be called after the variable `org-link-parameters' has changed."
  4927. (let ((types-re (regexp-opt (org-link-types) t)))
  4928. (setq org-link-types-re
  4929. (concat "\\`" types-re ":")
  4930. org-link-re-with-space
  4931. (concat "<?" types-re ":"
  4932. "\\([^" org-non-link-chars " ]"
  4933. "[^" org-non-link-chars "]*"
  4934. "[^" org-non-link-chars " ]\\)>?")
  4935. org-link-re-with-space2
  4936. (concat "<?" types-re ":"
  4937. "\\([^" org-non-link-chars " ]"
  4938. "[^\t\n\r]*"
  4939. "[^" org-non-link-chars " ]\\)>?")
  4940. org-link-re-with-space3
  4941. (concat "<?" types-re ":"
  4942. "\\([^" org-non-link-chars " ]"
  4943. "[^\t\n\r]*\\)")
  4944. org-angle-link-re
  4945. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4946. types-re)
  4947. org-plain-link-re
  4948. (concat
  4949. "\\<" types-re ":"
  4950. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4951. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4952. org-bracket-link-regexp
  4953. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4954. org-bracket-link-analytic-regexp
  4955. (concat
  4956. "\\[\\["
  4957. "\\(" types-re ":\\)?"
  4958. "\\([^]]+\\)"
  4959. "\\]"
  4960. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4961. "\\]")
  4962. org-bracket-link-analytic-regexp++
  4963. (concat
  4964. "\\[\\["
  4965. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4966. "\\([^]]+\\)"
  4967. "\\]"
  4968. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4969. "\\]")
  4970. org-any-link-re
  4971. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4972. org-angle-link-re "\\)\\|\\("
  4973. org-plain-link-re "\\)"))))
  4974. (org-make-link-regexps)
  4975. (defvar org-emph-face nil)
  4976. (defun org-do-emphasis-faces (limit)
  4977. "Run through the buffer and emphasize strings."
  4978. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4979. (car org-emphasis-regexp-components))))
  4980. (catch :exit
  4981. (while (re-search-forward quick-re limit t)
  4982. (let* ((marker (match-string 2))
  4983. (verbatim? (member marker '("~" "="))))
  4984. (when (save-excursion
  4985. (goto-char (match-beginning 0))
  4986. (and
  4987. ;; Do not match table hlines.
  4988. (not (and (equal marker "+")
  4989. (org-match-line
  4990. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4991. ;; Do not match headline stars. Do not consider
  4992. ;; stars of a headline as closing marker for bold
  4993. ;; markup either.
  4994. (not (and (equal marker "*")
  4995. (save-excursion
  4996. (forward-char)
  4997. (skip-chars-backward "*")
  4998. (looking-at-p org-outline-regexp-bol))))
  4999. ;; Match full emphasis markup regexp.
  5000. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5001. ;; Do not span over paragraph boundaries.
  5002. (not (string-match-p org-element-paragraph-separate
  5003. (match-string 2)))
  5004. ;; Do not span over cells in table rows.
  5005. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5006. (string-match-p "|" (match-string 4))))))
  5007. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5008. (font-lock-prepend-text-property
  5009. (match-beginning 2) (match-end 2) 'face face)
  5010. (when verbatim?
  5011. (org-remove-flyspell-overlays-in
  5012. (match-beginning 0) (match-end 0)))
  5013. (add-text-properties (match-beginning 2) (match-end 2)
  5014. '(font-lock-multiline t org-emphasis t))
  5015. (when org-hide-emphasis-markers
  5016. (add-text-properties (match-end 4) (match-beginning 5)
  5017. '(invisible org-link))
  5018. (add-text-properties (match-beginning 3) (match-end 3)
  5019. '(invisible org-link)))
  5020. (throw :exit t))))))))
  5021. (defun org-emphasize (&optional char)
  5022. "Insert or change an emphasis, i.e. a font like bold or italic.
  5023. If there is an active region, change that region to a new emphasis.
  5024. If there is no region, just insert the marker characters and position
  5025. the cursor between them.
  5026. CHAR should be the marker character. If it is a space, it means to
  5027. remove the emphasis of the selected region.
  5028. If CHAR is not given (for example in an interactive call) it will be
  5029. prompted for."
  5030. (interactive)
  5031. (let ((erc org-emphasis-regexp-components)
  5032. (string "") beg end move s)
  5033. (if (org-region-active-p)
  5034. (setq beg (region-beginning)
  5035. end (region-end)
  5036. string (buffer-substring beg end))
  5037. (setq move t))
  5038. (unless char
  5039. (message "Emphasis marker or tag: [%s]"
  5040. (mapconcat #'car org-emphasis-alist ""))
  5041. (setq char (read-char-exclusive)))
  5042. (if (equal char ?\s)
  5043. (setq s ""
  5044. move nil)
  5045. (unless (assoc (char-to-string char) org-emphasis-alist)
  5046. (user-error "No such emphasis marker: \"%c\"" char))
  5047. (setq s (char-to-string char)))
  5048. (while (and (> (length string) 1)
  5049. (equal (substring string 0 1) (substring string -1))
  5050. (assoc (substring string 0 1) org-emphasis-alist))
  5051. (setq string (substring string 1 -1)))
  5052. (setq string (concat s string s))
  5053. (when beg (delete-region beg end))
  5054. (unless (or (bolp)
  5055. (string-match (concat "[" (nth 0 erc) "\n]")
  5056. (char-to-string (char-before (point)))))
  5057. (insert " "))
  5058. (unless (or (eobp)
  5059. (string-match (concat "[" (nth 1 erc) "\n]")
  5060. (char-to-string (char-after (point)))))
  5061. (insert " ") (backward-char 1))
  5062. (insert string)
  5063. (and move (backward-char 1))))
  5064. (defconst org-nonsticky-props
  5065. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5066. (defsubst org-rear-nonsticky-at (pos)
  5067. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5068. (defun org-activate-links (limit)
  5069. "Add link properties to links.
  5070. This includes angle, plain, and bracket links."
  5071. (catch :exit
  5072. (while (re-search-forward org-any-link-re limit t)
  5073. (let* ((start (match-beginning 0))
  5074. (end (match-end 0))
  5075. (style (cond ((eq ?< (char-after start)) 'angle)
  5076. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5077. (t 'plain))))
  5078. (when (and (memq style org-highlight-links)
  5079. ;; Do not confuse plain links with tags.
  5080. (not (and (eq style 'plain)
  5081. (let ((face (get-text-property
  5082. (max (1- start) (point-min)) 'face)))
  5083. (if (consp face) (memq 'org-tag face)
  5084. (eq 'org-tag face))))))
  5085. (let* ((link-object (save-excursion
  5086. (goto-char start)
  5087. (save-match-data (org-element-link-parser))))
  5088. (link (org-element-property :raw-link link-object))
  5089. (type (org-element-property :type link-object))
  5090. (path (org-element-property :path link-object))
  5091. (properties ;for link's visible part
  5092. (list
  5093. 'face (pcase (org-link-get-parameter type :face)
  5094. ((and (pred functionp) face) (funcall face path))
  5095. ((and (pred facep) face) face)
  5096. ((and (pred consp) face) face) ;anonymous
  5097. (_ 'org-link))
  5098. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5099. 'highlight)
  5100. 'keymap (or (org-link-get-parameter type :keymap)
  5101. org-mouse-map)
  5102. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5103. ((and (pred stringp) echo) echo)
  5104. ((and (pred functionp) echo) echo)
  5105. (_ (concat "LINK: " link)))
  5106. 'htmlize-link (pcase (org-link-get-parameter type
  5107. :htmlize-link)
  5108. ((and (pred functionp) f) (funcall f))
  5109. (_ `(:uri ,link)))
  5110. 'font-lock-multiline t)))
  5111. (org-remove-flyspell-overlays-in start end)
  5112. (org-rear-nonsticky-at end)
  5113. (if (not (eq 'bracket style))
  5114. (add-text-properties start end properties)
  5115. ;; Handle invisible parts in bracket links.
  5116. (remove-text-properties start end '(invisible nil))
  5117. (let ((hidden
  5118. (append `(invisible
  5119. ,(or (org-link-get-parameter type :display)
  5120. 'org-link))
  5121. properties))
  5122. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5123. (visible-end (or (match-end 4) (match-end 2))))
  5124. (add-text-properties start visible-start hidden)
  5125. (add-text-properties visible-start visible-end properties)
  5126. (add-text-properties visible-end end hidden)
  5127. (org-rear-nonsticky-at visible-start)
  5128. (org-rear-nonsticky-at visible-end)))
  5129. (let ((f (org-link-get-parameter type :activate-func)))
  5130. (when (functionp f)
  5131. (funcall f start end path (eq style 'bracket))))
  5132. (throw :exit t))))) ;signal success
  5133. nil))
  5134. (defun org-activate-code (limit)
  5135. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5136. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5137. (remove-text-properties (match-beginning 0) (match-end 0)
  5138. '(display t invisible t intangible t))
  5139. t))
  5140. (defcustom org-src-fontify-natively t
  5141. "When non-nil, fontify code in code blocks.
  5142. See also the `org-block' face."
  5143. :type 'boolean
  5144. :version "26.1"
  5145. :package-version '(Org . "8.3")
  5146. :group 'org-appearance
  5147. :group 'org-babel)
  5148. (defcustom org-allow-promoting-top-level-subtree nil
  5149. "When non-nil, allow promoting a top level subtree.
  5150. The leading star of the top level headline will be replaced
  5151. by a #."
  5152. :type 'boolean
  5153. :version "24.1"
  5154. :group 'org-appearance)
  5155. (defun org-fontify-meta-lines-and-blocks (limit)
  5156. (condition-case nil
  5157. (org-fontify-meta-lines-and-blocks-1 limit)
  5158. (error (message "org-mode fontification error in %S at %d"
  5159. (current-buffer)
  5160. (line-number-at-pos)))))
  5161. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5162. "Fontify #+ lines and blocks."
  5163. (let ((case-fold-search t))
  5164. (when (re-search-forward
  5165. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5166. limit t)
  5167. (let ((beg (match-beginning 0))
  5168. (block-start (match-end 0))
  5169. (block-end nil)
  5170. (lang (match-string 7))
  5171. (beg1 (line-beginning-position 2))
  5172. (dc1 (downcase (match-string 2)))
  5173. (dc3 (downcase (match-string 3)))
  5174. end end1 quoting block-type)
  5175. (cond
  5176. ((and (match-end 4) (equal dc3 "+begin"))
  5177. ;; Truly a block
  5178. (setq block-type (downcase (match-string 5))
  5179. quoting (member block-type org-protecting-blocks))
  5180. (when (re-search-forward
  5181. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5182. nil t) ;; on purpose, we look further than LIMIT
  5183. (setq end (min (point-max) (match-end 0))
  5184. end1 (min (point-max) (1- (match-beginning 0))))
  5185. (setq block-end (match-beginning 0))
  5186. (when quoting
  5187. (org-remove-flyspell-overlays-in beg1 end1)
  5188. (remove-text-properties beg end
  5189. '(display t invisible t intangible t)))
  5190. (add-text-properties
  5191. beg end '(font-lock-fontified t font-lock-multiline t))
  5192. (add-text-properties beg beg1 '(face org-meta-line))
  5193. (org-remove-flyspell-overlays-in beg beg1)
  5194. (add-text-properties ; For end_src
  5195. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5196. (org-remove-flyspell-overlays-in end1 end)
  5197. (cond
  5198. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5199. (org-src-font-lock-fontify-block lang block-start block-end)
  5200. (add-text-properties beg1 block-end '(src-block t)))
  5201. (quoting
  5202. (add-text-properties beg1 (min (point-max) (1+ end1))
  5203. (list 'face
  5204. (list :inherit
  5205. (let ((face-name
  5206. (intern (format "org-block-%s" lang))))
  5207. (append (and (facep face-name) (list face-name))
  5208. '(org-block))))))) ; end of source block
  5209. ((not org-fontify-quote-and-verse-blocks))
  5210. ((string= block-type "quote")
  5211. (add-face-text-property
  5212. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5213. ((string= block-type "verse")
  5214. (add-face-text-property
  5215. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5216. (add-text-properties beg beg1 '(face org-block-begin-line))
  5217. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5218. '(face org-block-end-line))
  5219. t))
  5220. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5221. (org-remove-flyspell-overlays-in
  5222. (match-beginning 0)
  5223. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5224. (add-text-properties
  5225. beg (match-end 3)
  5226. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5227. '(font-lock-fontified t invisible t)
  5228. '(font-lock-fontified t face org-document-info-keyword)))
  5229. (add-text-properties
  5230. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5231. (if (string-equal dc1 "+title:")
  5232. '(font-lock-fontified t face org-document-title)
  5233. '(font-lock-fontified t face org-document-info))))
  5234. ((string-prefix-p "+caption" dc1)
  5235. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5236. (remove-text-properties (match-beginning 0) (match-end 0)
  5237. '(display t invisible t intangible t))
  5238. ;; Handle short captions.
  5239. (save-excursion
  5240. (beginning-of-line)
  5241. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5242. (add-text-properties (line-beginning-position) (match-end 1)
  5243. '(font-lock-fontified t face org-meta-line))
  5244. (add-text-properties (match-end 0) (line-end-position)
  5245. '(font-lock-fontified t face org-block))
  5246. t)
  5247. ((member dc3 '(" " ""))
  5248. (org-remove-flyspell-overlays-in beg (match-end 0))
  5249. (add-text-properties
  5250. beg (match-end 0)
  5251. '(font-lock-fontified t face font-lock-comment-face)))
  5252. (t ;; just any other in-buffer setting, but not indented
  5253. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5254. (remove-text-properties (match-beginning 0) (match-end 0)
  5255. '(display t invisible t intangible t))
  5256. (add-text-properties beg (match-end 0)
  5257. '(font-lock-fontified t face org-meta-line))
  5258. t))))))
  5259. (defun org-fontify-drawers (limit)
  5260. "Fontify drawers."
  5261. (when (re-search-forward org-drawer-regexp limit t)
  5262. (add-text-properties
  5263. (match-beginning 0) (match-end 0)
  5264. '(font-lock-fontified t face org-special-keyword))
  5265. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5266. t))
  5267. (defun org-fontify-macros (limit)
  5268. "Fontify macros."
  5269. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5270. (add-text-properties
  5271. (match-beginning 0) (match-end 0)
  5272. '(font-lock-fontified t face org-macro))
  5273. (when org-hide-macro-markers
  5274. (add-text-properties (match-end 2) (match-beginning 2)
  5275. '(invisible t))
  5276. (add-text-properties (match-beginning 1) (match-end 1)
  5277. '(invisible t)))
  5278. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5279. t))
  5280. (defun org-activate-footnote-links (limit)
  5281. "Add text properties for footnotes."
  5282. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5283. (when fn
  5284. (let* ((beg (nth 1 fn))
  5285. (end (nth 2 fn))
  5286. (label (car fn))
  5287. (referencep (/= (line-beginning-position) beg)))
  5288. (when (and referencep (nth 3 fn))
  5289. (save-excursion
  5290. (goto-char beg)
  5291. (search-forward (or label "fn:"))
  5292. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5293. (add-text-properties beg end
  5294. (list 'mouse-face 'highlight
  5295. 'keymap org-mouse-map
  5296. 'help-echo
  5297. (if referencep "Footnote reference"
  5298. "Footnote definition")
  5299. 'font-lock-fontified t
  5300. 'font-lock-multiline t
  5301. 'face 'org-footnote))))))
  5302. (defun org-activate-dates (limit)
  5303. "Add text properties for dates."
  5304. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5305. (not (equal (char-before (match-beginning 0)) 91)))
  5306. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5307. (add-text-properties (match-beginning 0) (match-end 0)
  5308. (list 'mouse-face 'highlight
  5309. 'keymap org-mouse-map))
  5310. (org-rear-nonsticky-at (match-end 0))
  5311. (when org-display-custom-times
  5312. ;; If it's a date range, activate custom time for second date.
  5313. (when (match-end 3)
  5314. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5315. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5316. t))
  5317. (defvar-local org-target-link-regexp nil
  5318. "Regular expression matching radio targets in plain text.")
  5319. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5320. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5321. border border border))
  5322. "Regular expression matching a link target.")
  5323. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5324. "Regular expression matching a radio target.")
  5325. (defconst org-any-target-regexp
  5326. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5327. "Regular expression matching any target.")
  5328. (defun org-activate-target-links (limit)
  5329. "Add text properties for target matches."
  5330. (when org-target-link-regexp
  5331. (let ((case-fold-search t))
  5332. (when (re-search-forward org-target-link-regexp limit t)
  5333. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5334. (add-text-properties (match-beginning 1) (match-end 1)
  5335. (list 'mouse-face 'highlight
  5336. 'keymap org-mouse-map
  5337. 'help-echo "Radio target link"
  5338. 'org-linked-text t))
  5339. (org-rear-nonsticky-at (match-end 1))
  5340. t))))
  5341. (defun org-update-radio-target-regexp ()
  5342. "Find all radio targets in this file and update the regular expression.
  5343. Also refresh fontification if needed."
  5344. (interactive)
  5345. (let ((old-regexp org-target-link-regexp)
  5346. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5347. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5348. (targets
  5349. (org-with-wide-buffer
  5350. (goto-char (point-min))
  5351. (let (rtn)
  5352. (while (re-search-forward org-radio-target-regexp nil t)
  5353. ;; Make sure point is really within the object.
  5354. (backward-char)
  5355. (let ((obj (org-element-context)))
  5356. (when (eq (org-element-type obj) 'radio-target)
  5357. (cl-pushnew (org-element-property :value obj) rtn
  5358. :test #'equal))))
  5359. rtn))))
  5360. (setq org-target-link-regexp
  5361. (and targets
  5362. (concat before-re
  5363. (mapconcat
  5364. (lambda (x)
  5365. (replace-regexp-in-string
  5366. " +" "\\s-+" (regexp-quote x) t t))
  5367. targets
  5368. "\\|")
  5369. after-re)))
  5370. (unless (equal old-regexp org-target-link-regexp)
  5371. ;; Clean-up cache.
  5372. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5373. ((not org-target-link-regexp) old-regexp)
  5374. (t
  5375. (concat before-re
  5376. (mapconcat
  5377. (lambda (re)
  5378. (substring re (length before-re)
  5379. (- (length after-re))))
  5380. (list old-regexp org-target-link-regexp)
  5381. "\\|")
  5382. after-re)))))
  5383. (org-with-wide-buffer
  5384. (goto-char (point-min))
  5385. (while (re-search-forward regexp nil t)
  5386. (org-element-cache-refresh (match-beginning 1)))))
  5387. ;; Re fontify buffer.
  5388. (when (memq 'radio org-highlight-links)
  5389. (org-restart-font-lock)))))
  5390. (defvar org-latex-and-related-regexp nil
  5391. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5392. (defun org-compute-latex-and-related-regexp ()
  5393. "Compute regular expression for LaTeX, entities and sub/superscript.
  5394. Result depends on variable `org-highlight-latex-and-related'."
  5395. (setq-local
  5396. org-latex-and-related-regexp
  5397. (let* ((re-sub
  5398. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5399. ((eq org-use-sub-superscripts '{})
  5400. (list org-match-substring-with-braces-regexp))
  5401. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5402. (re-latex
  5403. (when (memq 'latex org-highlight-latex-and-related)
  5404. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5405. (delq nil
  5406. (mapcar (lambda (x)
  5407. (and (member (car x) matchers) (nth 1 x)))
  5408. org-latex-regexps)))))
  5409. (re-entities
  5410. (when (memq 'entities org-highlight-latex-and-related)
  5411. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5412. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5413. (defun org-do-latex-and-related (limit)
  5414. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5415. LIMIT bounds the search for syntax to highlight. Stop at first
  5416. highlighted object, if any. Return t if some highlighting was
  5417. done, nil otherwise."
  5418. (when (org-string-nw-p org-latex-and-related-regexp)
  5419. (catch 'found
  5420. (while (re-search-forward org-latex-and-related-regexp limit t)
  5421. (unless
  5422. (cl-some
  5423. (lambda (f)
  5424. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5425. (save-excursion
  5426. (goto-char (1+ (match-beginning 0)))
  5427. (face-at-point nil t)))
  5428. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5429. '(?_ ?^))
  5430. 1
  5431. 0)))
  5432. (font-lock-prepend-text-property
  5433. (+ offset (match-beginning 0)) (match-end 0)
  5434. 'face 'org-latex-and-related)
  5435. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5436. '(font-lock-multiline t)))
  5437. (throw 'found t)))
  5438. nil)))
  5439. (defun org-restart-font-lock ()
  5440. "Restart `font-lock-mode', to force refontification."
  5441. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5442. (font-lock-mode -1)
  5443. (font-lock-mode 1)))
  5444. (defun org-activate-tags (limit)
  5445. (when (re-search-forward
  5446. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5447. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5448. (add-text-properties (match-beginning 1) (match-end 1)
  5449. (list 'mouse-face 'highlight
  5450. 'keymap org-mouse-map))
  5451. (org-rear-nonsticky-at (match-end 1))
  5452. t))
  5453. (defun org-outline-level ()
  5454. "Compute the outline level of the heading at point.
  5455. If this is called at a normal headline, the level is the number
  5456. of stars. Use `org-reduced-level' to remove the effect of
  5457. `org-odd-levels'. Unlike to `org-current-level', this function
  5458. takes into consideration inlinetasks."
  5459. (org-with-wide-buffer
  5460. (end-of-line)
  5461. (if (re-search-backward org-outline-regexp-bol nil t)
  5462. (1- (- (match-end 0) (match-beginning 0)))
  5463. 0)))
  5464. (defvar org-font-lock-keywords nil)
  5465. (defsubst org-re-property (property &optional literal allow-null value)
  5466. "Return a regexp matching a PROPERTY line.
  5467. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5468. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5469. non-nil, match properties even without a value.
  5470. Match group 3 is set to the value when it exists. If there is no
  5471. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5472. With optional argument VALUE, match only property lines with
  5473. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5474. unless LITERAL is non-nil."
  5475. (concat
  5476. "^\\(?4:[ \t]*\\)"
  5477. (format "\\(?1::\\(?2:%s\\):\\)"
  5478. (if literal property (regexp-quote property)))
  5479. (cond (value
  5480. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5481. (if literal value (regexp-quote value))))
  5482. (allow-null
  5483. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5484. (t
  5485. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5486. (defconst org-property-re
  5487. (org-re-property "\\S-+" 'literal t)
  5488. "Regular expression matching a property line.
  5489. There are four matching groups:
  5490. 1: :PROPKEY: including the leading and trailing colon,
  5491. 2: PROPKEY without the leading and trailing colon,
  5492. 3: PROPVAL without leading or trailing spaces,
  5493. 4: the indentation of the current line,
  5494. 5: trailing whitespace.")
  5495. (defvar org-font-lock-hook nil
  5496. "Functions to be called for special font lock stuff.")
  5497. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5498. (defvar org-font-lock-set-keywords-hook nil
  5499. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5500. This is called after `org-font-lock-extra-keywords' is defined, but before
  5501. it is installed to be used by font lock. This can be useful if something
  5502. needs to be inserted at a specific position in the font-lock sequence.")
  5503. (defun org-font-lock-hook (limit)
  5504. "Run `org-font-lock-hook' within LIMIT."
  5505. (run-hook-with-args 'org-font-lock-hook limit))
  5506. (defun org-set-font-lock-defaults ()
  5507. "Set font lock defaults for the current buffer."
  5508. (let* ((em org-fontify-emphasized-text)
  5509. (lk org-highlight-links)
  5510. (org-font-lock-extra-keywords
  5511. (list
  5512. ;; Call the hook
  5513. '(org-font-lock-hook)
  5514. ;; Headlines
  5515. `(,(if org-fontify-whole-heading-line
  5516. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5517. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5518. (1 (org-get-level-face 1))
  5519. (2 (org-get-level-face 2))
  5520. (3 (org-get-level-face 3)))
  5521. ;; Table lines
  5522. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5523. (1 'org-table t))
  5524. ;; Table internals
  5525. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5526. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5527. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5528. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5529. ;; Drawers
  5530. '(org-fontify-drawers)
  5531. ;; Properties
  5532. (list org-property-re
  5533. '(1 'org-special-keyword t)
  5534. '(3 'org-property-value t))
  5535. ;; Link related fontification.
  5536. '(org-activate-links)
  5537. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5538. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5539. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5540. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5541. ;; Targets.
  5542. (list org-any-target-regexp '(0 'org-target t))
  5543. ;; Diary sexps.
  5544. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5545. ;; Macro
  5546. '(org-fontify-macros)
  5547. ;; TODO keyword
  5548. (list (format org-heading-keyword-regexp-format
  5549. org-todo-regexp)
  5550. '(2 (org-get-todo-face 2) t))
  5551. ;; DONE
  5552. (if org-fontify-done-headline
  5553. (list (format org-heading-keyword-regexp-format
  5554. (concat
  5555. "\\(?:"
  5556. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5557. "\\)"))
  5558. '(2 'org-headline-done t))
  5559. nil)
  5560. ;; Priorities
  5561. '(org-font-lock-add-priority-faces)
  5562. ;; Tags
  5563. '(org-font-lock-add-tag-faces)
  5564. ;; Tags groups
  5565. (when (and org-group-tags org-tag-groups-alist)
  5566. (list (concat org-outline-regexp-bol ".+\\(:"
  5567. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5568. ":\\).*$")
  5569. '(1 'org-tag-group prepend)))
  5570. ;; Special keywords
  5571. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5572. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5573. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5574. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5575. ;; Emphasis
  5576. (when em '(org-do-emphasis-faces))
  5577. ;; Checkboxes
  5578. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5579. 1 'org-checkbox prepend)
  5580. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5581. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5582. (0 (org-get-checkbox-statistics-face) t)))
  5583. ;; Description list items
  5584. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5585. 1 'org-list-dt prepend)
  5586. ;; ARCHIVEd headings
  5587. (list (concat
  5588. org-outline-regexp-bol
  5589. "\\(.*:" org-archive-tag ":.*\\)")
  5590. '(1 'org-archived prepend))
  5591. ;; Specials
  5592. '(org-do-latex-and-related)
  5593. '(org-fontify-entities)
  5594. '(org-raise-scripts)
  5595. ;; Code
  5596. '(org-activate-code (1 'org-code t))
  5597. ;; COMMENT
  5598. (list (format
  5599. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5600. org-todo-regexp
  5601. org-comment-string)
  5602. '(9 'org-special-keyword t))
  5603. ;; Blocks and meta lines
  5604. '(org-fontify-meta-lines-and-blocks))))
  5605. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5606. (run-hooks 'org-font-lock-set-keywords-hook)
  5607. ;; Now set the full font-lock-keywords
  5608. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5609. (setq-local font-lock-defaults
  5610. '(org-font-lock-keywords t nil nil backward-paragraph))
  5611. (kill-local-variable 'font-lock-keywords)
  5612. nil))
  5613. (defun org-toggle-pretty-entities ()
  5614. "Toggle the composition display of entities as UTF8 characters."
  5615. (interactive)
  5616. (setq-local org-pretty-entities (not org-pretty-entities))
  5617. (org-restart-font-lock)
  5618. (if org-pretty-entities
  5619. (message "Entities are now displayed as UTF8 characters")
  5620. (save-restriction
  5621. (widen)
  5622. (decompose-region (point-min) (point-max))
  5623. (message "Entities are now displayed as plain text"))))
  5624. (defvar-local org-custom-properties-overlays nil
  5625. "List of overlays used for custom properties.")
  5626. (defun org-toggle-custom-properties-visibility ()
  5627. "Display or hide properties in `org-custom-properties'."
  5628. (interactive)
  5629. (if org-custom-properties-overlays
  5630. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5631. (setq org-custom-properties-overlays nil))
  5632. (when org-custom-properties
  5633. (org-with-wide-buffer
  5634. (goto-char (point-min))
  5635. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5636. (while (re-search-forward regexp nil t)
  5637. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5638. (when (and end (< (point) end))
  5639. ;; Hide first custom property in current drawer.
  5640. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5641. (overlay-put o 'invisible t)
  5642. (overlay-put o 'org-custom-property t)
  5643. (push o org-custom-properties-overlays))
  5644. ;; Hide additional custom properties in the same drawer.
  5645. (while (re-search-forward regexp end t)
  5646. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5647. (overlay-put o 'invisible t)
  5648. (overlay-put o 'org-custom-property t)
  5649. (push o org-custom-properties-overlays)))))
  5650. ;; Each entry is limited to a single property drawer.
  5651. (outline-next-heading)))))))
  5652. (defun org-fontify-entities (limit)
  5653. "Find an entity to fontify."
  5654. (let (ee)
  5655. (when org-pretty-entities
  5656. (catch 'match
  5657. ;; "\_ "-family is left out on purpose. Only the first one,
  5658. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5659. ;; confusing when adding a second white space character.
  5660. (while (re-search-forward
  5661. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5662. limit t)
  5663. (when (and (not (org-at-comment-p))
  5664. (setq ee (org-entity-get (match-string 1)))
  5665. (= (length (nth 6 ee)) 1))
  5666. (let* ((end (if (equal (match-string 2) "{}")
  5667. (match-end 2)
  5668. (match-end 1))))
  5669. (add-text-properties
  5670. (match-beginning 0) end
  5671. (list 'font-lock-fontified t))
  5672. (compose-region (match-beginning 0) end
  5673. (nth 6 ee) nil)
  5674. (backward-char 1)
  5675. (throw 'match t))))
  5676. nil))))
  5677. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5678. "Fontify string S like in Org mode."
  5679. (with-temp-buffer
  5680. (insert s)
  5681. (let ((org-odd-levels-only odd-levels))
  5682. (org-mode)
  5683. (org-font-lock-ensure)
  5684. (buffer-string))))
  5685. (defvar org-m nil)
  5686. (defvar org-l nil)
  5687. (defvar org-f nil)
  5688. (defun org-get-level-face (n)
  5689. "Get the right face for match N in font-lock matching of headlines."
  5690. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5691. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5692. (if org-cycle-level-faces
  5693. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5694. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5695. (cond
  5696. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5697. ((eq n 2) org-f)
  5698. (t (unless org-level-color-stars-only org-f))))
  5699. (defun org-face-from-face-or-color (context inherit face-or-color)
  5700. "Create a face list that inherits INHERIT, but sets the foreground color.
  5701. When FACE-OR-COLOR is not a string, just return it."
  5702. (if (stringp face-or-color)
  5703. (list :inherit inherit
  5704. (cdr (assoc context org-faces-easy-properties))
  5705. face-or-color)
  5706. face-or-color))
  5707. (defun org-get-todo-face (kwd)
  5708. "Get the right face for a TODO keyword KWD.
  5709. If KWD is a number, get the corresponding match group."
  5710. (when (numberp kwd) (setq kwd (match-string kwd)))
  5711. (or (org-face-from-face-or-color
  5712. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5713. (and (member kwd org-done-keywords) 'org-done)
  5714. 'org-todo))
  5715. (defun org-get-priority-face (priority)
  5716. "Get the right face for PRIORITY.
  5717. PRIORITY is a character."
  5718. (or (org-face-from-face-or-color
  5719. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5720. 'org-priority))
  5721. (defun org-get-tag-face (tag)
  5722. "Get the right face for TAG.
  5723. If TAG is a number, get the corresponding match group."
  5724. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5725. (or (org-face-from-face-or-color
  5726. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5727. 'org-tag)))
  5728. (defun org-font-lock-add-priority-faces (limit)
  5729. "Add the special priority faces."
  5730. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5731. (add-text-properties
  5732. (match-beginning 1) (match-end 1)
  5733. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5734. 'font-lock-fontified t))))
  5735. (defun org-font-lock-add-tag-faces (limit)
  5736. "Add the special tag faces."
  5737. (when (and org-tag-faces org-tags-special-faces-re)
  5738. (while (re-search-forward org-tags-special-faces-re limit t)
  5739. (add-text-properties (match-beginning 1) (match-end 1)
  5740. (list 'face (org-get-tag-face 1)
  5741. 'font-lock-fontified t))
  5742. (backward-char 1))))
  5743. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5744. "Remove fontification and activation overlays from links."
  5745. (font-lock-default-unfontify-region beg end)
  5746. (let* ((buffer-undo-list t)
  5747. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5748. (inhibit-modification-hooks t)
  5749. deactivate-mark buffer-file-name buffer-file-truename)
  5750. (decompose-region beg end)
  5751. (remove-text-properties beg end
  5752. '(mouse-face t keymap t org-linked-text t
  5753. invisible t intangible t
  5754. org-emphasis t))
  5755. (org-remove-font-lock-display-properties beg end)))
  5756. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5757. ((raise 0.3) (height 0.7))
  5758. ((raise -0.5))
  5759. ((raise 0.5)))
  5760. "Display properties for showing superscripts and subscripts.")
  5761. (defun org-remove-font-lock-display-properties (beg end)
  5762. "Remove specific display properties that have been added by font lock.
  5763. The will remove the raise properties that are used to show superscripts
  5764. and subscripts."
  5765. (let (next prop)
  5766. (while (< beg end)
  5767. (setq next (next-single-property-change beg 'display nil end)
  5768. prop (get-text-property beg 'display))
  5769. (when (member prop org-script-display)
  5770. (put-text-property beg next 'display nil))
  5771. (setq beg next))))
  5772. (defun org-raise-scripts (limit)
  5773. "Add raise properties to sub/superscripts."
  5774. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5775. (re-search-forward
  5776. (if (eq org-use-sub-superscripts t)
  5777. org-match-substring-regexp
  5778. org-match-substring-with-braces-regexp)
  5779. limit t))
  5780. (let* ((pos (point)) table-p comment-p
  5781. (mpos (match-beginning 3))
  5782. (emph-p (get-text-property mpos 'org-emphasis))
  5783. (link-p (get-text-property mpos 'mouse-face))
  5784. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5785. (goto-char (point-at-bol))
  5786. (setq table-p (looking-at-p org-table-dataline-regexp)
  5787. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5788. (goto-char pos)
  5789. ;; Handle a_b^c
  5790. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5791. (unless (or comment-p emph-p link-p keyw-p)
  5792. (put-text-property (match-beginning 3) (match-end 0)
  5793. 'display
  5794. (if (equal (char-after (match-beginning 2)) ?^)
  5795. (nth (if table-p 3 1) org-script-display)
  5796. (nth (if table-p 2 0) org-script-display)))
  5797. (add-text-properties (match-beginning 2) (match-end 2)
  5798. (list 'invisible t))
  5799. (when (and (eq (char-after (match-beginning 3)) ?{)
  5800. (eq (char-before (match-end 3)) ?}))
  5801. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5802. (list 'invisible t))
  5803. (add-text-properties (1- (match-end 3)) (match-end 3)
  5804. (list 'invisible t))))
  5805. t)))
  5806. ;;;; Visibility cycling, including org-goto and indirect buffer
  5807. ;;; Cycling
  5808. (defvar-local org-cycle-global-status nil)
  5809. (put 'org-cycle-global-status 'org-state t)
  5810. (defvar-local org-cycle-subtree-status nil)
  5811. (put 'org-cycle-subtree-status 'org-state t)
  5812. (defvar org-inlinetask-min-level)
  5813. ;;;###autoload
  5814. (defun org-cycle (&optional arg)
  5815. "TAB-action and visibility cycling for Org mode.
  5816. This is the command invoked in Org mode by the `TAB' key. Its main
  5817. purpose is outline visibility cycling, but it also invokes other actions
  5818. in special contexts.
  5819. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5820. the entire
  5821. buffer through 3 states (global cycling)
  5822. 1. OVERVIEW: Show only top-level headlines.
  5823. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5824. 3. SHOW ALL: Show everything.
  5825. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5826. switch to the startup visibility,
  5827. determined by the variable `org-startup-folded', and by any VISIBILITY
  5828. properties in the buffer.
  5829. With a `\\[universal-argument] \\[universal-argument] \
  5830. \\[universal-argument]' prefix argument, show the entire buffer, including
  5831. any drawers.
  5832. When inside a table, re-align the table and move to the next field.
  5833. When point is at the beginning of a headline, rotate the subtree started
  5834. by this line through 3 different states (local cycling)
  5835. 1. FOLDED: Only the main headline is shown.
  5836. 2. CHILDREN: The main headline and the direct children are shown.
  5837. From this state, you can move to one of the children
  5838. and zoom in further.
  5839. 3. SUBTREE: Show the entire subtree, including body text.
  5840. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5841. When point is at the beginning of an empty headline and the variable
  5842. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5843. of the headline by demoting and promoting it to likely levels. This
  5844. speeds up creation document structure by pressing `TAB' once or several
  5845. times right after creating a new headline.
  5846. When there is a numeric prefix, go up to a heading with level ARG, do
  5847. a `show-subtree' and return to the previous cursor position. If ARG
  5848. is negative, go up that many levels.
  5849. When point is not at the beginning of a headline, execute the global
  5850. binding for `TAB', which is re-indenting the line. See the option
  5851. `org-cycle-emulate-tab' for details.
  5852. As a special case, if point is at the beginning of the buffer and there is
  5853. no headline in line 1, this function will act as if called with prefix arg
  5854. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5855. prefix arg, but only
  5856. if the variable `org-cycle-global-at-bob' is t."
  5857. (interactive "P")
  5858. (org-load-modules-maybe)
  5859. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5860. (and org-cycle-level-after-item/entry-creation
  5861. (or (org-cycle-level)
  5862. (org-cycle-item-indentation))))
  5863. (let* ((limit-level
  5864. (or org-cycle-max-level
  5865. (and (boundp 'org-inlinetask-min-level)
  5866. org-inlinetask-min-level
  5867. (1- org-inlinetask-min-level))))
  5868. (nstars (and limit-level
  5869. (if org-odd-levels-only
  5870. (and limit-level (1- (* limit-level 2)))
  5871. limit-level)))
  5872. (org-outline-regexp
  5873. (if (not (derived-mode-p 'org-mode))
  5874. outline-regexp
  5875. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5876. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5877. (not (looking-at org-outline-regexp))))
  5878. (org-cycle-hook
  5879. (if bob-special
  5880. (delq 'org-optimize-window-after-visibility-change
  5881. (copy-sequence org-cycle-hook))
  5882. org-cycle-hook))
  5883. (pos (point)))
  5884. (cond
  5885. ((equal arg '(16))
  5886. (setq last-command 'dummy)
  5887. (org-set-startup-visibility)
  5888. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5889. ((equal arg '(64))
  5890. (outline-show-all)
  5891. (org-unlogged-message "Entire buffer visible, including drawers"))
  5892. ((equal arg '(4)) (org-cycle-internal-global))
  5893. ;; Try hiding block at point.
  5894. ((org-hide-block-toggle-maybe))
  5895. ;; Try cdlatex TAB completion
  5896. ((org-try-cdlatex-tab))
  5897. ;; Table: enter it or move to the next field.
  5898. ((org-at-table-p 'any)
  5899. (if (org-at-table.el-p)
  5900. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5901. Use `\\[org-edit-special]' to edit table.el tables"))
  5902. (if arg (org-table-edit-field t)
  5903. (org-table-justify-field-maybe)
  5904. (call-interactively 'org-table-next-field))))
  5905. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5906. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5907. (bob-special (org-cycle-internal-global))
  5908. ;; Drawers: delegate to `org-flag-drawer'.
  5909. ((save-excursion
  5910. (beginning-of-line 1)
  5911. (looking-at org-drawer-regexp))
  5912. (org-flag-drawer ; toggle block visibility
  5913. (not (get-char-property (match-end 0) 'invisible))))
  5914. ;; Show-subtree, ARG levels up from here.
  5915. ((integerp arg)
  5916. (save-excursion
  5917. (org-back-to-heading)
  5918. (outline-up-heading (if (< arg 0) (- arg)
  5919. (- (funcall outline-level) arg)))
  5920. (org-show-subtree)))
  5921. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5922. ((and (featurep 'org-inlinetask)
  5923. (org-inlinetask-at-task-p)
  5924. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5925. (org-inlinetask-toggle-visibility))
  5926. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5927. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5928. (save-excursion (move-beginning-of-line 1)
  5929. (looking-at org-outline-regexp)))
  5930. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5931. (org-cycle-internal-local))
  5932. ;; From there: TAB emulation and template completion.
  5933. (buffer-read-only (org-back-to-heading))
  5934. ((run-hook-with-args-until-success
  5935. 'org-tab-after-check-for-cycling-hook))
  5936. ((run-hook-with-args-until-success
  5937. 'org-tab-before-tab-emulation-hook))
  5938. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5939. (or (not (bolp))
  5940. (not (looking-at org-outline-regexp))))
  5941. (call-interactively (global-key-binding "\t")))
  5942. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5943. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5944. (or (and (eq org-cycle-emulate-tab 'white)
  5945. (= (match-end 0) (point-at-eol)))
  5946. (and (eq org-cycle-emulate-tab 'whitestart)
  5947. (>= (match-end 0) pos))))
  5948. t
  5949. (eq org-cycle-emulate-tab t))
  5950. (call-interactively (global-key-binding "\t")))
  5951. (t (save-excursion
  5952. (org-back-to-heading)
  5953. (org-cycle)))))))
  5954. (defun org-cycle-internal-global ()
  5955. "Do the global cycling action."
  5956. ;; Hack to avoid display of messages for .org attachments in Gnus
  5957. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5958. (cond
  5959. ((and (eq last-command this-command)
  5960. (eq org-cycle-global-status 'overview))
  5961. ;; We just created the overview - now do table of contents
  5962. ;; This can be slow in very large buffers, so indicate action
  5963. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5964. (unless ga (org-unlogged-message "CONTENTS..."))
  5965. (org-content)
  5966. (unless ga (org-unlogged-message "CONTENTS...done"))
  5967. (setq org-cycle-global-status 'contents)
  5968. (run-hook-with-args 'org-cycle-hook 'contents))
  5969. ((and (eq last-command this-command)
  5970. (eq org-cycle-global-status 'contents))
  5971. ;; We just showed the table of contents - now show everything
  5972. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5973. (outline-show-all)
  5974. (unless ga (org-unlogged-message "SHOW ALL"))
  5975. (setq org-cycle-global-status 'all)
  5976. (run-hook-with-args 'org-cycle-hook 'all))
  5977. (t
  5978. ;; Default action: go to overview
  5979. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5980. (org-overview)
  5981. (unless ga (org-unlogged-message "OVERVIEW"))
  5982. (setq org-cycle-global-status 'overview)
  5983. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5984. (defvar org-called-with-limited-levels nil
  5985. "Non-nil when `org-with-limited-levels' is currently active.")
  5986. (defun org-cycle-internal-local ()
  5987. "Do the local cycling action."
  5988. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5989. ;; First, determine end of headline (EOH), end of subtree or item
  5990. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5991. (save-excursion
  5992. (if (org-at-item-p)
  5993. (progn
  5994. (beginning-of-line)
  5995. (setq struct (org-list-struct))
  5996. (setq eoh (point-at-eol))
  5997. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5998. (setq has-children (org-list-has-child-p (point) struct)))
  5999. (org-back-to-heading)
  6000. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6001. (setq eos (save-excursion (org-end-of-subtree t t)
  6002. (when (bolp) (backward-char)) (point)))
  6003. (setq has-children
  6004. (or (save-excursion
  6005. (let ((level (funcall outline-level)))
  6006. (outline-next-heading)
  6007. (and (org-at-heading-p t)
  6008. (> (funcall outline-level) level))))
  6009. (save-excursion
  6010. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6011. ;; Determine end invisible part of buffer (EOL)
  6012. (beginning-of-line 2)
  6013. (while (and (not (eobp)) ;This is like `next-line'.
  6014. (get-char-property (1- (point)) 'invisible))
  6015. (goto-char (next-single-char-property-change (point) 'invisible))
  6016. (and (eolp) (beginning-of-line 2)))
  6017. (setq eol (point)))
  6018. ;; Find out what to do next and set `this-command'
  6019. (cond
  6020. ((= eos eoh)
  6021. ;; Nothing is hidden behind this heading
  6022. (unless (org-before-first-heading-p)
  6023. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6024. (org-unlogged-message "EMPTY ENTRY")
  6025. (setq org-cycle-subtree-status nil)
  6026. (save-excursion
  6027. (goto-char eos)
  6028. (outline-next-heading)
  6029. (when (org-invisible-p) (org-flag-heading nil))))
  6030. ((and (or (>= eol eos)
  6031. (not (string-match "\\S-" (buffer-substring eol eos))))
  6032. (or has-children
  6033. (not (setq children-skipped
  6034. org-cycle-skip-children-state-if-no-children))))
  6035. ;; Entire subtree is hidden in one line: children view
  6036. (unless (org-before-first-heading-p)
  6037. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6038. (if (org-at-item-p)
  6039. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6040. (org-show-entry)
  6041. (org-with-limited-levels (org-show-children))
  6042. (org-show-set-visibility 'canonical)
  6043. ;; FIXME: This slows down the func way too much.
  6044. ;; How keep drawers hidden in subtree anyway?
  6045. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6046. ;; (org-cycle-hide-drawers 'subtree))
  6047. ;; Fold every list in subtree to top-level items.
  6048. (when (eq org-cycle-include-plain-lists 'integrate)
  6049. (save-excursion
  6050. (org-back-to-heading)
  6051. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6052. (beginning-of-line 1)
  6053. (let* ((struct (org-list-struct))
  6054. (prevs (org-list-prevs-alist struct))
  6055. (end (org-list-get-bottom-point struct)))
  6056. (dolist (e (org-list-get-all-items (point) struct prevs))
  6057. (org-list-set-item-visibility e struct 'folded))
  6058. (goto-char (if (< end eos) end eos)))))))
  6059. (org-unlogged-message "CHILDREN")
  6060. (save-excursion
  6061. (goto-char eos)
  6062. (outline-next-heading)
  6063. (when (org-invisible-p) (org-flag-heading nil)))
  6064. (setq org-cycle-subtree-status 'children)
  6065. (unless (org-before-first-heading-p)
  6066. (run-hook-with-args 'org-cycle-hook 'children)))
  6067. ((or children-skipped
  6068. (and (eq last-command this-command)
  6069. (eq org-cycle-subtree-status 'children)))
  6070. ;; We just showed the children, or no children are there,
  6071. ;; now show everything.
  6072. (unless (org-before-first-heading-p)
  6073. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6074. (outline-flag-region eoh eos nil)
  6075. (org-unlogged-message
  6076. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6077. (setq org-cycle-subtree-status 'subtree)
  6078. (unless (org-before-first-heading-p)
  6079. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6080. (t
  6081. ;; Default action: hide the subtree.
  6082. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6083. (outline-flag-region eoh eos t)
  6084. (org-unlogged-message "FOLDED")
  6085. (setq org-cycle-subtree-status 'folded)
  6086. (unless (org-before-first-heading-p)
  6087. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6088. ;;;###autoload
  6089. (defun org-global-cycle (&optional arg)
  6090. "Cycle the global visibility. For details see `org-cycle'.
  6091. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6092. With a numeric prefix, show all headlines up to that level."
  6093. (interactive "P")
  6094. (let ((org-cycle-include-plain-lists
  6095. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6096. (cond
  6097. ((integerp arg)
  6098. (outline-show-all)
  6099. (outline-hide-sublevels arg)
  6100. (setq org-cycle-global-status 'contents))
  6101. ((equal arg '(4))
  6102. (org-set-startup-visibility)
  6103. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6104. (t
  6105. (org-cycle '(4))))))
  6106. (defun org-set-startup-visibility ()
  6107. "Set the visibility required by startup options and properties."
  6108. (cond
  6109. ((eq org-startup-folded t)
  6110. (org-overview))
  6111. ((eq org-startup-folded 'content)
  6112. (org-content))
  6113. ((or (eq org-startup-folded 'showeverything)
  6114. (eq org-startup-folded nil))
  6115. (outline-show-all)))
  6116. (unless (eq org-startup-folded 'showeverything)
  6117. (when org-hide-block-startup (org-hide-block-all))
  6118. (org-set-visibility-according-to-property 'no-cleanup)
  6119. (org-cycle-hide-archived-subtrees 'all)
  6120. (org-cycle-hide-drawers 'all)
  6121. (org-cycle-show-empty-lines t)))
  6122. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6123. "Switch subtree visibilities according to :VISIBILITY: property."
  6124. (interactive)
  6125. (org-with-wide-buffer
  6126. (goto-char (point-min))
  6127. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6128. (if (not (org-at-property-p)) (outline-next-heading)
  6129. (let ((state (match-string 3)))
  6130. (save-excursion
  6131. (org-back-to-heading t)
  6132. (outline-hide-subtree)
  6133. (org-reveal)
  6134. (cond
  6135. ((equal state "folded")
  6136. (outline-hide-subtree))
  6137. ((equal state "children")
  6138. (org-show-hidden-entry)
  6139. (org-show-children))
  6140. ((equal state "content")
  6141. (save-excursion
  6142. (save-restriction
  6143. (org-narrow-to-subtree)
  6144. (org-content))))
  6145. ((member state '("all" "showall"))
  6146. (outline-show-subtree)))))))
  6147. (unless no-cleanup
  6148. (org-cycle-hide-archived-subtrees 'all)
  6149. (org-cycle-hide-drawers 'all)
  6150. (org-cycle-show-empty-lines 'all))))
  6151. ;; This function uses outline-regexp instead of the more fundamental
  6152. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6153. ;; buffers, where outline-regexp is needed.
  6154. (defun org-overview ()
  6155. "Switch to overview mode, showing only top-level headlines.
  6156. This shows all headlines with a level equal or greater than the level
  6157. of the first headline in the buffer. This is important, because if the
  6158. first headline is not level one, then (hide-sublevels 1) gives confusing
  6159. results."
  6160. (interactive)
  6161. (save-excursion
  6162. (let ((level
  6163. (save-excursion
  6164. (goto-char (point-min))
  6165. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6166. (goto-char (match-beginning 0))
  6167. (funcall outline-level)))))
  6168. (and level (outline-hide-sublevels level)))))
  6169. (defun org-content (&optional arg)
  6170. "Show all headlines in the buffer, like a table of contents.
  6171. With numerical argument N, show content up to level N."
  6172. (interactive "P")
  6173. (org-overview)
  6174. (save-excursion
  6175. ;; Visit all headings and show their offspring
  6176. (and (integerp arg) (org-overview))
  6177. (goto-char (point-max))
  6178. (catch 'exit
  6179. (while (and (progn (condition-case nil
  6180. (outline-previous-visible-heading 1)
  6181. (error (goto-char (point-min))))
  6182. t)
  6183. (looking-at org-outline-regexp))
  6184. (if (integerp arg)
  6185. (org-show-children (1- arg))
  6186. (outline-show-branches))
  6187. (when (bobp) (throw 'exit nil))))))
  6188. (defun org-optimize-window-after-visibility-change (state)
  6189. "Adjust the window after a change in outline visibility.
  6190. This function is the default value of the hook `org-cycle-hook'."
  6191. (when (get-buffer-window (current-buffer))
  6192. (cond
  6193. ((eq state 'content) nil)
  6194. ((eq state 'all) nil)
  6195. ((eq state 'folded) nil)
  6196. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6197. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6198. (defun org-remove-empty-overlays-at (pos)
  6199. "Remove outline overlays that do not contain non-white stuff."
  6200. (dolist (o (overlays-at pos))
  6201. (and (eq 'outline (overlay-get o 'invisible))
  6202. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6203. (overlay-end o))))
  6204. (delete-overlay o))))
  6205. (defun org-clean-visibility-after-subtree-move ()
  6206. "Fix visibility issues after moving a subtree."
  6207. ;; First, find a reasonable region to look at:
  6208. ;; Start two siblings above, end three below
  6209. (let* ((beg (save-excursion
  6210. (and (org-get-last-sibling)
  6211. (org-get-last-sibling))
  6212. (point)))
  6213. (end (save-excursion
  6214. (and (org-get-next-sibling)
  6215. (org-get-next-sibling)
  6216. (org-get-next-sibling))
  6217. (if (org-at-heading-p)
  6218. (point-at-eol)
  6219. (point))))
  6220. (level (looking-at "\\*+"))
  6221. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6222. (save-excursion
  6223. (save-restriction
  6224. (narrow-to-region beg end)
  6225. (when re
  6226. ;; Properly fold already folded siblings
  6227. (goto-char (point-min))
  6228. (while (re-search-forward re nil t)
  6229. (when (and (not (org-invisible-p))
  6230. (save-excursion
  6231. (goto-char (point-at-eol)) (org-invisible-p)))
  6232. (outline-hide-entry))))
  6233. (org-cycle-show-empty-lines 'overview)
  6234. (org-cycle-hide-drawers 'overview)))))
  6235. (defun org-cycle-show-empty-lines (state)
  6236. "Show empty lines above all visible headlines.
  6237. The region to be covered depends on STATE when called through
  6238. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6239. entire buffer covered. Note that an empty line is only shown if there
  6240. are at least `org-cycle-separator-lines' empty lines before the headline."
  6241. (when (/= org-cycle-separator-lines 0)
  6242. (save-excursion
  6243. (let* ((n (abs org-cycle-separator-lines))
  6244. (re (cond
  6245. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6246. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6247. (t (let ((ns (number-to-string (- n 2))))
  6248. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6249. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6250. beg end)
  6251. (cond
  6252. ((memq state '(overview contents t))
  6253. (setq beg (point-min) end (point-max)))
  6254. ((memq state '(children folded))
  6255. (setq beg (point)
  6256. end (progn (org-end-of-subtree t t)
  6257. (line-beginning-position 2)))))
  6258. (when beg
  6259. (goto-char beg)
  6260. (while (re-search-forward re end t)
  6261. (unless (get-char-property (match-end 1) 'invisible)
  6262. (let ((e (match-end 1))
  6263. (b (if (>= org-cycle-separator-lines 0)
  6264. (match-beginning 1)
  6265. (save-excursion
  6266. (goto-char (match-beginning 0))
  6267. (skip-chars-backward " \t\n")
  6268. (line-end-position)))))
  6269. (outline-flag-region b e nil))))))))
  6270. ;; Never hide empty lines at the end of the file.
  6271. (save-excursion
  6272. (goto-char (point-max))
  6273. (outline-previous-heading)
  6274. (outline-end-of-heading)
  6275. (when (and (looking-at "[ \t\n]+")
  6276. (= (match-end 0) (point-max)))
  6277. (outline-flag-region (point) (match-end 0) nil))))
  6278. (defun org-show-empty-lines-in-parent ()
  6279. "Move to the parent and re-show empty lines before visible headlines."
  6280. (save-excursion
  6281. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6282. (org-cycle-show-empty-lines context))))
  6283. (defun org-files-list ()
  6284. "Return `org-agenda-files' list, plus all open Org files.
  6285. This is useful for operations that need to scan all of a user's
  6286. open and agenda-wise Org files."
  6287. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  6288. (dolist (buf (buffer-list))
  6289. (with-current-buffer buf
  6290. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6291. (cl-pushnew (expand-file-name (buffer-file-name)) files
  6292. :test #'equal))))
  6293. files))
  6294. (defsubst org-entry-beginning-position ()
  6295. "Return the beginning position of the current entry."
  6296. (save-excursion (org-back-to-heading t) (point)))
  6297. (defsubst org-entry-end-position ()
  6298. "Return the end position of the current entry."
  6299. (save-excursion (outline-next-heading) (point)))
  6300. (defun org-cycle-hide-drawers (state &optional exceptions)
  6301. "Re-hide all drawers after a visibility state change.
  6302. STATE should be one of the symbols listed in the docstring of
  6303. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6304. a list of strings specifying which drawers should not be hidden."
  6305. (when (and (derived-mode-p 'org-mode)
  6306. (not (memq state '(overview folded contents))))
  6307. (save-excursion
  6308. (let* ((globalp (eq state 'all))
  6309. (beg (if globalp (point-min) (point)))
  6310. (end (if globalp (point-max)
  6311. (if (eq state 'children)
  6312. (save-excursion (outline-next-heading) (point))
  6313. (org-end-of-subtree t)))))
  6314. (goto-char beg)
  6315. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6316. (unless (member-ignore-case (match-string 1) exceptions)
  6317. (let ((drawer (org-element-at-point)))
  6318. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6319. (org-flag-drawer t drawer)
  6320. ;; Make sure to skip drawer entirely or we might flag
  6321. ;; it another time when matching its ending line with
  6322. ;; `org-drawer-regexp'.
  6323. (goto-char (org-element-property :end drawer))))))))))
  6324. (defun org-flag-drawer (flag &optional element)
  6325. "When FLAG is non-nil, hide the drawer we are at.
  6326. Otherwise make it visible. When optional argument ELEMENT is
  6327. a parsed drawer, as returned by `org-element-at-point', hide or
  6328. show that drawer instead."
  6329. (let ((drawer (or element
  6330. (and (save-excursion
  6331. (beginning-of-line)
  6332. (looking-at-p org-drawer-regexp))
  6333. (org-element-at-point)))))
  6334. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6335. (let ((post (org-element-property :post-affiliated drawer)))
  6336. (save-excursion
  6337. (outline-flag-region
  6338. (progn (goto-char post) (line-end-position))
  6339. (progn (goto-char (org-element-property :end drawer))
  6340. (skip-chars-backward " \r\t\n")
  6341. (line-end-position))
  6342. flag))
  6343. ;; When the drawer is hidden away, make sure point lies in
  6344. ;; a visible part of the buffer.
  6345. (when (and flag (> (line-beginning-position) post))
  6346. (goto-char post))))))
  6347. (defun org-subtree-end-visible-p ()
  6348. "Is the end of the current subtree visible?"
  6349. (pos-visible-in-window-p
  6350. (save-excursion (org-end-of-subtree t) (point))))
  6351. (defun org-first-headline-recenter ()
  6352. "Move cursor to the first headline and recenter the headline."
  6353. (let ((window (get-buffer-window)))
  6354. (when window
  6355. (goto-char (point-min))
  6356. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6357. (set-window-start window (line-beginning-position))))))
  6358. ;;; Saving and restoring visibility
  6359. (defun org-outline-overlay-data (&optional use-markers)
  6360. "Return a list of the locations of all outline overlays.
  6361. These are overlays with the `invisible' property value `outline'.
  6362. The return value is a list of cons cells, with start and stop
  6363. positions for each overlay.
  6364. If USE-MARKERS is set, return the positions as markers."
  6365. (let (beg end)
  6366. (org-with-wide-buffer
  6367. (delq nil
  6368. (mapcar (lambda (o)
  6369. (when (eq (overlay-get o 'invisible) 'outline)
  6370. (setq beg (overlay-start o)
  6371. end (overlay-end o))
  6372. (and beg end (> end beg)
  6373. (if use-markers
  6374. (cons (copy-marker beg)
  6375. (copy-marker end t))
  6376. (cons beg end)))))
  6377. (overlays-in (point-min) (point-max)))))))
  6378. (defun org-set-outline-overlay-data (data)
  6379. "Create visibility overlays for all positions in DATA.
  6380. DATA should have been made by `org-outline-overlay-data'."
  6381. (org-with-wide-buffer
  6382. (outline-show-all)
  6383. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6384. ;;; Folding of blocks
  6385. (defvar-local org-hide-block-overlays nil
  6386. "Overlays hiding blocks.")
  6387. (defun org-block-map (function &optional start end)
  6388. "Call FUNCTION at the head of all source blocks in the current buffer.
  6389. Optional arguments START and END can be used to limit the range."
  6390. (let ((start (or start (point-min)))
  6391. (end (or end (point-max))))
  6392. (save-excursion
  6393. (goto-char start)
  6394. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6395. (save-excursion
  6396. (save-match-data
  6397. (goto-char (match-beginning 0))
  6398. (funcall function)))))))
  6399. (defun org-hide-block-toggle-all ()
  6400. "Toggle the visibility of all blocks in the current buffer."
  6401. (org-block-map 'org-hide-block-toggle))
  6402. (defun org-hide-block-all ()
  6403. "Fold all blocks in the current buffer."
  6404. (interactive)
  6405. (org-show-block-all)
  6406. (org-block-map 'org-hide-block-toggle-maybe))
  6407. (defun org-show-block-all ()
  6408. "Unfold all blocks in the current buffer."
  6409. (interactive)
  6410. (mapc #'delete-overlay org-hide-block-overlays)
  6411. (setq org-hide-block-overlays nil))
  6412. (defun org-hide-block-toggle-maybe ()
  6413. "Toggle visibility of block at point.
  6414. Unlike to `org-hide-block-toggle', this function does not throw
  6415. an error. Return a non-nil value when toggling is successful."
  6416. (interactive)
  6417. (ignore-errors (org-hide-block-toggle)))
  6418. (defun org-hide-block-toggle (&optional force)
  6419. "Toggle the visibility of the current block.
  6420. When optional argument FORCE is `off', make block visible. If it
  6421. is non-nil, hide it unconditionally. Throw an error when not at
  6422. a block. Return a non-nil value when toggling is successful."
  6423. (interactive)
  6424. (let ((element (org-element-at-point)))
  6425. (unless (memq (org-element-type element)
  6426. '(center-block comment-block dynamic-block example-block
  6427. export-block quote-block special-block
  6428. src-block verse-block))
  6429. (user-error "Not at a block"))
  6430. (let* ((start (save-excursion
  6431. (goto-char (org-element-property :post-affiliated element))
  6432. (line-end-position)))
  6433. (end (save-excursion
  6434. (goto-char (org-element-property :end element))
  6435. (skip-chars-backward " \r\t\n")
  6436. (line-end-position)))
  6437. (overlays (overlays-at start)))
  6438. (cond
  6439. ;; Do nothing when not before or at the block opening line or
  6440. ;; at the block closing line.
  6441. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6442. ((and (not (eq force 'off))
  6443. (not (memq t (mapcar
  6444. (lambda (o)
  6445. (eq (overlay-get o 'invisible) 'org-hide-block))
  6446. overlays))))
  6447. (let ((ov (make-overlay start end)))
  6448. (overlay-put ov 'invisible 'org-hide-block)
  6449. ;; Make the block accessible to `isearch'.
  6450. (overlay-put
  6451. ov 'isearch-open-invisible
  6452. (lambda (ov)
  6453. (when (memq ov org-hide-block-overlays)
  6454. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6455. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6456. (delete-overlay ov))))
  6457. (push ov org-hide-block-overlays)
  6458. ;; When the block is hidden away, make sure point is left in
  6459. ;; a visible part of the buffer.
  6460. (when (> (line-beginning-position) start)
  6461. (goto-char start)
  6462. (beginning-of-line))
  6463. ;; Signal successful toggling.
  6464. t))
  6465. ((or (not force) (eq force 'off))
  6466. (dolist (ov overlays t)
  6467. (when (memq ov org-hide-block-overlays)
  6468. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6469. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6470. (delete-overlay ov))))))))
  6471. ;; Remove overlays when changing major mode
  6472. (add-hook 'org-mode-hook
  6473. (lambda () (add-hook 'change-major-mode-hook
  6474. 'org-show-block-all 'append 'local)))
  6475. ;;; Indirect buffer display of subtrees
  6476. (defvar org-indirect-dedicated-frame nil
  6477. "This is the frame being used for indirect tree display.")
  6478. (defvar org-last-indirect-buffer nil)
  6479. (defun org-tree-to-indirect-buffer (&optional arg)
  6480. "Create indirect buffer and narrow it to current subtree.
  6481. With a numerical prefix ARG, go up to this level and then take that tree.
  6482. If ARG is negative, go up that many levels.
  6483. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6484. indirect buffer previously made with this command, to avoid proliferation of
  6485. indirect buffers. However, when you call the command with a \
  6486. `\\[universal-argument]' prefix, or
  6487. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6488. so that you can work with several indirect buffers at the same time. If
  6489. `org-indirect-buffer-display' is `dedicated-frame', the \
  6490. `\\[universal-argument]' prefix also
  6491. requests that a new frame be made for the new buffer, so that the dedicated
  6492. frame is not changed."
  6493. (interactive "P")
  6494. (let ((cbuf (current-buffer))
  6495. (cwin (selected-window))
  6496. (pos (point))
  6497. beg end level heading ibuf)
  6498. (save-excursion
  6499. (org-back-to-heading t)
  6500. (when (numberp arg)
  6501. (setq level (org-outline-level))
  6502. (when (< arg 0) (setq arg (+ level arg)))
  6503. (while (> (setq level (org-outline-level)) arg)
  6504. (org-up-heading-safe)))
  6505. (setq beg (point)
  6506. heading (org-get-heading 'no-tags))
  6507. (org-end-of-subtree t t)
  6508. (when (org-at-heading-p) (backward-char 1))
  6509. (setq end (point)))
  6510. (when (and (buffer-live-p org-last-indirect-buffer)
  6511. (not (eq org-indirect-buffer-display 'new-frame))
  6512. (not arg))
  6513. (kill-buffer org-last-indirect-buffer))
  6514. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6515. org-last-indirect-buffer ibuf)
  6516. (cond
  6517. ((or (eq org-indirect-buffer-display 'new-frame)
  6518. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6519. (select-frame (make-frame))
  6520. (delete-other-windows)
  6521. (pop-to-buffer-same-window ibuf)
  6522. (org-set-frame-title heading))
  6523. ((eq org-indirect-buffer-display 'dedicated-frame)
  6524. (raise-frame
  6525. (select-frame (or (and org-indirect-dedicated-frame
  6526. (frame-live-p org-indirect-dedicated-frame)
  6527. org-indirect-dedicated-frame)
  6528. (setq org-indirect-dedicated-frame (make-frame)))))
  6529. (delete-other-windows)
  6530. (pop-to-buffer-same-window ibuf)
  6531. (org-set-frame-title (concat "Indirect: " heading)))
  6532. ((eq org-indirect-buffer-display 'current-window)
  6533. (pop-to-buffer-same-window ibuf))
  6534. ((eq org-indirect-buffer-display 'other-window)
  6535. (pop-to-buffer ibuf))
  6536. (t (error "Invalid value")))
  6537. (narrow-to-region beg end)
  6538. (outline-show-all)
  6539. (goto-char pos)
  6540. (run-hook-with-args 'org-cycle-hook 'all)
  6541. (and (window-live-p cwin) (select-window cwin))))
  6542. (defun org-get-indirect-buffer (&optional buffer heading)
  6543. (setq buffer (or buffer (current-buffer)))
  6544. (let ((n 1) (base (buffer-name buffer)) bname)
  6545. (while (buffer-live-p
  6546. (get-buffer
  6547. (setq bname
  6548. (concat base "-"
  6549. (if heading (concat heading "-" (number-to-string n))
  6550. (number-to-string n))))))
  6551. (setq n (1+ n)))
  6552. (condition-case nil
  6553. (make-indirect-buffer buffer bname 'clone)
  6554. (error (make-indirect-buffer buffer bname)))))
  6555. (defun org-set-frame-title (title)
  6556. "Set the title of the current frame to the string TITLE."
  6557. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6558. ;;;; Structure editing
  6559. ;;; Inserting headlines
  6560. (defun org--line-empty-p (n)
  6561. "Is the Nth next line empty?
  6562. Counts the current line as N = 1 and the previous line as N = 0;
  6563. see `beginning-of-line'."
  6564. (save-excursion
  6565. (and (not (bobp))
  6566. (or (beginning-of-line n) t)
  6567. (save-match-data
  6568. (looking-at "[ \t]*$")))))
  6569. (defun org-previous-line-empty-p ()
  6570. "Is the previous line a blank line?
  6571. When NEXT is non-nil, check the next line instead."
  6572. (org--line-empty-p 0))
  6573. (defun org-next-line-empty-p ()
  6574. "Is the previous line a blank line?
  6575. When NEXT is non-nil, check the next line instead."
  6576. (org--line-empty-p 2))
  6577. (defun org--blank-before-heading-p (&optional parent)
  6578. "Non-nil when an empty line should precede a new heading here.
  6579. When optional argument PARENT is non-nil, consider parent
  6580. headline instead of current one."
  6581. (pcase (assq 'heading org-blank-before-new-entry)
  6582. (`(heading . auto)
  6583. (save-excursion
  6584. (org-with-limited-levels
  6585. (unless (and (org-before-first-heading-p)
  6586. (not (outline-next-heading)))
  6587. (org-back-to-heading t)
  6588. (when parent (org-up-heading-safe))
  6589. (cond ((not (bobp))
  6590. (org-previous-line-empty-p))
  6591. ((outline-next-heading)
  6592. (org-previous-line-empty-p))
  6593. ;; Ignore trailing spaces on last buffer line.
  6594. ((progn (skip-chars-backward " \t") (bolp))
  6595. (org-previous-line-empty-p))
  6596. (t nil))))))
  6597. (`(heading . ,value) value)
  6598. (_ nil)))
  6599. (defun org-insert-heading (&optional arg invisible-ok top)
  6600. "Insert a new heading or an item with the same depth at point.
  6601. If point is at the beginning of a heading, insert a new heading
  6602. or a new headline above the current one. When at the beginning
  6603. of a regular line of text, turn it into a heading.
  6604. If point is in the middle of a line, split it and create a new
  6605. headline with the text in the current line after point (see
  6606. `org-M-RET-may-split-line' on how to modify this behavior). As
  6607. a special case, on a headline, splitting can only happen on the
  6608. title itself. E.g., this excludes breaking stars or tags.
  6609. With a `\\[universal-argument]' prefix, set \
  6610. `org-insert-heading-respect-content' to
  6611. a non-nil value for the duration of the command. This forces the
  6612. insertion of a heading after the current subtree, independently
  6613. on the location of point.
  6614. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6615. insert the heading at the end of the tree
  6616. above the current heading. For example, if point is within a
  6617. 2nd-level heading, then it will insert a 2nd-level heading at
  6618. the end of the 1st-level parent subtree.
  6619. When INVISIBLE-OK is set, stop at invisible headlines when going
  6620. back. This is important for non-interactive uses of the
  6621. command.
  6622. When optional argument TOP is non-nil, insert a level 1 heading,
  6623. unconditionally."
  6624. (interactive "P")
  6625. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6626. (level (org-current-level))
  6627. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6628. (cond
  6629. ((or org-insert-heading-respect-content
  6630. (member arg '((4) (16)))
  6631. (and (not invisible-ok)
  6632. (invisible-p (max (1- (point)) (point-min)))))
  6633. ;; Position point at the location of insertion.
  6634. (if (not level) ;before first headline
  6635. (org-with-limited-levels (outline-next-heading))
  6636. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6637. ;; is nil.
  6638. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6639. (cond ((equal arg '(16))
  6640. (org-up-heading-safe)
  6641. (org-end-of-subtree t t))
  6642. (t
  6643. (org-end-of-subtree t t))))
  6644. (unless (bolp) (insert "\n")) ;ensure final newline
  6645. (unless (and blank? (org-previous-line-empty-p))
  6646. (org-N-empty-lines-before-current (if blank? 1 0)))
  6647. (insert stars " \n")
  6648. (forward-char -1))
  6649. ;; At a headline...
  6650. ((org-at-heading-p)
  6651. (cond ((bolp)
  6652. (when blank? (save-excursion (insert "\n")))
  6653. (save-excursion (insert stars " \n"))
  6654. (unless (and blank? (org-previous-line-empty-p))
  6655. (org-N-empty-lines-before-current (if blank? 1 0)))
  6656. (end-of-line))
  6657. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6658. (org-match-line org-complex-heading-regexp)
  6659. (org-pos-in-match-range (point) 4))
  6660. ;; Grab the text that should moved to the new headline.
  6661. ;; Preserve tags.
  6662. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6663. (if (looking-at "[ \t]*$") (replace-match "")
  6664. (org-set-tags nil t))
  6665. (end-of-line)
  6666. (when blank? (insert "\n"))
  6667. (insert "\n" stars " ")
  6668. (when (org-string-nw-p split) (insert split))
  6669. (when (eobp) (save-excursion (insert "\n")))))
  6670. (t
  6671. (end-of-line)
  6672. (when blank? (insert "\n"))
  6673. (insert "\n" stars " ")
  6674. (when (eobp) (save-excursion (insert "\n"))))))
  6675. ;; On regular text, turn line into a headline or split, if
  6676. ;; appropriate.
  6677. ((bolp)
  6678. (insert stars " ")
  6679. (unless (and blank? (org-previous-line-empty-p))
  6680. (org-N-empty-lines-before-current (if blank? 1 0))))
  6681. (t
  6682. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6683. (end-of-line))
  6684. (insert "\n" stars " ")
  6685. (unless (and blank? (org-previous-line-empty-p))
  6686. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6687. (run-hooks 'org-insert-heading-hook))
  6688. (defun org-N-empty-lines-before-current (n)
  6689. "Make the number of empty lines before current exactly N.
  6690. So this will delete or add empty lines."
  6691. (let ((column (current-column)))
  6692. (beginning-of-line)
  6693. (unless (bobp)
  6694. (let ((start (save-excursion
  6695. (skip-chars-backward " \r\t\n")
  6696. (line-end-position))))
  6697. (delete-region start (line-end-position 0))))
  6698. (insert (make-string n ?\n))
  6699. (move-to-column column)))
  6700. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6701. "Return the heading of the current entry, without the stars.
  6702. When NO-TAGS is non-nil, don't include tags.
  6703. When NO-TODO is non-nil, don't include TODO keywords.
  6704. When NO-PRIORITY is non-nil, don't include priority cookie.
  6705. When NO-COMMENT is non-nil, don't include COMMENT string."
  6706. (save-excursion
  6707. (org-back-to-heading t)
  6708. (let ((case-fold-search nil))
  6709. (looking-at org-complex-heading-regexp)
  6710. (let ((todo (and (not no-todo) (match-string 2)))
  6711. (priority (and (not no-priority) (match-string 3)))
  6712. (headline (pcase (match-string 4)
  6713. (`nil "")
  6714. ((and (guard no-comment) h)
  6715. (replace-regexp-in-string
  6716. (eval-when-compile
  6717. (format "\\`%s[ \t]+" org-comment-string))
  6718. "" h))
  6719. (h h)))
  6720. (tags (and (not no-tags) (match-string 5))))
  6721. (mapconcat #'identity
  6722. (delq nil (list todo priority headline tags))
  6723. " ")))))
  6724. (defvar orgstruct-mode) ; defined below
  6725. (defun org-heading-components ()
  6726. "Return the components of the current heading.
  6727. This is a list with the following elements:
  6728. - the level as an integer
  6729. - the reduced level, different if `org-odd-levels-only' is set.
  6730. - the TODO keyword, or nil
  6731. - the priority character, like ?A, or nil if no priority is given
  6732. - the headline text itself, or the tags string if no headline text
  6733. - the tags string, or nil."
  6734. (save-excursion
  6735. (org-back-to-heading t)
  6736. (when (let (case-fold-search)
  6737. (looking-at
  6738. (if orgstruct-mode
  6739. org-heading-regexp
  6740. org-complex-heading-regexp)))
  6741. (if orgstruct-mode
  6742. (list (length (match-string 1))
  6743. (org-reduced-level (length (match-string 1)))
  6744. nil
  6745. nil
  6746. (match-string 2)
  6747. nil)
  6748. (list (length (match-string 1))
  6749. (org-reduced-level (length (match-string 1)))
  6750. (match-string-no-properties 2)
  6751. (and (match-end 3) (aref (match-string 3) 2))
  6752. (match-string-no-properties 4)
  6753. (match-string-no-properties 5))))))
  6754. (defun org-get-entry ()
  6755. "Get the entry text, after heading, entire subtree."
  6756. (save-excursion
  6757. (org-back-to-heading t)
  6758. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6759. (defun org-edit-headline (&optional heading)
  6760. "Edit the current headline.
  6761. Set it to HEADING when provided."
  6762. (interactive)
  6763. (org-with-wide-buffer
  6764. (org-back-to-heading t)
  6765. (let ((case-fold-search nil))
  6766. (when (looking-at org-complex-heading-regexp)
  6767. (let* ((old (match-string-no-properties 4))
  6768. (new (save-match-data
  6769. (org-trim (or heading (read-string "Edit: " old))))))
  6770. (unless (equal old new)
  6771. (if old (replace-match new t t nil 4)
  6772. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6773. (insert " " new))
  6774. (org-set-tags nil t)
  6775. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6776. (defun org-insert-heading-after-current ()
  6777. "Insert a new heading with same level as current, after current subtree."
  6778. (interactive)
  6779. (org-back-to-heading)
  6780. (org-insert-heading)
  6781. (org-move-subtree-down)
  6782. (end-of-line 1))
  6783. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6784. "Insert heading with `org-insert-heading-respect-content' set to t."
  6785. (interactive)
  6786. (org-insert-heading '(4) invisible-ok))
  6787. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6788. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6789. (interactive)
  6790. (org-insert-todo-heading force-state '(4)))
  6791. (defun org-insert-todo-heading (arg &optional force-heading)
  6792. "Insert a new heading with the same level and TODO state as current heading.
  6793. If the heading has no TODO state, or if the state is DONE, use
  6794. the first state (TODO by default). Also with one prefix arg,
  6795. force first state. With two prefix args, force inserting at the
  6796. end of the parent subtree.
  6797. When called at a plain list item, insert a new item with an
  6798. unchecked check box."
  6799. (interactive "P")
  6800. (when (or force-heading (not (org-insert-item 'checkbox)))
  6801. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6802. force-heading))
  6803. (save-excursion
  6804. (org-forward-heading-same-level -1)
  6805. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6806. (let* ((new-mark-x
  6807. (if (or (equal arg '(4))
  6808. (not (match-beginning 2))
  6809. (member (match-string 2) org-done-keywords))
  6810. (car org-todo-keywords-1)
  6811. (match-string 2)))
  6812. (new-mark
  6813. (or
  6814. (run-hook-with-args-until-success
  6815. 'org-todo-get-default-hook new-mark-x nil)
  6816. new-mark-x)))
  6817. (beginning-of-line 1)
  6818. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6819. (if org-treat-insert-todo-heading-as-state-change
  6820. (org-todo new-mark)
  6821. (insert new-mark " "))))
  6822. (when org-provide-todo-statistics
  6823. (org-update-parent-todo-statistics))))
  6824. (defun org-insert-subheading (arg)
  6825. "Insert a new subheading and demote it.
  6826. Works for outline headings and for plain lists alike."
  6827. (interactive "P")
  6828. (org-insert-heading arg)
  6829. (cond
  6830. ((org-at-heading-p) (org-do-demote))
  6831. ((org-at-item-p) (org-indent-item))))
  6832. (defun org-insert-todo-subheading (arg)
  6833. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6834. Works for outline headings and for plain lists alike."
  6835. (interactive "P")
  6836. (org-insert-todo-heading arg)
  6837. (cond
  6838. ((org-at-heading-p) (org-do-demote))
  6839. ((org-at-item-p) (org-indent-item))))
  6840. ;;; Promotion and Demotion
  6841. (defvar org-after-demote-entry-hook nil
  6842. "Hook run after an entry has been demoted.
  6843. The cursor will be at the beginning of the entry.
  6844. When a subtree is being demoted, the hook will be called for each node.")
  6845. (defvar org-after-promote-entry-hook nil
  6846. "Hook run after an entry has been promoted.
  6847. The cursor will be at the beginning of the entry.
  6848. When a subtree is being promoted, the hook will be called for each node.")
  6849. (defun org-promote-subtree ()
  6850. "Promote the entire subtree.
  6851. See also `org-promote'."
  6852. (interactive)
  6853. (save-excursion
  6854. (org-with-limited-levels (org-map-tree 'org-promote)))
  6855. (org-fix-position-after-promote))
  6856. (defun org-demote-subtree ()
  6857. "Demote the entire subtree.
  6858. See `org-demote' and `org-promote'."
  6859. (interactive)
  6860. (save-excursion
  6861. (org-with-limited-levels (org-map-tree 'org-demote)))
  6862. (org-fix-position-after-promote))
  6863. (defun org-do-promote ()
  6864. "Promote the current heading higher up the tree.
  6865. If the region is active in `transient-mark-mode', promote all
  6866. headings in the region."
  6867. (interactive)
  6868. (save-excursion
  6869. (if (org-region-active-p)
  6870. (org-map-region 'org-promote (region-beginning) (region-end))
  6871. (org-promote)))
  6872. (org-fix-position-after-promote))
  6873. (defun org-do-demote ()
  6874. "Demote the current heading lower down the tree.
  6875. If the region is active in `transient-mark-mode', demote all
  6876. headings in the region."
  6877. (interactive)
  6878. (save-excursion
  6879. (if (org-region-active-p)
  6880. (org-map-region 'org-demote (region-beginning) (region-end))
  6881. (org-demote)))
  6882. (org-fix-position-after-promote))
  6883. (defun org-fix-position-after-promote ()
  6884. "Fix cursor position and indentation after demoting/promoting."
  6885. (let ((pos (point)))
  6886. (when (save-excursion
  6887. (beginning-of-line)
  6888. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6889. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6890. (cond ((eobp) (insert " "))
  6891. ((eolp) (insert " "))
  6892. ((equal (char-after) ?\s) (forward-char 1))))))
  6893. (defun org-current-level ()
  6894. "Return the level of the current entry, or nil if before the first headline.
  6895. The level is the number of stars at the beginning of the
  6896. headline. Use `org-reduced-level' to remove the effect of
  6897. `org-odd-levels'. Unlike to `org-outline-level', this function
  6898. ignores inlinetasks."
  6899. (let ((level (org-with-limited-levels (org-outline-level))))
  6900. (and (> level 0) level)))
  6901. (defun org-get-previous-line-level ()
  6902. "Return the outline depth of the last headline before the current line.
  6903. Returns 0 for the first headline in the buffer, and nil if before the
  6904. first headline."
  6905. (and (org-current-level)
  6906. (or (and (/= (line-beginning-position) (point-min))
  6907. (save-excursion (beginning-of-line 0) (org-current-level)))
  6908. 0)))
  6909. (defun org-reduced-level (l)
  6910. "Compute the effective level of a heading.
  6911. This takes into account the setting of `org-odd-levels-only'."
  6912. (cond
  6913. ((zerop l) 0)
  6914. (org-odd-levels-only (1+ (floor (/ l 2))))
  6915. (t l)))
  6916. (defun org-level-increment ()
  6917. "Return the number of stars that will be added or removed at a
  6918. time to headlines when structure editing, based on the value of
  6919. `org-odd-levels-only'."
  6920. (if org-odd-levels-only 2 1))
  6921. (defun org-get-valid-level (level &optional change)
  6922. "Rectify a level change under the influence of `org-odd-levels-only'.
  6923. LEVEL is a current level, CHANGE is by how much the level should
  6924. be modified. Even if CHANGE is nil, LEVEL may be returned
  6925. modified because even level numbers will become the next higher
  6926. odd number. Returns values greater than 0."
  6927. (if org-odd-levels-only
  6928. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6929. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6930. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6931. (max 1 (+ level (or change 0)))))
  6932. (defun org-promote ()
  6933. "Promote the current heading higher up the tree."
  6934. (org-with-wide-buffer
  6935. (org-back-to-heading t)
  6936. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6937. after-change-functions))
  6938. (level (save-match-data (funcall outline-level)))
  6939. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6940. (diff (abs (- level (length up-head) -1))))
  6941. (cond
  6942. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6943. (replace-match "# " nil t))
  6944. ((= level 1)
  6945. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6946. (t (replace-match up-head nil t)))
  6947. (unless (= level 1)
  6948. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6949. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6950. (run-hooks 'org-after-promote-entry-hook))))
  6951. (defun org-demote ()
  6952. "Demote the current heading lower down the tree."
  6953. (org-with-wide-buffer
  6954. (org-back-to-heading t)
  6955. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6956. after-change-functions))
  6957. (level (save-match-data (funcall outline-level)))
  6958. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6959. (diff (abs (- level (length down-head) -1))))
  6960. (replace-match down-head nil t)
  6961. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6962. (when org-adapt-indentation (org-fixup-indentation diff))
  6963. (run-hooks 'org-after-demote-entry-hook))))
  6964. (defun org-cycle-level ()
  6965. "Cycle the level of an empty headline through possible states.
  6966. This goes first to child, then to parent, level, then up the hierarchy.
  6967. After top level, it switches back to sibling level."
  6968. (interactive)
  6969. (let ((org-adapt-indentation nil))
  6970. (when (org-point-at-end-of-empty-headline)
  6971. (setq this-command 'org-cycle-level) ; Only needed for caching
  6972. (let ((cur-level (org-current-level))
  6973. (prev-level (org-get-previous-line-level)))
  6974. (cond
  6975. ;; If first headline in file, promote to top-level.
  6976. ((= prev-level 0)
  6977. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6978. do (org-do-promote)))
  6979. ;; If same level as prev, demote one.
  6980. ((= prev-level cur-level)
  6981. (org-do-demote))
  6982. ;; If parent is top-level, promote to top level if not already.
  6983. ((= prev-level 1)
  6984. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6985. do (org-do-promote)))
  6986. ;; If top-level, return to prev-level.
  6987. ((= cur-level 1)
  6988. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6989. do (org-do-demote)))
  6990. ;; If less than prev-level, promote one.
  6991. ((< cur-level prev-level)
  6992. (org-do-promote))
  6993. ;; If deeper than prev-level, promote until higher than
  6994. ;; prev-level.
  6995. ((> cur-level prev-level)
  6996. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6997. do (org-do-promote))))
  6998. t))))
  6999. (defun org-map-tree (fun)
  7000. "Call FUN for every heading underneath the current one."
  7001. (org-back-to-heading t)
  7002. (let ((level (funcall outline-level)))
  7003. (save-excursion
  7004. (funcall fun)
  7005. (while (and (progn
  7006. (outline-next-heading)
  7007. (> (funcall outline-level) level))
  7008. (not (eobp)))
  7009. (funcall fun)))))
  7010. (defun org-map-region (fun beg end)
  7011. "Call FUN for every heading between BEG and END."
  7012. (let ((org-ignore-region t))
  7013. (save-excursion
  7014. (setq end (copy-marker end))
  7015. (goto-char beg)
  7016. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7017. (< (point) end))
  7018. (funcall fun))
  7019. (while (and (progn
  7020. (outline-next-heading)
  7021. (< (point) end))
  7022. (not (eobp)))
  7023. (funcall fun)))))
  7024. (defun org-fixup-indentation (diff)
  7025. "Change the indentation in the current entry by DIFF.
  7026. DIFF is an integer. Indentation is done according to the
  7027. following rules:
  7028. - Planning information and property drawers are always indented
  7029. according to the new level of the headline;
  7030. - Footnote definitions and their contents are ignored;
  7031. - Inlinetasks' boundaries are not shifted;
  7032. - Empty lines are ignored;
  7033. - Other lines' indentation are shifted by DIFF columns, unless
  7034. it would introduce a structural change in the document, in
  7035. which case no shifting is done at all.
  7036. Assume point is at a heading or an inlinetask beginning."
  7037. (org-with-wide-buffer
  7038. (narrow-to-region (line-beginning-position)
  7039. (save-excursion
  7040. (if (org-with-limited-levels (org-at-heading-p))
  7041. (org-with-limited-levels (outline-next-heading))
  7042. (org-inlinetask-goto-end))
  7043. (point)))
  7044. (forward-line)
  7045. ;; Indent properly planning info and property drawer.
  7046. (when (looking-at-p org-planning-line-re)
  7047. (org-indent-line)
  7048. (forward-line))
  7049. (when (looking-at org-property-drawer-re)
  7050. (goto-char (match-end 0))
  7051. (forward-line)
  7052. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7053. (catch 'no-shift
  7054. (when (zerop diff) (throw 'no-shift nil))
  7055. ;; If DIFF is negative, first check if a shift is possible at all
  7056. ;; (e.g., it doesn't break structure). This can only happen if
  7057. ;; some contents are not properly indented.
  7058. (let ((case-fold-search t))
  7059. (when (< diff 0)
  7060. (let ((diff (- diff))
  7061. (forbidden-re (concat org-outline-regexp
  7062. "\\|"
  7063. (substring org-footnote-definition-re 1))))
  7064. (save-excursion
  7065. (while (not (eobp))
  7066. (cond
  7067. ((looking-at-p "[ \t]*$") (forward-line))
  7068. ((and (looking-at-p org-footnote-definition-re)
  7069. (let ((e (org-element-at-point)))
  7070. (and (eq (org-element-type e) 'footnote-definition)
  7071. (goto-char (org-element-property :end e))))))
  7072. ((looking-at-p org-outline-regexp) (forward-line))
  7073. ;; Give up if shifting would move before column 0 or
  7074. ;; if it would introduce a headline or a footnote
  7075. ;; definition.
  7076. (t
  7077. (skip-chars-forward " \t")
  7078. (let ((ind (current-column)))
  7079. (when (or (< ind diff)
  7080. (and (= ind diff) (looking-at-p forbidden-re)))
  7081. (throw 'no-shift nil)))
  7082. ;; Ignore contents of example blocks and source
  7083. ;; blocks if their indentation is meant to be
  7084. ;; preserved. Jump to block's closing line.
  7085. (beginning-of-line)
  7086. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7087. (let ((e (org-element-at-point)))
  7088. (and (memq (org-element-type e)
  7089. '(example-block src-block))
  7090. (or org-src-preserve-indentation
  7091. (org-element-property :preserve-indent e))
  7092. (goto-char (org-element-property :end e))
  7093. (progn (skip-chars-backward " \r\t\n")
  7094. (beginning-of-line)
  7095. t))))
  7096. (forward-line))))))))
  7097. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7098. ;; by DIFF. Also skip contents of source or example blocks
  7099. ;; when indentation is meant to be preserved.
  7100. (while (not (eobp))
  7101. (cond
  7102. ((and (looking-at-p org-footnote-definition-re)
  7103. (let ((e (org-element-at-point)))
  7104. (and (eq (org-element-type e) 'footnote-definition)
  7105. (goto-char (org-element-property :end e))))))
  7106. ((looking-at-p org-outline-regexp) (forward-line))
  7107. ((looking-at-p "[ \t]*$") (forward-line))
  7108. (t
  7109. (indent-line-to (+ (org-get-indentation) diff))
  7110. (beginning-of-line)
  7111. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7112. (let ((e (org-element-at-point)))
  7113. (and (memq (org-element-type e)
  7114. '(example-block src-block))
  7115. (or org-src-preserve-indentation
  7116. (org-element-property :preserve-indent e))
  7117. (goto-char (org-element-property :end e))
  7118. (progn (skip-chars-backward " \r\t\n")
  7119. (beginning-of-line)
  7120. t))))
  7121. (forward-line)))))))))
  7122. (defun org-convert-to-odd-levels ()
  7123. "Convert an Org file with all levels allowed to one with odd levels.
  7124. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7125. level 5 etc."
  7126. (interactive)
  7127. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7128. (let ((outline-level 'org-outline-level)
  7129. (org-odd-levels-only nil) n)
  7130. (save-excursion
  7131. (goto-char (point-min))
  7132. (while (re-search-forward "^\\*\\*+ " nil t)
  7133. (setq n (- (length (match-string 0)) 2))
  7134. (while (>= (setq n (1- n)) 0)
  7135. (org-demote))
  7136. (end-of-line 1))))))
  7137. (defun org-convert-to-oddeven-levels ()
  7138. "Convert an Org file with only odd levels to one with odd/even levels.
  7139. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7140. file contains a section with an even level, conversion would
  7141. destroy the structure of the file. An error is signaled in this
  7142. case."
  7143. (interactive)
  7144. (goto-char (point-min))
  7145. ;; First check if there are no even levels
  7146. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7147. (org-show-set-visibility 'canonical)
  7148. (error "Not all levels are odd in this file. Conversion not possible"))
  7149. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7150. (let ((outline-regexp org-outline-regexp)
  7151. (outline-level 'org-outline-level)
  7152. (org-odd-levels-only nil) n)
  7153. (save-excursion
  7154. (goto-char (point-min))
  7155. (while (re-search-forward "^\\*\\*+ " nil t)
  7156. (setq n (/ (1- (length (match-string 0))) 2))
  7157. (while (>= (setq n (1- n)) 0)
  7158. (org-promote))
  7159. (end-of-line 1))))))
  7160. (defun org-tr-level (n)
  7161. "Make N odd if required."
  7162. (if org-odd-levels-only (1+ (/ n 2)) n))
  7163. ;;; Vertical tree motion, cutting and pasting of subtrees
  7164. (defun org-move-subtree-up (&optional arg)
  7165. "Move the current subtree up past ARG headlines of the same level."
  7166. (interactive "p")
  7167. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7168. (defun org-move-subtree-down (&optional arg)
  7169. "Move the current subtree down past ARG headlines of the same level."
  7170. (interactive "p")
  7171. (setq arg (prefix-numeric-value arg))
  7172. (org-preserve-local-variables
  7173. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7174. 'org-get-last-sibling))
  7175. (ins-point (make-marker))
  7176. (cnt (abs arg))
  7177. (col (current-column))
  7178. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7179. ;; Select the tree
  7180. (org-back-to-heading)
  7181. (setq beg0 (point))
  7182. (save-excursion
  7183. (setq ne-beg (org-back-over-empty-lines))
  7184. (setq beg (point)))
  7185. (save-match-data
  7186. (save-excursion (outline-end-of-heading)
  7187. (setq folded (org-invisible-p)))
  7188. (progn (org-end-of-subtree nil t)
  7189. (unless (eobp) (backward-char))))
  7190. (outline-next-heading)
  7191. (setq ne-end (org-back-over-empty-lines))
  7192. (setq end (point))
  7193. (goto-char beg0)
  7194. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7195. ;; include less whitespace
  7196. (save-excursion
  7197. (goto-char beg)
  7198. (forward-line (- ne-beg ne-end))
  7199. (setq beg (point))))
  7200. ;; Find insertion point, with error handling
  7201. (while (> cnt 0)
  7202. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7203. (progn (goto-char beg0)
  7204. (user-error "Cannot move past superior level or buffer limit")))
  7205. (setq cnt (1- cnt)))
  7206. (when (> arg 0)
  7207. ;; Moving forward - still need to move over subtree
  7208. (org-end-of-subtree t t)
  7209. (save-excursion
  7210. (org-back-over-empty-lines)
  7211. (unless (bolp) (insert "\n"))))
  7212. (setq ne-ins (org-back-over-empty-lines))
  7213. (move-marker ins-point (point))
  7214. (setq txt (buffer-substring beg end))
  7215. (org-save-markers-in-region beg end)
  7216. (delete-region beg end)
  7217. (org-remove-empty-overlays-at beg)
  7218. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7219. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7220. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7221. (let ((bbb (point)))
  7222. (insert-before-markers txt)
  7223. (org-reinstall-markers-in-region bbb)
  7224. (move-marker ins-point bbb))
  7225. (or (bolp) (insert "\n"))
  7226. (setq ins-end (point))
  7227. (goto-char ins-point)
  7228. (org-skip-whitespace)
  7229. (when (and (< arg 0)
  7230. (org-first-sibling-p)
  7231. (> ne-ins ne-beg))
  7232. ;; Move whitespace back to beginning.
  7233. (save-excursion
  7234. (goto-char ins-end)
  7235. (let ((kill-whole-line t))
  7236. (kill-line (- ne-ins ne-beg)) (point)))
  7237. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7238. (move-marker ins-point nil)
  7239. (if folded
  7240. (outline-hide-subtree)
  7241. (org-show-entry)
  7242. (org-show-children)
  7243. (org-cycle-hide-drawers 'children))
  7244. (org-clean-visibility-after-subtree-move)
  7245. ;; Move back to the initial column we were at.
  7246. (move-to-column col))))
  7247. (defvar org-subtree-clip ""
  7248. "Clipboard for cut and paste of subtrees.
  7249. This is actually only a copy of the kill, because we use the normal kill
  7250. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7251. (defvar org-subtree-clip-folded nil
  7252. "Was the last copied subtree folded?
  7253. This is used to fold the tree back after pasting.")
  7254. (defun org-cut-subtree (&optional n)
  7255. "Cut the current subtree into the clipboard.
  7256. With prefix arg N, cut this many sequential subtrees.
  7257. This is a short-hand for marking the subtree and then cutting it."
  7258. (interactive "p")
  7259. (org-copy-subtree n 'cut))
  7260. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7261. "Copy the current subtree it in the clipboard.
  7262. With prefix arg N, copy this many sequential subtrees.
  7263. This is a short-hand for marking the subtree and then copying it.
  7264. If CUT is non-nil, actually cut the subtree.
  7265. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7266. of some markers in the region, even if CUT is non-nil. This is
  7267. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7268. (interactive "p")
  7269. (org-preserve-local-variables
  7270. (let (beg end folded (beg0 (point)))
  7271. (if (called-interactively-p 'any)
  7272. (org-back-to-heading nil) ; take what looks like a subtree
  7273. (org-back-to-heading t)) ; take what is really there
  7274. (setq beg (point))
  7275. (skip-chars-forward " \t\r\n")
  7276. (save-match-data
  7277. (if nosubtrees
  7278. (outline-next-heading)
  7279. (save-excursion (outline-end-of-heading)
  7280. (setq folded (org-invisible-p)))
  7281. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7282. (org-end-of-subtree t t)))
  7283. ;; Include the end of an inlinetask
  7284. (when (and (featurep 'org-inlinetask)
  7285. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7286. "END[ \t]*$")))
  7287. (end-of-line))
  7288. (setq end (point))
  7289. (goto-char beg0)
  7290. (when (> end beg)
  7291. (setq org-subtree-clip-folded folded)
  7292. (when (or cut force-store-markers)
  7293. (org-save-markers-in-region beg end))
  7294. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7295. (setq org-subtree-clip (current-kill 0))
  7296. (message "%s: Subtree(s) with %d characters"
  7297. (if cut "Cut" "Copied")
  7298. (length org-subtree-clip))))))
  7299. (defun org-paste-subtree (&optional level tree for-yank remove)
  7300. "Paste the clipboard as a subtree, with modification of headline level.
  7301. The entire subtree is promoted or demoted in order to match a new headline
  7302. level.
  7303. If the cursor is at the beginning of a headline, the same level as
  7304. that headline is used to paste the tree.
  7305. If not, the new level is derived from the *visible* headings
  7306. before and after the insertion point, and taken to be the inferior headline
  7307. level of the two. So if the previous visible heading is level 3 and the
  7308. next is level 4 (or vice versa), level 4 will be used for insertion.
  7309. This makes sure that the subtree remains an independent subtree and does
  7310. not swallow low level entries.
  7311. You can also force a different level, either by using a numeric prefix
  7312. argument, or by inserting the heading marker by hand. For example, if the
  7313. cursor is after \"*****\", then the tree will be shifted to level 5.
  7314. If optional TREE is given, use this text instead of the kill ring.
  7315. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7316. move back over whitespace before inserting, and move point to the end of
  7317. the inserted text when done.
  7318. When REMOVE is non-nil, remove the subtree from the clipboard."
  7319. (interactive "P")
  7320. (setq tree (or tree (and kill-ring (current-kill 0))))
  7321. (unless (org-kill-is-subtree-p tree)
  7322. (user-error "%s"
  7323. (substitute-command-keys
  7324. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7325. (org-with-limited-levels
  7326. (let* ((visp (not (org-invisible-p)))
  7327. (txt tree)
  7328. (^re_ "\\(\\*+\\)[ \t]*")
  7329. (old-level (if (string-match org-outline-regexp-bol txt)
  7330. (- (match-end 0) (match-beginning 0) 1)
  7331. -1))
  7332. (force-level (cond (level (prefix-numeric-value level))
  7333. ((and (looking-at "[ \t]*$")
  7334. (string-match
  7335. "^\\*+$" (buffer-substring
  7336. (point-at-bol) (point))))
  7337. (- (match-end 0) (match-beginning 0)))
  7338. ((and (bolp)
  7339. (looking-at org-outline-regexp))
  7340. (- (match-end 0) (point) 1))))
  7341. (previous-level (save-excursion
  7342. (condition-case nil
  7343. (progn
  7344. (outline-previous-visible-heading 1)
  7345. (if (looking-at ^re_)
  7346. (- (match-end 0) (match-beginning 0) 1)
  7347. 1))
  7348. (error 1))))
  7349. (next-level (save-excursion
  7350. (condition-case nil
  7351. (progn
  7352. (or (looking-at org-outline-regexp)
  7353. (outline-next-visible-heading 1))
  7354. (if (looking-at ^re_)
  7355. (- (match-end 0) (match-beginning 0) 1)
  7356. 1))
  7357. (error 1))))
  7358. (new-level (or force-level (max previous-level next-level)))
  7359. (shift (if (or (= old-level -1)
  7360. (= new-level -1)
  7361. (= old-level new-level))
  7362. 0
  7363. (- new-level old-level)))
  7364. (delta (if (> shift 0) -1 1))
  7365. (func (if (> shift 0) 'org-demote 'org-promote))
  7366. (org-odd-levels-only nil)
  7367. beg end newend)
  7368. ;; Remove the forced level indicator
  7369. (when force-level
  7370. (delete-region (point-at-bol) (point)))
  7371. ;; Paste
  7372. (beginning-of-line (if (bolp) 1 2))
  7373. (setq beg (point))
  7374. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7375. (insert-before-markers txt)
  7376. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7377. (setq newend (point))
  7378. (org-reinstall-markers-in-region beg)
  7379. (setq end (point))
  7380. (goto-char beg)
  7381. (skip-chars-forward " \t\n\r")
  7382. (setq beg (point))
  7383. (when (and (org-invisible-p) visp)
  7384. (save-excursion (outline-show-heading)))
  7385. ;; Shift if necessary
  7386. (unless (= shift 0)
  7387. (save-restriction
  7388. (narrow-to-region beg end)
  7389. (while (not (= shift 0))
  7390. (org-map-region func (point-min) (point-max))
  7391. (setq shift (+ delta shift)))
  7392. (goto-char (point-min))
  7393. (setq newend (point-max))))
  7394. (when (or (called-interactively-p 'interactive) for-yank)
  7395. (message "Clipboard pasted as level %d subtree" new-level))
  7396. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7397. kill-ring
  7398. (eq org-subtree-clip (current-kill 0))
  7399. org-subtree-clip-folded)
  7400. ;; The tree was folded before it was killed/copied
  7401. (outline-hide-subtree))
  7402. (and for-yank (goto-char newend))
  7403. (and remove (setq kill-ring (cdr kill-ring))))))
  7404. (defun org-kill-is-subtree-p (&optional txt)
  7405. "Check if the current kill is an outline subtree, or a set of trees.
  7406. Returns nil if kill does not start with a headline, or if the first
  7407. headline level is not the largest headline level in the tree.
  7408. So this will actually accept several entries of equal levels as well,
  7409. which is OK for `org-paste-subtree'.
  7410. If optional TXT is given, check this string instead of the current kill."
  7411. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7412. (re (org-get-limited-outline-regexp))
  7413. (^re (concat "^" re))
  7414. (start-level (and kill
  7415. (string-match
  7416. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7417. kill)
  7418. (- (match-end 2) (match-beginning 2) 1)))
  7419. (start (1+ (or (match-beginning 2) -1))))
  7420. (if (not start-level)
  7421. (progn
  7422. nil) ;; does not even start with a heading
  7423. (catch 'exit
  7424. (while (setq start (string-match ^re kill (1+ start)))
  7425. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7426. (throw 'exit nil)))
  7427. t))))
  7428. (defvar org-markers-to-move nil
  7429. "Markers that should be moved with a cut-and-paste operation.
  7430. Those markers are stored together with their positions relative to
  7431. the start of the region.")
  7432. (defun org-save-markers-in-region (beg end)
  7433. "Check markers in region.
  7434. If these markers are between BEG and END, record their position relative
  7435. to BEG, so that after moving the block of text, we can put the markers back
  7436. into place.
  7437. This function gets called just before an entry or tree gets cut from the
  7438. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7439. called immediately, to move the markers with the entries."
  7440. (setq org-markers-to-move nil)
  7441. (when (featurep 'org-clock)
  7442. (org-clock-save-markers-for-cut-and-paste beg end))
  7443. (when (featurep 'org-agenda)
  7444. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7445. (defun org-check-and-save-marker (marker beg end)
  7446. "Check if MARKER is between BEG and END.
  7447. If yes, remember the marker and the distance to BEG."
  7448. (when (and (marker-buffer marker)
  7449. (equal (marker-buffer marker) (current-buffer))
  7450. (>= marker beg) (< marker end))
  7451. (push (cons marker (- marker beg)) org-markers-to-move)))
  7452. (defun org-reinstall-markers-in-region (beg)
  7453. "Move all remembered markers to their position relative to BEG."
  7454. (dolist (x org-markers-to-move)
  7455. (move-marker (car x) (+ beg (cdr x))))
  7456. (setq org-markers-to-move nil))
  7457. (defun org-narrow-to-subtree ()
  7458. "Narrow buffer to the current subtree."
  7459. (interactive)
  7460. (save-excursion
  7461. (save-match-data
  7462. (org-with-limited-levels
  7463. (narrow-to-region
  7464. (progn (org-back-to-heading t) (point))
  7465. (progn (org-end-of-subtree t t)
  7466. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7467. (point)))))))
  7468. (defun org-narrow-to-block ()
  7469. "Narrow buffer to the current block."
  7470. (interactive)
  7471. (let* ((case-fold-search t)
  7472. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7473. "^[ \t]*#\\+end_.*")))
  7474. (if blockp
  7475. (narrow-to-region (car blockp) (cdr blockp))
  7476. (user-error "Not in a block"))))
  7477. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7478. "Clone the task (subtree) at point N times.
  7479. The clones will be inserted as siblings.
  7480. In interactive use, the user will be prompted for the number of
  7481. clones to be produced. If the entry has a timestamp, the user
  7482. will also be prompted for a time shift, which may be a repeater
  7483. as used in time stamps, for example `+3d'. To disable this,
  7484. you can call the function with a universal prefix argument.
  7485. When a valid repeater is given and the entry contains any time
  7486. stamps, the clones will become a sequence in time, with time
  7487. stamps in the subtree shifted for each clone produced. If SHIFT
  7488. is nil or the empty string, time stamps will be left alone. The
  7489. ID property of the original subtree is removed.
  7490. In each clone, all the CLOCK entries will be removed. This
  7491. prevents Org from considering that the clocked times overlap.
  7492. If the original subtree did contain time stamps with a repeater,
  7493. the following will happen:
  7494. - the repeater will be removed in each clone
  7495. - an additional clone will be produced, with the current, unshifted
  7496. date(s) in the entry.
  7497. - the original entry will be placed *after* all the clones, with
  7498. repeater intact.
  7499. - the start days in the repeater in the original entry will be shifted
  7500. to past the last clone.
  7501. In this way you can spell out a number of instances of a repeating task,
  7502. and still retain the repeater to cover future instances of the task.
  7503. As described above, N+1 clones are produced when the original
  7504. subtree has a repeater. Setting N to 0, then, can be used to
  7505. remove the repeater from a subtree and create a shifted clone
  7506. with the original repeater."
  7507. (interactive "nNumber of clones to produce: ")
  7508. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7509. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7510. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7511. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7512. (shift
  7513. (or shift
  7514. (if (and (not (equal current-prefix-arg '(4)))
  7515. (save-excursion
  7516. (goto-char beg)
  7517. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7518. (read-from-minibuffer
  7519. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7520. ""))) ;No time shift
  7521. (doshift
  7522. (and (org-string-nw-p shift)
  7523. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7524. shift)
  7525. (user-error "Invalid shift specification %s" shift)))))
  7526. (goto-char end-of-tree)
  7527. (unless (bolp) (insert "\n"))
  7528. (let* ((end (point))
  7529. (template (buffer-substring beg end))
  7530. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7531. (shift-what (pcase (and doshift (match-string 2 shift))
  7532. (`nil nil)
  7533. ("d" 'day)
  7534. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7535. ("m" 'month)
  7536. ("y" 'year)
  7537. (_ (error "Unsupported time unit"))))
  7538. (nmin 1)
  7539. (nmax n)
  7540. (n-no-remove -1)
  7541. (idprop (org-entry-get nil "ID")))
  7542. (when (and doshift
  7543. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7544. template))
  7545. (delete-region beg end)
  7546. (setq end beg)
  7547. (setq nmin 0)
  7548. (setq nmax (1+ nmax))
  7549. (setq n-no-remove nmax))
  7550. (goto-char end)
  7551. (cl-loop for n from nmin to nmax do
  7552. (insert
  7553. ;; Prepare clone.
  7554. (with-temp-buffer
  7555. (insert template)
  7556. (org-mode)
  7557. (goto-char (point-min))
  7558. (org-show-subtree)
  7559. (and idprop (if org-clone-delete-id
  7560. (org-entry-delete nil "ID")
  7561. (org-id-get-create t)))
  7562. (unless (= n 0)
  7563. (while (re-search-forward org-clock-line-re nil t)
  7564. (delete-region (line-beginning-position)
  7565. (line-beginning-position 2)))
  7566. (goto-char (point-min))
  7567. (while (re-search-forward org-drawer-regexp nil t)
  7568. (org-remove-empty-drawer-at (point))))
  7569. (goto-char (point-min))
  7570. (when doshift
  7571. (while (re-search-forward org-ts-regexp-both nil t)
  7572. (org-timestamp-change (* n shift-n) shift-what))
  7573. (unless (= n n-no-remove)
  7574. (goto-char (point-min))
  7575. (while (re-search-forward org-ts-regexp nil t)
  7576. (save-excursion
  7577. (goto-char (match-beginning 0))
  7578. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7579. (delete-region (match-beginning 1) (match-end 1)))))))
  7580. (buffer-string)))))
  7581. (goto-char beg)))
  7582. ;;; Outline Sorting
  7583. (defun org-sort (&optional with-case)
  7584. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7585. Optional argument WITH-CASE means sort case-sensitively."
  7586. (interactive "P")
  7587. (org-call-with-arg
  7588. (cond ((org-at-table-p) #'org-table-sort-lines)
  7589. ((org-at-item-p) #'org-sort-list)
  7590. (t #'org-sort-entries))
  7591. with-case))
  7592. (defun org-sort-remove-invisible (s)
  7593. "Remove invisible part of links and emphasis markers from string S."
  7594. (remove-text-properties 0 (length s) org-rm-props s)
  7595. (replace-regexp-in-string
  7596. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7597. (replace-regexp-in-string
  7598. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7599. (org-link-display-format s)
  7600. t t) t t))
  7601. (defvar org-priority-regexp) ; defined later in the file
  7602. (defvar org-after-sorting-entries-or-items-hook nil
  7603. "Hook that is run after a bunch of entries or items have been sorted.
  7604. When children are sorted, the cursor is in the parent line when this
  7605. hook gets called. When a region or a plain list is sorted, the cursor
  7606. will be in the first entry of the sorted region/list.")
  7607. (defun org-sort-entries
  7608. (&optional with-case sorting-type getkey-func compare-func property
  7609. interactive?)
  7610. "Sort entries on a certain level of an outline tree.
  7611. If there is an active region, the entries in the region are sorted.
  7612. Else, if the cursor is before the first entry, sort the top-level items.
  7613. Else, the children of the entry at point are sorted.
  7614. Sorting can be alphabetically, numerically, by date/time as given by
  7615. a time stamp, by a property, by priority order, or by a custom function.
  7616. The command prompts for the sorting type unless it has been given to the
  7617. function through the SORTING-TYPE argument, which needs to be a character,
  7618. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7619. the precise meaning of each character:
  7620. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7621. c By creation time, which is assumed to be the first inactive time stamp
  7622. at the beginning of a line.
  7623. d By deadline date/time.
  7624. k By clocking time.
  7625. n Numerically, by converting the beginning of the entry/item to a number.
  7626. o By order of TODO keywords.
  7627. p By priority according to the cookie.
  7628. r By the value of a property.
  7629. s By scheduled date/time.
  7630. t By date/time, either the first active time stamp in the entry, or, if
  7631. none exist, by the first inactive one.
  7632. Capital letters will reverse the sort order.
  7633. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7634. called with point at the beginning of the record. It must return a
  7635. value that is compatible with COMPARE-FUNC, the function used to
  7636. compare entries.
  7637. Comparing entries ignores case by default. However, with an optional argument
  7638. WITH-CASE, the sorting considers case as well.
  7639. Sorting is done against the visible part of the headlines, it ignores hidden
  7640. links.
  7641. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7642. A non-nil value for INTERACTIVE? is used to signal that this
  7643. function is being called interactively."
  7644. (interactive (list current-prefix-arg nil nil nil nil t))
  7645. (let ((case-func (if with-case 'identity 'downcase))
  7646. start beg end stars re re2
  7647. txt what tmp)
  7648. ;; Find beginning and end of region to sort
  7649. (cond
  7650. ((org-region-active-p)
  7651. ;; we will sort the region
  7652. (setq end (region-end)
  7653. what "region")
  7654. (goto-char (region-beginning))
  7655. (unless (org-at-heading-p) (outline-next-heading))
  7656. (setq start (point)))
  7657. ((or (org-at-heading-p)
  7658. (ignore-errors (progn (org-back-to-heading) t)))
  7659. ;; we will sort the children of the current headline
  7660. (org-back-to-heading)
  7661. (setq start (point)
  7662. end (progn (org-end-of-subtree t t)
  7663. (or (bolp) (insert "\n"))
  7664. (when (>= (org-back-over-empty-lines) 1)
  7665. (forward-line 1))
  7666. (point))
  7667. what "children")
  7668. (goto-char start)
  7669. (outline-show-subtree)
  7670. (outline-next-heading))
  7671. (t
  7672. ;; we will sort the top-level entries in this file
  7673. (goto-char (point-min))
  7674. (or (org-at-heading-p) (outline-next-heading))
  7675. (setq start (point))
  7676. (goto-char (point-max))
  7677. (beginning-of-line 1)
  7678. (when (looking-at ".*?\\S-")
  7679. ;; File ends in a non-white line
  7680. (end-of-line 1)
  7681. (insert "\n"))
  7682. (setq end (point-max))
  7683. (setq what "top-level")
  7684. (goto-char start)
  7685. (outline-show-all)))
  7686. (setq beg (point))
  7687. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7688. (looking-at "\\(\\*+\\)")
  7689. (setq stars (match-string 1)
  7690. re (concat "^" (regexp-quote stars) " +")
  7691. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7692. txt (buffer-substring beg end))
  7693. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7694. (when (and (not (equal stars "*")) (string-match re2 txt))
  7695. (user-error "Region to sort contains a level above the first entry"))
  7696. (unless sorting-type
  7697. (message
  7698. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7699. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7700. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7701. what)
  7702. (setq sorting-type (read-char-exclusive)))
  7703. (unless getkey-func
  7704. (and (= (downcase sorting-type) ?f)
  7705. (setq getkey-func
  7706. (or (and interactive?
  7707. (org-read-function
  7708. "Function for extracting keys: "))
  7709. (error "Missing key extractor")))))
  7710. (and (= (downcase sorting-type) ?r)
  7711. (not property)
  7712. (setq property
  7713. (completing-read "Property: "
  7714. (mapcar #'list (org-buffer-property-keys t))
  7715. nil t)))
  7716. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7717. (message "Sorting entries...")
  7718. (save-restriction
  7719. (narrow-to-region start end)
  7720. (let ((restore-clock?
  7721. ;; The clock marker is lost when using `sort-subr'; mark
  7722. ;; the clock with temporary `:org-clock-marker-backup'
  7723. ;; text property.
  7724. (when (and (eq (org-clock-is-active) (current-buffer))
  7725. (<= start (marker-position org-clock-marker))
  7726. (>= end (marker-position org-clock-marker)))
  7727. (org-with-silent-modifications
  7728. (put-text-property (1- org-clock-marker) org-clock-marker
  7729. :org-clock-marker-backup t))
  7730. t))
  7731. (dcst (downcase sorting-type))
  7732. (case-fold-search nil)
  7733. (now (current-time)))
  7734. (org-preserve-local-variables
  7735. (sort-subr
  7736. (/= dcst sorting-type)
  7737. ;; This function moves to the beginning character of the
  7738. ;; "record" to be sorted.
  7739. (lambda nil
  7740. (if (re-search-forward re nil t)
  7741. (goto-char (match-beginning 0))
  7742. (goto-char (point-max))))
  7743. ;; This function moves to the last character of the "record" being
  7744. ;; sorted.
  7745. (lambda nil
  7746. (save-match-data
  7747. (condition-case nil
  7748. (outline-forward-same-level 1)
  7749. (error
  7750. (goto-char (point-max))))))
  7751. ;; This function returns the value that gets sorted against.
  7752. (lambda ()
  7753. (cond
  7754. ((= dcst ?n)
  7755. (if (looking-at org-complex-heading-regexp)
  7756. (string-to-number
  7757. (org-sort-remove-invisible (match-string 4)))
  7758. nil))
  7759. ((= dcst ?a)
  7760. (if (looking-at org-complex-heading-regexp)
  7761. (funcall case-func
  7762. (org-sort-remove-invisible (match-string 4)))
  7763. nil))
  7764. ((= dcst ?k)
  7765. (or (get-text-property (point) :org-clock-minutes) 0))
  7766. ((= dcst ?t)
  7767. (let ((end (save-excursion (outline-next-heading) (point))))
  7768. (if (or (re-search-forward org-ts-regexp end t)
  7769. (re-search-forward org-ts-regexp-both end t))
  7770. (org-time-string-to-seconds (match-string 0))
  7771. (float-time now))))
  7772. ((= dcst ?c)
  7773. (let ((end (save-excursion (outline-next-heading) (point))))
  7774. (if (re-search-forward
  7775. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7776. end t)
  7777. (org-time-string-to-seconds (match-string 0))
  7778. (float-time now))))
  7779. ((= dcst ?s)
  7780. (let ((end (save-excursion (outline-next-heading) (point))))
  7781. (if (re-search-forward org-scheduled-time-regexp end t)
  7782. (org-time-string-to-seconds (match-string 1))
  7783. (float-time now))))
  7784. ((= dcst ?d)
  7785. (let ((end (save-excursion (outline-next-heading) (point))))
  7786. (if (re-search-forward org-deadline-time-regexp end t)
  7787. (org-time-string-to-seconds (match-string 1))
  7788. (float-time now))))
  7789. ((= dcst ?p)
  7790. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7791. (string-to-char (match-string 2))
  7792. org-default-priority))
  7793. ((= dcst ?r)
  7794. (or (org-entry-get nil property) ""))
  7795. ((= dcst ?o)
  7796. (when (looking-at org-complex-heading-regexp)
  7797. (let* ((m (match-string 2))
  7798. (s (if (member m org-done-keywords) '- '+)))
  7799. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7800. ((= dcst ?f)
  7801. (if getkey-func
  7802. (progn
  7803. (setq tmp (funcall getkey-func))
  7804. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7805. tmp)
  7806. (error "Invalid key function `%s'" getkey-func)))
  7807. (t (error "Invalid sorting type `%c'" sorting-type))))
  7808. nil
  7809. (cond
  7810. ((= dcst ?a) 'string<)
  7811. ((= dcst ?f)
  7812. (or compare-func
  7813. (and interactive?
  7814. (org-read-function
  7815. (concat "Function for comparing keys "
  7816. "(empty for default `sort-subr' predicate): ")
  7817. 'allow-empty))))
  7818. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7819. (when restore-clock?
  7820. (move-marker org-clock-marker
  7821. (1+ (next-single-property-change
  7822. start :org-clock-marker-backup)))
  7823. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7824. '(:org-clock-marker-backup t)))))
  7825. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7826. (message "Sorting entries...done")))
  7827. ;;; The orgstruct minor mode
  7828. ;; Define a minor mode which can be used in other modes in order to
  7829. ;; integrate the Org mode structure editing commands.
  7830. ;; This is really a hack, because the Org mode structure commands use
  7831. ;; keys which normally belong to the major mode. Here is how it
  7832. ;; works: The minor mode defines all the keys necessary to operate the
  7833. ;; structure commands, but wraps the commands into a function which
  7834. ;; tests if the cursor is currently at a headline or a plain list
  7835. ;; item. If that is the case, the structure command is used,
  7836. ;; temporarily setting many Org mode variables like regular
  7837. ;; expressions for filling etc. However, when any of those keys is
  7838. ;; used at a different location, function uses `key-binding' to look
  7839. ;; up if the key has an associated command in another currently active
  7840. ;; keymap (minor modes, major mode, global), and executes that
  7841. ;; command. There might be problems if any of the keys is otherwise
  7842. ;; used as a prefix key.
  7843. (defcustom orgstruct-heading-prefix-regexp ""
  7844. "Regexp that matches the custom prefix of Org headlines in
  7845. orgstruct(++)-mode."
  7846. :group 'org
  7847. :version "26.1"
  7848. :package-version '(Org . "8.3")
  7849. :type 'regexp)
  7850. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  7851. (defcustom orgstruct-setup-hook nil
  7852. "Hook run after orgstruct-mode-map is filled."
  7853. :group 'org
  7854. :version "24.4"
  7855. :package-version '(Org . "8.0")
  7856. :type 'hook)
  7857. (defvar orgstruct-initialized nil)
  7858. (defvar org-local-vars nil
  7859. "List of local variables, for use by `orgstruct-mode'.")
  7860. ;;;###autoload
  7861. (define-minor-mode orgstruct-mode
  7862. "Toggle the minor mode `orgstruct-mode'.
  7863. This mode is for using Org mode structure commands in other
  7864. modes. The following keys behave as if Org mode were active, if
  7865. the cursor is on a headline, or on a plain list item (both as
  7866. defined by Org mode)."
  7867. nil " OrgStruct" (make-sparse-keymap)
  7868. (funcall (if orgstruct-mode
  7869. 'add-to-invisibility-spec
  7870. 'remove-from-invisibility-spec)
  7871. '(outline . t))
  7872. (when orgstruct-mode
  7873. (org-load-modules-maybe)
  7874. (unless orgstruct-initialized
  7875. (orgstruct-setup)
  7876. (setq orgstruct-initialized t))))
  7877. ;;;###autoload
  7878. (defun turn-on-orgstruct ()
  7879. "Unconditionally turn on `orgstruct-mode'."
  7880. (orgstruct-mode 1))
  7881. (defvar-local orgstruct-is-++ nil
  7882. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  7883. (defvar-local org-fb-vars nil)
  7884. (defun orgstruct++-mode (&optional arg)
  7885. "Toggle `orgstruct-mode', the enhanced version of it.
  7886. In addition to setting orgstruct-mode, this also exports all
  7887. indentation and autofilling variables from Org mode into the
  7888. buffer. It will also recognize item context in multiline items."
  7889. (interactive "P")
  7890. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  7891. (if (< arg 1)
  7892. (progn (orgstruct-mode -1)
  7893. (dolist (v org-fb-vars)
  7894. (set (make-local-variable (car v))
  7895. (if (eq (car-safe (cadr v)) 'quote)
  7896. (cl-cadadr v)
  7897. (nth 1 v)))))
  7898. (orgstruct-mode 1)
  7899. (setq org-fb-vars nil)
  7900. (unless org-local-vars
  7901. (setq org-local-vars (org-get-local-variables)))
  7902. (let (var val)
  7903. (dolist (x org-local-vars)
  7904. (when (string-match
  7905. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  7906. \\|fill-prefix\\|indent-\\)"
  7907. (symbol-name (car x)))
  7908. (setq var (car x) val (nth 1 x))
  7909. (push (list var `(quote ,(eval var))) org-fb-vars)
  7910. (set (make-local-variable var)
  7911. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  7912. (setq-local orgstruct-is-++ t))))
  7913. ;;;###autoload
  7914. (defun turn-on-orgstruct++ ()
  7915. "Unconditionally turn on `orgstruct++-mode'."
  7916. (orgstruct++-mode 1))
  7917. (defun orgstruct-error ()
  7918. "Error when there is no default binding for a structure key."
  7919. (interactive)
  7920. (funcall (if (fboundp 'user-error)
  7921. 'user-error
  7922. 'error)
  7923. "This key has no function outside structure elements"))
  7924. (defun orgstruct-setup ()
  7925. "Setup orgstruct keymap."
  7926. (dolist (cell '((org-demote . t)
  7927. (org-metaleft . t)
  7928. (org-metaright . t)
  7929. (org-promote . t)
  7930. (org-shiftmetaleft . t)
  7931. (org-shiftmetaright . t)
  7932. org-backward-element
  7933. org-backward-heading-same-level
  7934. org-ctrl-c-ret
  7935. org-ctrl-c-minus
  7936. org-ctrl-c-star
  7937. org-cycle
  7938. org-force-cycle-archived
  7939. org-forward-heading-same-level
  7940. org-insert-heading
  7941. org-insert-heading-respect-content
  7942. org-kill-note-or-show-branches
  7943. org-mark-subtree
  7944. org-meta-return
  7945. org-metadown
  7946. org-metaup
  7947. org-narrow-to-subtree
  7948. org-promote-subtree
  7949. org-reveal
  7950. org-shiftdown
  7951. org-shiftleft
  7952. org-shiftmetadown
  7953. org-shiftmetaup
  7954. org-shiftright
  7955. org-shifttab
  7956. org-shifttab
  7957. org-shiftup
  7958. org-show-children
  7959. org-show-subtree
  7960. org-sort
  7961. org-up-element
  7962. outline-demote
  7963. outline-next-visible-heading
  7964. outline-previous-visible-heading
  7965. outline-promote
  7966. outline-up-heading))
  7967. (let ((f (or (car-safe cell) cell))
  7968. (disable-when-heading-prefix (cdr-safe cell)))
  7969. (when (fboundp f)
  7970. (let ((new-bindings))
  7971. (dolist (binding (nconc (where-is-internal f org-mode-map)
  7972. (where-is-internal f outline-mode-map)))
  7973. (push binding new-bindings)
  7974. ;; TODO use local-function-key-map
  7975. (dolist (rep '(("<tab>" . "TAB")
  7976. ("<return>" . "RET")
  7977. ("<escape>" . "ESC")
  7978. ("<delete>" . "DEL")))
  7979. (setq binding (read-kbd-macro
  7980. (let ((case-fold-search))
  7981. (replace-regexp-in-string
  7982. (regexp-quote (cdr rep))
  7983. (car rep)
  7984. (key-description binding)))))
  7985. (cl-pushnew binding new-bindings :test 'equal)))
  7986. (dolist (binding new-bindings)
  7987. (let ((key (lookup-key orgstruct-mode-map binding)))
  7988. (when (or (not key) (numberp key))
  7989. (ignore-errors
  7990. (org-defkey orgstruct-mode-map
  7991. binding
  7992. (orgstruct-make-binding
  7993. f binding disable-when-heading-prefix))))))))))
  7994. (run-hooks 'orgstruct-setup-hook))
  7995. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  7996. "Create a function for binding in the structure minor mode.
  7997. FUN is the command to call inside a table. KEY is the key that
  7998. should be checked in for a command to execute outside of tables.
  7999. Non-nil `disable-when-heading-prefix' means to disable the command
  8000. if `orgstruct-heading-prefix-regexp' is not empty."
  8001. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8002. (let ((nname name)
  8003. (i 0))
  8004. (while (fboundp (intern nname))
  8005. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8006. (setq name (intern nname)))
  8007. (eval
  8008. (let ((bindings '((org-heading-regexp
  8009. (concat "^"
  8010. orgstruct-heading-prefix-regexp
  8011. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8012. (org-outline-regexp
  8013. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8014. (org-outline-regexp-bol
  8015. (concat "^" org-outline-regexp))
  8016. (outline-regexp org-outline-regexp)
  8017. (outline-heading-end-regexp "\n")
  8018. (outline-level 'org-outline-level)
  8019. (outline-heading-alist))))
  8020. `(defun ,name (arg)
  8021. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8022. "Outside of structure, run the binding of `"
  8023. (key-description key) "'."
  8024. (when disable-when-heading-prefix
  8025. (concat
  8026. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8027. "back to the default binding due to limitations of Org's implementation of\n"
  8028. "`" (symbol-name fun) "'.")))
  8029. (interactive "p")
  8030. (let* ((disable
  8031. ,(and disable-when-heading-prefix
  8032. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8033. (fallback
  8034. (or disable
  8035. (not
  8036. (let* ,bindings
  8037. (org-context-p 'headline 'item
  8038. ,(when (memq fun
  8039. '(org-insert-heading
  8040. org-insert-heading-respect-content
  8041. org-meta-return))
  8042. '(when orgstruct-is-++
  8043. 'item-body))))))))
  8044. (if fallback
  8045. (let* ((orgstruct-mode)
  8046. (binding
  8047. (let ((key ,key))
  8048. (catch 'exit
  8049. (dolist
  8050. (rep
  8051. '(nil
  8052. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8053. ("<\\([^>]*\\)return>" . "\\1RET")
  8054. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8055. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8056. nil)
  8057. (when rep
  8058. (setq key (read-kbd-macro
  8059. (let ((case-fold-search))
  8060. (replace-regexp-in-string
  8061. (car rep)
  8062. (cdr rep)
  8063. (key-description key))))))
  8064. (when (key-binding key)
  8065. (throw 'exit (key-binding key))))))))
  8066. (if (keymapp binding)
  8067. (org-set-transient-map binding)
  8068. (let ((func (or binding
  8069. (unless disable
  8070. 'orgstruct-error))))
  8071. (when func
  8072. (call-interactively func)))))
  8073. (org-run-like-in-org-mode
  8074. (lambda ()
  8075. (interactive)
  8076. (let* ,bindings
  8077. (call-interactively ',fun)))))))))
  8078. name))
  8079. (defun org-contextualize-keys (alist contexts)
  8080. "Return valid elements in ALIST depending on CONTEXTS.
  8081. `org-agenda-custom-commands' or `org-capture-templates' are the
  8082. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8083. or `org-capture-templates-contexts' are the associated contexts
  8084. definitions."
  8085. (let ((contexts
  8086. ;; normalize contexts
  8087. (mapcar
  8088. (lambda(c) (cond ((listp (cadr c))
  8089. (list (car c) (car c) (nth 1 c)))
  8090. ((string= "" (cadr c))
  8091. (list (car c) (car c) (nth 2 c)))
  8092. (t c)))
  8093. contexts))
  8094. (a alist) r s)
  8095. ;; loop over all commands or templates
  8096. (dolist (c a)
  8097. (let (vrules repl)
  8098. (cond
  8099. ((not (assoc (car c) contexts))
  8100. (push c r))
  8101. ((and (assoc (car c) contexts)
  8102. (setq vrules (org-contextualize-validate-key
  8103. (car c) contexts)))
  8104. (mapc (lambda (vr)
  8105. (unless (equal (car vr) (cadr vr))
  8106. (setq repl vr)))
  8107. vrules)
  8108. (if (not repl) (push c r)
  8109. (push (cadr repl) s)
  8110. (push
  8111. (cons (car c)
  8112. (cdr (or (assoc (cadr repl) alist)
  8113. (error "Undefined key `%s' as contextual replacement for `%s'"
  8114. (cadr repl) (car c)))))
  8115. r))))))
  8116. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8117. (delq
  8118. nil
  8119. (delete-dups
  8120. (mapcar (lambda (x)
  8121. (let ((tpl (car x)))
  8122. (unless (delq
  8123. nil
  8124. (mapcar (lambda (y)
  8125. (equal y tpl))
  8126. s))
  8127. x)))
  8128. (reverse r))))))
  8129. (defun org-contextualize-validate-key (key contexts)
  8130. "Check CONTEXTS for agenda or capture KEY."
  8131. (let (res)
  8132. (dolist (r contexts)
  8133. (dolist (rr (car (last r)))
  8134. (when
  8135. (and (equal key (car r))
  8136. (if (functionp rr) (funcall rr)
  8137. (or (and (eq (car rr) 'in-file)
  8138. (buffer-file-name)
  8139. (string-match (cdr rr) (buffer-file-name)))
  8140. (and (eq (car rr) 'in-mode)
  8141. (string-match (cdr rr) (symbol-name major-mode)))
  8142. (and (eq (car rr) 'in-buffer)
  8143. (string-match (cdr rr) (buffer-name)))
  8144. (when (and (eq (car rr) 'not-in-file)
  8145. (buffer-file-name))
  8146. (not (string-match (cdr rr) (buffer-file-name))))
  8147. (when (eq (car rr) 'not-in-mode)
  8148. (not (string-match (cdr rr) (symbol-name major-mode))))
  8149. (when (eq (car rr) 'not-in-buffer)
  8150. (not (string-match (cdr rr) (buffer-name)))))))
  8151. (push r res))))
  8152. (delete-dups (delq nil res))))
  8153. (defun org-context-p (&rest contexts)
  8154. "Check if local context is any of CONTEXTS.
  8155. Possible values in the list of contexts are `table', `headline', and `item'."
  8156. (let ((pos (point)))
  8157. (goto-char (point-at-bol))
  8158. (prog1 (or (and (memq 'table contexts)
  8159. (looking-at "[ \t]*|"))
  8160. (and (memq 'headline contexts)
  8161. (looking-at org-outline-regexp))
  8162. (and (memq 'item contexts)
  8163. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8164. (and (memq 'item-body contexts)
  8165. (org-in-item-p)))
  8166. (goto-char pos))))
  8167. ;;;###autoload
  8168. (defun org-run-like-in-org-mode (cmd)
  8169. "Run a command, pretending that the current buffer is in Org mode.
  8170. This will temporarily bind local variables that are typically bound in
  8171. Org mode to the values they have in Org mode, and then interactively
  8172. call CMD."
  8173. (org-load-modules-maybe)
  8174. (unless org-local-vars
  8175. (setq org-local-vars (org-get-local-variables)))
  8176. (let (binds)
  8177. (dolist (var org-local-vars)
  8178. (when (or (not (boundp (car var)))
  8179. (eq (symbol-value (car var))
  8180. (default-value (car var))))
  8181. (push (list (car var) `(quote ,(cadr var))) binds)))
  8182. (eval `(let ,binds
  8183. (call-interactively (quote ,cmd))))))
  8184. (defun org-get-category (&optional pos force-refresh)
  8185. "Get the category applying to position POS."
  8186. (save-match-data
  8187. (when force-refresh (org-refresh-category-properties))
  8188. (let ((pos (or pos (point))))
  8189. (or (get-text-property pos 'org-category)
  8190. (progn (org-refresh-category-properties)
  8191. (get-text-property pos 'org-category))))))
  8192. ;;; Refresh properties
  8193. (defun org-refresh-properties (dprop tprop)
  8194. "Refresh buffer text properties.
  8195. DPROP is the drawer property and TPROP is either the
  8196. corresponding text property to set, or an alist with each element
  8197. being a text property (as a symbol) and a function to apply to
  8198. the value of the drawer property."
  8199. (let* ((case-fold-search t)
  8200. (inhibit-read-only t)
  8201. (inherit? (org-property-inherit-p dprop))
  8202. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8203. (global (and inherit? (org--property-global-value dprop nil))))
  8204. (org-with-silent-modifications
  8205. (org-with-point-at 1
  8206. ;; Set global values (e.g., values defined through
  8207. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8208. (when global (put-text-property (point-min) (point-max) tprop global))
  8209. ;; Set local values.
  8210. (while (re-search-forward property-re nil t)
  8211. (when (org-at-property-p)
  8212. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8213. (outline-next-heading))))))
  8214. (defun org-refresh-property (tprop p &optional inherit)
  8215. "Refresh the buffer text property TPROP from the drawer property P.
  8216. The refresh happens only for the current headline, or the whole
  8217. sub-tree if optional argument INHERIT is non-nil."
  8218. (unless (org-before-first-heading-p)
  8219. (save-excursion
  8220. (org-back-to-heading t)
  8221. (let ((start (point))
  8222. (end (save-excursion
  8223. (if inherit (org-end-of-subtree t t)
  8224. (or (outline-next-heading) (point-max))))))
  8225. (if (symbolp tprop)
  8226. ;; TPROP is a text property symbol.
  8227. (put-text-property start end tprop p)
  8228. ;; TPROP is an alist with (property . function) elements.
  8229. (pcase-dolist (`(,prop . ,f) tprop)
  8230. (put-text-property start end prop (funcall f p))))))))
  8231. (defun org-refresh-category-properties ()
  8232. "Refresh category text properties in the buffer."
  8233. (let ((case-fold-search t)
  8234. (inhibit-read-only t)
  8235. (default-category
  8236. (cond ((null org-category)
  8237. (if buffer-file-name
  8238. (file-name-sans-extension
  8239. (file-name-nondirectory buffer-file-name))
  8240. "???"))
  8241. ((symbolp org-category) (symbol-name org-category))
  8242. (t org-category))))
  8243. (org-with-silent-modifications
  8244. (org-with-wide-buffer
  8245. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8246. ;; This is the default category for the buffer. If none is
  8247. ;; found, fall-back to `org-category' or buffer file name.
  8248. (put-text-property
  8249. (point-min) (point-max)
  8250. 'org-category
  8251. (catch 'buffer-category
  8252. (goto-char (point-max))
  8253. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8254. (let ((element (org-element-at-point)))
  8255. (when (eq (org-element-type element) 'keyword)
  8256. (throw 'buffer-category
  8257. (org-element-property :value element)))))
  8258. default-category))
  8259. ;; Set sub-tree specific categories.
  8260. (goto-char (point-min))
  8261. (let ((regexp (org-re-property "CATEGORY")))
  8262. (while (re-search-forward regexp nil t)
  8263. (let ((value (match-string-no-properties 3)))
  8264. (when (org-at-property-p)
  8265. (put-text-property
  8266. (save-excursion (org-back-to-heading t) (point))
  8267. (save-excursion (org-end-of-subtree t t) (point))
  8268. 'org-category
  8269. value)))))))))
  8270. (defun org-refresh-stats-properties ()
  8271. "Refresh stats text properties in the buffer."
  8272. (org-with-silent-modifications
  8273. (org-with-point-at 1
  8274. (let ((regexp (concat org-outline-regexp-bol
  8275. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8276. (while (re-search-forward regexp nil t)
  8277. (let* ((numerator (string-to-number (match-string 1)))
  8278. (denominator (and (match-end 2)
  8279. (string-to-number (match-string 2))))
  8280. (stats (cond ((not denominator) numerator) ;percent
  8281. ((= denominator 0) 0)
  8282. (t (/ (* numerator 100) denominator)))))
  8283. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8284. 'org-stats stats)))))))
  8285. (defun org-refresh-effort-properties ()
  8286. "Refresh effort properties"
  8287. (org-refresh-properties
  8288. org-effort-property
  8289. '((effort . identity)
  8290. (effort-minutes . org-duration-to-minutes))))
  8291. ;;;; Link Stuff
  8292. ;;; Link abbreviations
  8293. (defun org-link-expand-abbrev (link)
  8294. "Apply replacements as defined in `org-link-abbrev-alist'."
  8295. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8296. (let* ((key (match-string 1 link))
  8297. (as (or (assoc key org-link-abbrev-alist-local)
  8298. (assoc key org-link-abbrev-alist)))
  8299. (tag (and (match-end 2) (match-string 3 link)))
  8300. rpl)
  8301. (if (not as)
  8302. link
  8303. (setq rpl (cdr as))
  8304. (cond
  8305. ((symbolp rpl) (funcall rpl tag))
  8306. ((string-match "%(\\([^)]+\\))" rpl)
  8307. (replace-match
  8308. (save-match-data
  8309. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8310. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8311. ((string-match "%h" rpl)
  8312. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8313. (t (concat rpl tag)))))
  8314. link))
  8315. ;;; Storing and inserting links
  8316. (defvar org-insert-link-history nil
  8317. "Minibuffer history for links inserted with `org-insert-link'.")
  8318. (defvar org-stored-links nil
  8319. "Contains the links stored with `org-store-link'.")
  8320. (defvar org-store-link-plist nil
  8321. "Plist with info about the most recently link created with `org-store-link'.")
  8322. (defun org-store-link-functions ()
  8323. "Return a list of functions that are called to create and store a link.
  8324. The functions defined in the :store property of
  8325. `org-link-parameters'.
  8326. Each function will be called in turn until one returns a non-nil
  8327. value. Each function should check if it is responsible for
  8328. creating this link (for example by looking at the major mode).
  8329. If not, it must exit and return nil. If yes, it should return
  8330. a non-nil value after calling `org-store-link-props' with a list
  8331. of properties and values. Special properties are:
  8332. :type The link prefix, like \"http\". This must be given.
  8333. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8334. This is obligatory as well.
  8335. :description Optional default description for the second pair
  8336. of brackets in an Org mode link. The user can still change
  8337. this when inserting this link into an Org mode buffer.
  8338. In addition to these, any additional properties can be specified
  8339. and then used in capture templates."
  8340. (cl-loop for link in org-link-parameters
  8341. with store-func
  8342. do (setq store-func (org-link-get-parameter (car link) :store))
  8343. if store-func
  8344. collect store-func))
  8345. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8346. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8347. ;;;###autoload
  8348. (defun org-store-link (arg)
  8349. "Store an org-link to the current location.
  8350. \\<org-mode-map>
  8351. This link is added to `org-stored-links' and can later be inserted
  8352. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8353. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8354. A single
  8355. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8356. `org-gnus-prefer-web-links' for links to Usenet articles.
  8357. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8358. skipping storing functions that are not
  8359. part of Org core.
  8360. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8361. prefix ARG forces storing a link for each line in the
  8362. active region."
  8363. (interactive "P")
  8364. (org-load-modules-maybe)
  8365. (if (and (equal arg '(64)) (org-region-active-p))
  8366. (save-excursion
  8367. (let ((end (region-end)))
  8368. (goto-char (region-beginning))
  8369. (set-mark (point))
  8370. (while (< (point-at-eol) end)
  8371. (move-end-of-line 1) (activate-mark)
  8372. (let (current-prefix-arg)
  8373. (call-interactively 'org-store-link))
  8374. (move-beginning-of-line 2)
  8375. (set-mark (point)))))
  8376. (setq org-store-link-plist nil)
  8377. (let (link cpltxt desc description search txt custom-id agenda-link)
  8378. (cond
  8379. ;; Store a link using an external link type, if any function is
  8380. ;; available. If more than one can generate a link from current
  8381. ;; location, ask which one to use.
  8382. ((and (not (equal arg '(16)))
  8383. (let ((results-alist nil))
  8384. (dolist (f (org-store-link-functions))
  8385. (when (funcall f)
  8386. ;; XXX: return value is not link's plist, so we
  8387. ;; store the new value before it is modified. It
  8388. ;; would be cleaner to ask store link functions to
  8389. ;; return the plist instead.
  8390. (push (cons f (copy-sequence org-store-link-plist))
  8391. results-alist)))
  8392. (pcase results-alist
  8393. (`nil nil)
  8394. (`((,_ . ,_)) t) ;single choice: nothing to do
  8395. (`((,name . ,_) . ,_)
  8396. ;; Reinstate link plist associated to the chosen
  8397. ;; function.
  8398. (apply #'org-store-link-props
  8399. (cdr (assoc-string
  8400. (completing-read
  8401. "Which function for creating the link? "
  8402. (mapcar #'car results-alist) nil t name)
  8403. results-alist)))
  8404. t))))
  8405. (setq link (plist-get org-store-link-plist :link))
  8406. (setq desc (or (plist-get org-store-link-plist :description)
  8407. link)))
  8408. ;; Store a link from a source code buffer.
  8409. ((org-src-edit-buffer-p)
  8410. (let ((coderef-format (org-src-coderef-format)))
  8411. (cond ((save-excursion
  8412. (beginning-of-line)
  8413. (looking-at (org-src-coderef-regexp coderef-format)))
  8414. (setq link (format "(%s)" (match-string-no-properties 3))))
  8415. ((called-interactively-p 'any)
  8416. (let ((label (read-string "Code line label: ")))
  8417. (end-of-line)
  8418. (setq link (format coderef-format label))
  8419. (let ((gc (- 79 (length link))))
  8420. (if (< (current-column) gc)
  8421. (org-move-to-column gc t)
  8422. (insert " ")))
  8423. (insert link)
  8424. (setq link (concat "(" label ")"))
  8425. (setq desc nil)))
  8426. (t (setq link nil)))))
  8427. ;; We are in the agenda, link to referenced location
  8428. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8429. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8430. (get-text-property (point) 'org-marker))))
  8431. (when m
  8432. (org-with-point-at m
  8433. (setq agenda-link
  8434. (if (called-interactively-p 'any)
  8435. (call-interactively 'org-store-link)
  8436. (org-store-link nil)))))))
  8437. ((eq major-mode 'calendar-mode)
  8438. (let ((cd (calendar-cursor-to-date)))
  8439. (setq link
  8440. (format-time-string
  8441. (car org-time-stamp-formats)
  8442. (apply 'encode-time
  8443. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8444. nil nil nil))))
  8445. (org-store-link-props :type "calendar" :date cd)))
  8446. ((eq major-mode 'help-mode)
  8447. (setq link (concat "help:" (save-excursion
  8448. (goto-char (point-min))
  8449. (looking-at "^[^ ]+")
  8450. (match-string 0))))
  8451. (org-store-link-props :type "help"))
  8452. ((eq major-mode 'w3-mode)
  8453. (setq cpltxt (if (and (buffer-name)
  8454. (not (string-match "Untitled" (buffer-name))))
  8455. (buffer-name)
  8456. (url-view-url t))
  8457. link (url-view-url t))
  8458. (org-store-link-props :type "w3" :url (url-view-url t)))
  8459. ((eq major-mode 'image-mode)
  8460. (setq cpltxt (concat "file:"
  8461. (abbreviate-file-name buffer-file-name))
  8462. link cpltxt)
  8463. (org-store-link-props :type "image" :file buffer-file-name))
  8464. ;; In dired, store a link to the file of the current line
  8465. ((derived-mode-p 'dired-mode)
  8466. (let ((file (dired-get-filename nil t)))
  8467. (setq file (if file
  8468. (abbreviate-file-name
  8469. (expand-file-name (dired-get-filename nil t)))
  8470. ;; otherwise, no file so use current directory.
  8471. default-directory))
  8472. (setq cpltxt (concat "file:" file)
  8473. link cpltxt)))
  8474. ((setq search (run-hook-with-args-until-success
  8475. 'org-create-file-search-functions))
  8476. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8477. "::" search))
  8478. (setq cpltxt (or description link)))
  8479. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8480. (org-with-limited-levels
  8481. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8482. (cond
  8483. ;; Store a link using the target at point
  8484. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8485. (setq cpltxt
  8486. (concat "file:"
  8487. (abbreviate-file-name
  8488. (buffer-file-name (buffer-base-buffer)))
  8489. "::" (match-string 1))
  8490. link cpltxt))
  8491. ((and (featurep 'org-id)
  8492. (or (eq org-id-link-to-org-use-id t)
  8493. (and (called-interactively-p 'any)
  8494. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8495. (and (eq org-id-link-to-org-use-id
  8496. 'create-if-interactive-and-no-custom-id)
  8497. (not custom-id))))
  8498. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8499. ;; Store a link using the ID at point
  8500. (setq link (condition-case nil
  8501. (prog1 (org-id-store-link)
  8502. (setq desc (or (plist-get org-store-link-plist
  8503. :description)
  8504. "")))
  8505. (error
  8506. ;; Probably before first headline, link only to file
  8507. (concat "file:"
  8508. (abbreviate-file-name
  8509. (buffer-file-name (buffer-base-buffer))))))))
  8510. (t
  8511. ;; Just link to current headline
  8512. (setq cpltxt (concat "file:"
  8513. (abbreviate-file-name
  8514. (buffer-file-name (buffer-base-buffer)))))
  8515. ;; Add a context search string
  8516. (when (org-xor org-context-in-file-links
  8517. (equal arg '(4)))
  8518. (let* ((element (org-element-at-point))
  8519. (name (org-element-property :name element)))
  8520. (setq txt (cond
  8521. ((org-at-heading-p) nil)
  8522. (name)
  8523. ((org-region-active-p)
  8524. (buffer-substring (region-beginning) (region-end)))))
  8525. (when (or (null txt) (string-match "\\S-" txt))
  8526. (setq cpltxt
  8527. (concat cpltxt "::"
  8528. (condition-case nil
  8529. (org-make-org-heading-search-string txt)
  8530. (error "")))
  8531. desc (or name
  8532. (nth 4 (ignore-errors (org-heading-components)))
  8533. "NONE")))))
  8534. (when (string-match "::\\'" cpltxt)
  8535. (setq cpltxt (substring cpltxt 0 -2)))
  8536. (setq link cpltxt)))))
  8537. ((buffer-file-name (buffer-base-buffer))
  8538. ;; Just link to this file here.
  8539. (setq cpltxt (concat "file:"
  8540. (abbreviate-file-name
  8541. (buffer-file-name (buffer-base-buffer)))))
  8542. ;; Add a context string.
  8543. (when (org-xor org-context-in-file-links
  8544. (equal arg '(4)))
  8545. (setq txt (if (org-region-active-p)
  8546. (buffer-substring (region-beginning) (region-end))
  8547. (buffer-substring (point-at-bol) (point-at-eol))))
  8548. ;; Only use search option if there is some text.
  8549. (when (string-match "\\S-" txt)
  8550. (setq cpltxt
  8551. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8552. desc "NONE")))
  8553. (setq link cpltxt))
  8554. ((called-interactively-p 'interactive)
  8555. (user-error "No method for storing a link from this buffer"))
  8556. (t (setq link nil)))
  8557. ;; We're done setting link and desc, clean up
  8558. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8559. (setq link (or link cpltxt)
  8560. desc (or desc cpltxt))
  8561. (cond ((not desc))
  8562. ((equal desc "NONE") (setq desc nil))
  8563. (t (setq desc
  8564. (replace-regexp-in-string
  8565. org-bracket-link-analytic-regexp
  8566. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8567. desc))))
  8568. ;; Return the link
  8569. (if (not (and (or (called-interactively-p 'any)
  8570. executing-kbd-macro)
  8571. link))
  8572. (or agenda-link (and link (org-make-link-string link desc)))
  8573. (push (list link desc) org-stored-links)
  8574. (message "Stored: %s" (or desc link))
  8575. (when custom-id
  8576. (setq link (concat "file:" (abbreviate-file-name
  8577. (buffer-file-name)) "::#" custom-id))
  8578. (push (list link desc) org-stored-links))
  8579. (car org-stored-links)))))
  8580. (defun org-store-link-props (&rest plist)
  8581. "Store link properties.
  8582. The properties are pre-processed by extracting names, addresses
  8583. and dates."
  8584. (let ((x (plist-get plist :from)))
  8585. (when x
  8586. (let ((adr (mail-extract-address-components x)))
  8587. (setq plist (plist-put plist :fromname (car adr)))
  8588. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8589. (let ((x (plist-get plist :to)))
  8590. (when x
  8591. (let ((adr (mail-extract-address-components x)))
  8592. (setq plist (plist-put plist :toname (car adr)))
  8593. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8594. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8595. (when x
  8596. (setq plist (plist-put plist :date-timestamp
  8597. (format-time-string
  8598. (org-time-stamp-format t) x)))
  8599. (setq plist (plist-put plist :date-timestamp-inactive
  8600. (format-time-string
  8601. (org-time-stamp-format t t) x)))))
  8602. (let ((from (plist-get plist :from))
  8603. (to (plist-get plist :to)))
  8604. (when (and from to org-from-is-user-regexp)
  8605. (setq plist
  8606. (plist-put plist :fromto
  8607. (if (string-match org-from-is-user-regexp from)
  8608. (concat "to %t")
  8609. (concat "from %f"))))))
  8610. (setq org-store-link-plist plist))
  8611. (defun org-add-link-props (&rest plist)
  8612. "Add these properties to the link property list."
  8613. (let (key value)
  8614. (while plist
  8615. (setq key (pop plist) value (pop plist))
  8616. (setq org-store-link-plist
  8617. (plist-put org-store-link-plist key value)))))
  8618. (defun org-email-link-description (&optional fmt)
  8619. "Return the description part of an email link.
  8620. This takes information from `org-store-link-plist' and formats it
  8621. according to FMT (default from `org-email-link-description-format')."
  8622. (setq fmt (or fmt org-email-link-description-format))
  8623. (let* ((p org-store-link-plist)
  8624. (to (plist-get p :toaddress))
  8625. (from (plist-get p :fromaddress))
  8626. (table
  8627. (list
  8628. (cons "%c" (plist-get p :fromto))
  8629. (cons "%F" (plist-get p :from))
  8630. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8631. (cons "%T" (plist-get p :to))
  8632. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8633. (cons "%s" (plist-get p :subject))
  8634. (cons "%d" (plist-get p :date))
  8635. (cons "%m" (plist-get p :message-id)))))
  8636. (when (string-match "%c" fmt)
  8637. ;; Check if the user wrote this message
  8638. (if (and org-from-is-user-regexp from to
  8639. (save-match-data (string-match org-from-is-user-regexp from)))
  8640. (setq fmt (replace-match "to %t" t t fmt))
  8641. (setq fmt (replace-match "from %f" t t fmt))))
  8642. (org-replace-escapes fmt table)))
  8643. (defun org-make-org-heading-search-string (&optional string)
  8644. "Make search string for the current headline or STRING."
  8645. (let ((s (or string
  8646. (and (derived-mode-p 'org-mode)
  8647. (save-excursion
  8648. (org-back-to-heading t)
  8649. (org-element-property :raw-value (org-element-at-point))))))
  8650. (lines org-context-in-file-links))
  8651. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8652. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8653. (when (and string (integerp lines) (> lines 0))
  8654. (let ((slines (org-split-string s "\n")))
  8655. (when (< lines (length slines))
  8656. (setq s (mapconcat
  8657. 'identity
  8658. (reverse (nthcdr (- (length slines) lines)
  8659. (reverse slines))) "\n")))))
  8660. (mapconcat #'identity (split-string s) " ")))
  8661. (defconst org-link-escape-chars
  8662. ;;%20 %5B %5D %25
  8663. '(?\s ?\[ ?\] ?%)
  8664. "List of characters that should be escaped in a link when stored to Org.
  8665. This is the list that is used for internal purposes.")
  8666. (defun org-make-link-string (link &optional description)
  8667. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8668. (unless (org-string-nw-p link) (error "Empty link"))
  8669. (let ((uri (cond ((string-match org-link-types-re link)
  8670. (concat (match-string 1 link)
  8671. (org-link-escape (substring link (match-end 1)))))
  8672. ((or (file-name-absolute-p link)
  8673. (string-match-p "\\`\\.\\.?/" link))
  8674. (org-link-escape link))
  8675. ;; For readability, do not encode space characters
  8676. ;; in fuzzy links.
  8677. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8678. (description
  8679. (and (org-string-nw-p description)
  8680. ;; Remove brackets from description, as they are fatal.
  8681. (replace-regexp-in-string
  8682. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8683. (org-trim description)))))
  8684. (format "[[%s]%s]"
  8685. uri
  8686. (if description (format "[%s]" description) ""))))
  8687. (defun org-link-escape (text &optional table merge)
  8688. "Return percent escaped representation of TEXT.
  8689. TEXT is a string with the text to escape.
  8690. Optional argument TABLE is a list with characters that should be
  8691. escaped. When nil, `org-link-escape-chars' is used.
  8692. If optional argument MERGE is set, merge TABLE into
  8693. `org-link-escape-chars'."
  8694. (let ((characters-to-encode
  8695. (cond ((null table) org-link-escape-chars)
  8696. (merge (append org-link-escape-chars table))
  8697. (t table))))
  8698. (mapconcat
  8699. (lambda (c)
  8700. (if (or (memq c characters-to-encode)
  8701. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8702. (mapconcat (lambda (e) (format "%%%.2X" e))
  8703. (or (encode-coding-char c 'utf-8)
  8704. (error "Unable to percent escape character: %c" c))
  8705. "")
  8706. (char-to-string c)))
  8707. text "")))
  8708. (defun org-link-unescape (str)
  8709. "Unhex hexified Unicode parts in string STR.
  8710. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8711. reciprocal of `org-link-escape', which see."
  8712. (if (org-string-nw-p str)
  8713. (replace-regexp-in-string
  8714. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8715. str))
  8716. (defun org-link-unescape-compound (hex)
  8717. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8718. Note: this function also decodes single byte encodings like
  8719. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8720. (save-match-data
  8721. (let* ((bytes (cdr (split-string hex "%")))
  8722. (ret "")
  8723. (eat 0)
  8724. (sum 0))
  8725. (while bytes
  8726. (let* ((val (string-to-number (pop bytes) 16))
  8727. (shift-xor
  8728. (if (= 0 eat)
  8729. (cond
  8730. ((>= val 252) (cons 6 252))
  8731. ((>= val 248) (cons 5 248))
  8732. ((>= val 240) (cons 4 240))
  8733. ((>= val 224) (cons 3 224))
  8734. ((>= val 192) (cons 2 192))
  8735. (t (cons 0 0)))
  8736. (cons 6 128))))
  8737. (when (>= val 192) (setq eat (car shift-xor)))
  8738. (setq val (logxor val (cdr shift-xor)))
  8739. (setq sum (+ (lsh sum (car shift-xor)) val))
  8740. (when (> eat 0) (setq eat (- eat 1)))
  8741. (cond
  8742. ((= 0 eat) ;multi byte
  8743. (setq ret (concat ret (char-to-string sum)))
  8744. (setq sum 0))
  8745. ((not bytes) ; single byte(s)
  8746. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8747. ret)))
  8748. (defun org-link-unescape-single-byte-sequence (hex)
  8749. "Unhexify hex-encoded single byte character sequences."
  8750. (mapconcat (lambda (byte)
  8751. (char-to-string (string-to-number byte 16)))
  8752. (cdr (split-string hex "%")) ""))
  8753. (defun org-fixup-message-id-for-http (s)
  8754. "Replace special characters in a message id, so it can be used in an http query."
  8755. (when (string-match "%" s)
  8756. (setq s (mapconcat (lambda (c)
  8757. (if (eq c ?%)
  8758. "%25"
  8759. (char-to-string c)))
  8760. s "")))
  8761. (while (string-match "<" s)
  8762. (setq s (replace-match "%3C" t t s)))
  8763. (while (string-match ">" s)
  8764. (setq s (replace-match "%3E" t t s)))
  8765. (while (string-match "@" s)
  8766. (setq s (replace-match "%40" t t s)))
  8767. s)
  8768. (defun org-link-prettify (link)
  8769. "Return a human-readable representation of LINK.
  8770. The car of LINK must be a raw link.
  8771. The cdr of LINK must be either a link description or nil."
  8772. (let ((desc (or (cadr link) "<no description>")))
  8773. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8774. "<" (car link) ">")))
  8775. ;;;###autoload
  8776. (defun org-insert-link-global ()
  8777. "Insert a link like Org mode does.
  8778. This command can be called in any mode to insert a link in Org syntax."
  8779. (interactive)
  8780. (org-load-modules-maybe)
  8781. (org-run-like-in-org-mode 'org-insert-link))
  8782. (defun org-insert-all-links (arg &optional pre post)
  8783. "Insert all links in `org-stored-links'.
  8784. When a universal prefix, do not delete the links from `org-stored-links'.
  8785. When `ARG' is a number, insert the last N link(s).
  8786. `PRE' and `POST' are optional arguments to define a string to
  8787. prepend or to append."
  8788. (interactive "P")
  8789. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8790. (links (copy-sequence org-stored-links))
  8791. (pr (or pre "- "))
  8792. (po (or post "\n"))
  8793. (cnt 1) l)
  8794. (if (null org-stored-links)
  8795. (message "No link to insert")
  8796. (while (and (or (listp arg) (>= arg cnt))
  8797. (setq l (if (listp arg)
  8798. (pop links)
  8799. (pop org-stored-links))))
  8800. (setq cnt (1+ cnt))
  8801. (insert pr)
  8802. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8803. (insert po)))))
  8804. (defun org-insert-last-stored-link (arg)
  8805. "Insert the last link stored in `org-stored-links'."
  8806. (interactive "p")
  8807. (org-insert-all-links arg "" "\n"))
  8808. (defun org-link-fontify-links-to-this-file ()
  8809. "Fontify links to the current file in `org-stored-links'."
  8810. (let ((f (buffer-file-name)) a b)
  8811. (setq a (mapcar (lambda(l)
  8812. (let ((ll (car l)))
  8813. (when (and (string-match "^file:\\(.+\\)::" ll)
  8814. (equal f (expand-file-name (match-string 1 ll))))
  8815. ll)))
  8816. org-stored-links))
  8817. (when (featurep 'org-id)
  8818. (setq b (mapcar (lambda(l)
  8819. (let ((ll (car l)))
  8820. (when (and (string-match "^id:\\(.+\\)$" ll)
  8821. (equal f (expand-file-name
  8822. (or (org-id-find-id-file
  8823. (match-string 1 ll)) ""))))
  8824. ll)))
  8825. org-stored-links)))
  8826. (mapcar (lambda(l)
  8827. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8828. (delq nil (append a b)))))
  8829. (defvar org--links-history nil)
  8830. (defun org-insert-link (&optional complete-file link-location default-description)
  8831. "Insert a link. At the prompt, enter the link.
  8832. Completion can be used to insert any of the link protocol prefixes in use.
  8833. The history can be used to select a link previously stored with
  8834. `org-store-link'. When the empty string is entered (i.e. if you just
  8835. press `RET' at the prompt), the link defaults to the most recently
  8836. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8837. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8838. You will also be prompted for a description, and if one is given, it will
  8839. be displayed in the buffer instead of the link.
  8840. If there is already a link at point, this command will allow you to edit
  8841. link and description parts.
  8842. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8843. file name can be
  8844. selected using completion. The path to the file will be relative to the
  8845. current directory if the file is in the current directory or a subdirectory.
  8846. Otherwise, the link will be the absolute path as completed in the minibuffer
  8847. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8848. option `org-link-file-path-type'.
  8849. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8850. absolute path even if the file is in
  8851. the current directory or below.
  8852. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8853. prefix negates `org-keep-stored-link-after-insertion'.
  8854. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8855. the link location instead of reading one interactively.
  8856. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8857. be used as the default description. Otherwise, if
  8858. `org-make-link-description-function' is non-nil, this function
  8859. will be called with the link target, and the result will be the
  8860. default link description."
  8861. (interactive "P")
  8862. (let* ((wcf (current-window-configuration))
  8863. (origbuf (current-buffer))
  8864. (region (when (org-region-active-p)
  8865. (buffer-substring (region-beginning) (region-end))))
  8866. (remove (and region (list (region-beginning) (region-end))))
  8867. (desc region)
  8868. (link link-location)
  8869. (abbrevs org-link-abbrev-alist-local)
  8870. entry all-prefixes auto-desc)
  8871. (cond
  8872. (link-location) ; specified by arg, just use it.
  8873. ((org-in-regexp org-bracket-link-regexp 1)
  8874. ;; We do have a link at point, and we are going to edit it.
  8875. (setq remove (list (match-beginning 0) (match-end 0)))
  8876. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8877. (setq link (read-string "Link: "
  8878. (org-link-unescape
  8879. (match-string-no-properties 1)))))
  8880. ((or (org-in-regexp org-angle-link-re)
  8881. (org-in-regexp org-plain-link-re))
  8882. ;; Convert to bracket link
  8883. (setq remove (list (match-beginning 0) (match-end 0))
  8884. link (read-string "Link: "
  8885. (org-unbracket-string "<" ">" (match-string 0)))))
  8886. ((member complete-file '((4) (16)))
  8887. ;; Completing read for file names.
  8888. (setq link (org-file-complete-link complete-file)))
  8889. (t
  8890. ;; Read link, with completion for stored links.
  8891. (org-link-fontify-links-to-this-file)
  8892. (org-switch-to-buffer-other-window "*Org Links*")
  8893. (with-current-buffer "*Org Links*"
  8894. (erase-buffer)
  8895. (insert "Insert a link.
  8896. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8897. (when org-stored-links
  8898. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8899. (insert (mapconcat 'org-link-prettify
  8900. (reverse org-stored-links) "\n")))
  8901. (goto-char (point-min)))
  8902. (let ((cw (selected-window)))
  8903. (select-window (get-buffer-window "*Org Links*" 'visible))
  8904. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8905. (unless (pos-visible-in-window-p (point-max))
  8906. (org-fit-window-to-buffer))
  8907. (and (window-live-p cw) (select-window cw)))
  8908. (setq all-prefixes (append (mapcar 'car abbrevs)
  8909. (mapcar 'car org-link-abbrev-alist)
  8910. (org-link-types)))
  8911. (unwind-protect
  8912. ;; Fake a link history, containing the stored links.
  8913. (let ((org--links-history
  8914. (append (mapcar #'car org-stored-links)
  8915. org-insert-link-history)))
  8916. (setq link
  8917. (org-completing-read
  8918. "Link: "
  8919. (append
  8920. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8921. (mapcar #'car org-stored-links))
  8922. nil nil nil
  8923. 'org--links-history
  8924. (caar org-stored-links)))
  8925. (unless (org-string-nw-p link) (user-error "No link selected"))
  8926. (dolist (l org-stored-links)
  8927. (when (equal link (cadr l))
  8928. (setq link (car l))
  8929. (setq auto-desc t)))
  8930. (when (or (member link all-prefixes)
  8931. (and (equal ":" (substring link -1))
  8932. (member (substring link 0 -1) all-prefixes)
  8933. (setq link (substring link 0 -1))))
  8934. (setq link (with-current-buffer origbuf
  8935. (org-link-try-special-completion link)))))
  8936. (set-window-configuration wcf)
  8937. (kill-buffer "*Org Links*"))
  8938. (setq entry (assoc link org-stored-links))
  8939. (or entry (push link org-insert-link-history))
  8940. (setq desc (or desc (nth 1 entry)))))
  8941. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8942. (not org-keep-stored-link-after-insertion))
  8943. (setq org-stored-links (delq (assoc link org-stored-links)
  8944. org-stored-links)))
  8945. (when (and (string-match org-plain-link-re link)
  8946. (not (string-match org-ts-regexp link)))
  8947. ;; URL-like link, normalize the use of angular brackets.
  8948. (setq link (org-unbracket-string "<" ">" link)))
  8949. ;; Check if we are linking to the current file with a search
  8950. ;; option If yes, simplify the link by using only the search
  8951. ;; option.
  8952. (when (and buffer-file-name
  8953. (let ((case-fold-search nil))
  8954. (string-match "\\`file:\\(.+?\\)::" link)))
  8955. (let ((path (match-string-no-properties 1 link))
  8956. (search (substring-no-properties link (match-end 0))))
  8957. (save-match-data
  8958. (when (equal (file-truename buffer-file-name) (file-truename path))
  8959. ;; We are linking to this same file, with a search option
  8960. (setq link search)))))
  8961. ;; Check if we can/should use a relative path. If yes, simplify
  8962. ;; the link.
  8963. (let ((case-fold-search nil))
  8964. (when (string-match "\\`\\(file\\|docview\\):" link)
  8965. (let* ((type (match-string-no-properties 0 link))
  8966. (path-start (match-end 0))
  8967. (search (and (string-match "::\\(.*\\)\\'" link)
  8968. (match-string 1 link)))
  8969. (path
  8970. (if search
  8971. (substring-no-properties
  8972. link path-start (match-beginning 0))
  8973. (substring-no-properties link (match-end 0))))
  8974. (origpath path))
  8975. (cond
  8976. ((or (eq org-link-file-path-type 'absolute)
  8977. (equal complete-file '(16)))
  8978. (setq path (abbreviate-file-name (expand-file-name path))))
  8979. ((eq org-link-file-path-type 'noabbrev)
  8980. (setq path (expand-file-name path)))
  8981. ((eq org-link-file-path-type 'relative)
  8982. (setq path (file-relative-name path)))
  8983. (t
  8984. (save-match-data
  8985. (if (string-match (concat "^" (regexp-quote
  8986. (expand-file-name
  8987. (file-name-as-directory
  8988. default-directory))))
  8989. (expand-file-name path))
  8990. ;; We are linking a file with relative path name.
  8991. (setq path (substring (expand-file-name path)
  8992. (match-end 0)))
  8993. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8994. (setq link (concat type path (and search (concat "::" search))))
  8995. (when (equal desc origpath)
  8996. (setq desc path)))))
  8997. (unless auto-desc
  8998. (let ((initial-input
  8999. (cond
  9000. (default-description)
  9001. ((not org-make-link-description-function) desc)
  9002. (t (condition-case nil
  9003. (funcall org-make-link-description-function link desc)
  9004. (error
  9005. (message "Can't get link description from `%s'"
  9006. (symbol-name org-make-link-description-function))
  9007. (sit-for 2)
  9008. nil))))))
  9009. (setq desc (read-string "Description: " initial-input))))
  9010. (unless (string-match "\\S-" desc) (setq desc nil))
  9011. (when remove (apply 'delete-region remove))
  9012. (insert (org-make-link-string link desc))
  9013. ;; Redisplay so as the new link has proper invisible characters.
  9014. (sit-for 0)))
  9015. (defun org-link-try-special-completion (type)
  9016. "If there is completion support for link type TYPE, offer it."
  9017. (let ((fun (org-link-get-parameter type :complete)))
  9018. (if (functionp fun)
  9019. (funcall fun)
  9020. (read-string "Link (no completion support): " (concat type ":")))))
  9021. (defun org-file-complete-link (&optional arg)
  9022. "Create a file link using completion."
  9023. (let ((file (read-file-name "File: "))
  9024. (pwd (file-name-as-directory (expand-file-name ".")))
  9025. (pwd1 (file-name-as-directory (abbreviate-file-name
  9026. (expand-file-name ".")))))
  9027. (cond ((equal arg '(16))
  9028. (concat "file:"
  9029. (abbreviate-file-name (expand-file-name file))))
  9030. ((string-match
  9031. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9032. (concat "file:" (match-string 1 file)))
  9033. ((string-match
  9034. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9035. (expand-file-name file))
  9036. (concat "file:"
  9037. (match-string 1 (expand-file-name file))))
  9038. (t (concat "file:" file)))))
  9039. ;;; Opening/following a link
  9040. (defvar org-link-search-failed nil)
  9041. (defvar org-open-link-functions nil
  9042. "Hook for functions finding a plain text link.
  9043. These functions must take a single argument, the link content.
  9044. They will be called for links that look like [[link text][description]]
  9045. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9046. like a filename (e.g. \"./blue.png\").
  9047. These functions will be called *before* Org attempts to resolve the
  9048. link by doing text searches in the current buffer - so if you want a
  9049. link \"[[target]]\" to still find \"<<target>>\", your function should
  9050. handle this as a special case.
  9051. When the function does handle the link, it must return a non-nil value.
  9052. If it decides that it is not responsible for this link, it must return
  9053. nil to indicate that that Org can continue with other options like
  9054. exact and fuzzy text search.")
  9055. (defun org-next-link (&optional search-backward)
  9056. "Move forward to the next link.
  9057. If the link is in hidden text, expose it."
  9058. (interactive "P")
  9059. (when (and org-link-search-failed (eq this-command last-command))
  9060. (goto-char (point-min))
  9061. (message "Link search wrapped back to beginning of buffer"))
  9062. (setq org-link-search-failed nil)
  9063. (let* ((pos (point))
  9064. (ct (org-context))
  9065. (a (assq :link ct))
  9066. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9067. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9068. ((looking-at org-any-link-re)
  9069. ;; Don't stay stuck at link without an org-link face
  9070. (forward-char (if search-backward -1 1))))
  9071. (if (funcall srch-fun org-any-link-re nil t)
  9072. (progn
  9073. (goto-char (match-beginning 0))
  9074. (when (org-invisible-p) (org-show-context)))
  9075. (goto-char pos)
  9076. (setq org-link-search-failed t)
  9077. (message "No further link found"))))
  9078. (defun org-previous-link ()
  9079. "Move backward to the previous link.
  9080. If the link is in hidden text, expose it."
  9081. (interactive)
  9082. (funcall 'org-next-link t))
  9083. (defun org-translate-link (s)
  9084. "Translate a link string if a translation function has been defined."
  9085. (with-temp-buffer
  9086. (insert (org-trim s))
  9087. (org-trim (org-element-interpret-data (org-element-context)))))
  9088. (defun org-translate-link-from-planner (type path)
  9089. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9090. This is still an experimental function, your mileage may vary."
  9091. (cond
  9092. ((member type '("http" "https" "news" "ftp"))
  9093. ;; standard Internet links are the same.
  9094. nil)
  9095. ((and (equal type "irc") (string-match "^//" path))
  9096. ;; Planner has two / at the beginning of an irc link, we have 1.
  9097. ;; We should have zero, actually....
  9098. (setq path (substring path 1)))
  9099. ((and (equal type "lisp") (string-match "^/" path))
  9100. ;; Planner has a slash, we do not.
  9101. (setq type "elisp" path (substring path 1)))
  9102. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9103. ;; A typical message link. Planner has the id after the final slash,
  9104. ;; we separate it with a hash mark
  9105. (setq path (concat (match-string 1 path) "#"
  9106. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9107. (cons type path))
  9108. (defun org-find-file-at-mouse (ev)
  9109. "Open file link or URL at mouse."
  9110. (interactive "e")
  9111. (mouse-set-point ev)
  9112. (org-open-at-point 'in-emacs))
  9113. (defun org-open-at-mouse (ev)
  9114. "Open file link or URL at mouse.
  9115. See the docstring of `org-open-file' for details."
  9116. (interactive "e")
  9117. (mouse-set-point ev)
  9118. (when (eq major-mode 'org-agenda-mode)
  9119. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9120. (org-open-at-point))
  9121. (defvar org-window-config-before-follow-link nil
  9122. "The window configuration before following a link.
  9123. This is saved in case the need arises to restore it.")
  9124. ;;;###autoload
  9125. (defun org-open-at-point-global ()
  9126. "Follow a link or time-stamp like Org mode does.
  9127. This command can be called in any mode to follow an external link
  9128. or a time-stamp that has Org mode syntax. Its behavior is
  9129. undefined when called on internal links (e.g., fuzzy links).
  9130. Raise an error when there is nothing to follow. "
  9131. (interactive)
  9132. (cond ((org-in-regexp org-any-link-re)
  9133. (org-open-link-from-string (match-string-no-properties 0)))
  9134. ((or (org-in-regexp org-ts-regexp-both nil t)
  9135. (org-in-regexp org-tsr-regexp-both nil t))
  9136. (org-follow-timestamp-link))
  9137. (t (user-error "No link found"))))
  9138. ;;;###autoload
  9139. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9140. "Open a link in the string S, as if it was in Org mode."
  9141. (interactive "sLink: \nP")
  9142. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9143. (with-temp-buffer
  9144. (let ((org-inhibit-startup (not reference-buffer)))
  9145. (org-mode)
  9146. (insert s)
  9147. (goto-char (point-min))
  9148. (when reference-buffer
  9149. (setq org-link-abbrev-alist-local
  9150. (with-current-buffer reference-buffer
  9151. org-link-abbrev-alist-local)))
  9152. (org-open-at-point arg reference-buffer)))))
  9153. (defvar org-open-at-point-functions nil
  9154. "Hook that is run when following a link at point.
  9155. Functions in this hook must return t if they identify and follow
  9156. a link at point. If they don't find anything interesting at point,
  9157. they must return nil.")
  9158. (defvar org-link-search-inhibit-query nil)
  9159. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9160. (defun org--open-doi-link (path)
  9161. "Open a \"doi\" type link.
  9162. PATH is a the path to search for, as a string."
  9163. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9164. (defun org--open-elisp-link (path)
  9165. "Open a \"elisp\" type link.
  9166. PATH is the sexp to evaluate, as a string."
  9167. (let ((cmd path))
  9168. (if (or (and (org-string-nw-p
  9169. org-confirm-elisp-link-not-regexp)
  9170. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9171. (not org-confirm-elisp-link-function)
  9172. (funcall org-confirm-elisp-link-function
  9173. (format "Execute \"%s\" as elisp? "
  9174. (org-add-props cmd nil 'face 'org-warning))))
  9175. (message "%s => %s" cmd
  9176. (if (eq (string-to-char cmd) ?\()
  9177. (eval (read cmd))
  9178. (call-interactively (read cmd))))
  9179. (user-error "Abort"))))
  9180. (defun org--open-help-link (path)
  9181. "Open a \"help\" type link.
  9182. PATH is a symbol name, as a string."
  9183. (pcase (intern path)
  9184. ((and (pred fboundp) variable) (describe-function variable))
  9185. ((and (pred boundp) function) (describe-variable function))
  9186. (name (user-error "Unknown function or variable: %s" name))))
  9187. (defun org--open-shell-link (path)
  9188. "Open a \"shell\" type link.
  9189. PATH is the command to execute, as a string."
  9190. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9191. (cmd path))
  9192. (if (or (and (org-string-nw-p
  9193. org-confirm-shell-link-not-regexp)
  9194. (string-match
  9195. org-confirm-shell-link-not-regexp cmd))
  9196. (not org-confirm-shell-link-function)
  9197. (funcall org-confirm-shell-link-function
  9198. (format "Execute \"%s\" in shell? "
  9199. (org-add-props cmd nil
  9200. 'face 'org-warning))))
  9201. (progn
  9202. (message "Executing %s" cmd)
  9203. (shell-command cmd buf)
  9204. (when (featurep 'midnight)
  9205. (setq clean-buffer-list-kill-buffer-names
  9206. (cons (buffer-name buf)
  9207. clean-buffer-list-kill-buffer-names))))
  9208. (user-error "Abort"))))
  9209. (defun org-open-at-point (&optional arg reference-buffer)
  9210. "Open link, timestamp, footnote or tags at point.
  9211. When point is on a link, follow it. Normally, files will be
  9212. opened by an appropriate application. If the optional prefix
  9213. argument ARG is non-nil, Emacs will visit the file. With
  9214. a double prefix argument, try to open outside of Emacs, in the
  9215. application the system uses for this file type.
  9216. When point is on a timestamp, open the agenda at the day
  9217. specified.
  9218. When point is a footnote definition, move to the first reference
  9219. found. If it is on a reference, move to the associated
  9220. definition.
  9221. When point is on a headline, display a list of every link in the
  9222. entry, so it is possible to pick one, or all, of them. If point
  9223. is on a tag, call `org-tags-view' instead.
  9224. When optional argument REFERENCE-BUFFER is non-nil, it should
  9225. specify a buffer from where the link search should happen. This
  9226. is used internally by `org-open-link-from-string'.
  9227. On top of syntactically correct links, this function will also
  9228. try to open links and time-stamps in comments, example
  9229. blocks... i.e., whenever point is on something looking like
  9230. a timestamp or a link."
  9231. (interactive "P")
  9232. ;; On a code block, open block's results.
  9233. (unless (call-interactively 'org-babel-open-src-block-result)
  9234. (org-load-modules-maybe)
  9235. (setq org-window-config-before-follow-link (current-window-configuration))
  9236. (org-remove-occur-highlights nil nil t)
  9237. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9238. (let* ((context
  9239. ;; Only consider supported types, even if they are not
  9240. ;; the closest one.
  9241. (org-element-lineage
  9242. (org-element-context)
  9243. '(clock footnote-definition footnote-reference headline
  9244. inlinetask link timestamp)
  9245. t))
  9246. (type (org-element-type context))
  9247. (value (org-element-property :value context)))
  9248. (cond
  9249. ;; On a headline or an inlinetask, but not on a timestamp,
  9250. ;; a link, a footnote reference.
  9251. ((memq type '(headline inlinetask))
  9252. (org-match-line org-complex-heading-regexp)
  9253. (if (and (match-beginning 5)
  9254. (>= (point) (match-beginning 5))
  9255. (< (point) (match-end 5)))
  9256. ;; On tags.
  9257. (org-tags-view arg (substring (match-string 5) 0 -1))
  9258. ;; Not on tags.
  9259. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9260. (`(nil . ,_)
  9261. (require 'org-attach)
  9262. (org-attach-reveal 'if-exists))
  9263. (`(,links . ,links-end)
  9264. (dolist (link (if (stringp links) (list links) links))
  9265. (search-forward link nil links-end)
  9266. (goto-char (match-beginning 0))
  9267. (org-open-at-point))))))
  9268. ;; On a footnote reference or at definition's label.
  9269. ((or (eq type 'footnote-reference)
  9270. (and (eq type 'footnote-definition)
  9271. (save-excursion
  9272. ;; Do not validate action when point is on the
  9273. ;; spaces right after the footnote label, in
  9274. ;; order to be on par with behaviour on links.
  9275. (skip-chars-forward " \t")
  9276. (let ((begin
  9277. (org-element-property :contents-begin context)))
  9278. (if begin (< (point) begin)
  9279. (= (org-element-property :post-affiliated context)
  9280. (line-beginning-position)))))))
  9281. (org-footnote-action))
  9282. ;; No valid context. Ignore catch-all types like `headline'.
  9283. ;; If point is on something looking like a link or
  9284. ;; a time-stamp, try opening it. It may be useful in
  9285. ;; comments, example blocks...
  9286. ((memq type '(footnote-definition headline inlinetask nil))
  9287. (call-interactively #'org-open-at-point-global))
  9288. ;; On a clock line, make sure point is on the timestamp
  9289. ;; before opening it.
  9290. ((and (eq type 'clock)
  9291. value
  9292. (>= (point) (org-element-property :begin value))
  9293. (<= (point) (org-element-property :end value)))
  9294. (org-follow-timestamp-link))
  9295. ;; Do nothing on white spaces after an object.
  9296. ((>= (point)
  9297. (save-excursion
  9298. (goto-char (org-element-property :end context))
  9299. (skip-chars-backward " \t")
  9300. (point)))
  9301. (user-error "No link found"))
  9302. ((eq type 'timestamp) (org-follow-timestamp-link))
  9303. ((eq type 'link)
  9304. (let ((type (org-element-property :type context))
  9305. (path (org-link-unescape (org-element-property :path context))))
  9306. ;; Switch back to REFERENCE-BUFFER needed when called in
  9307. ;; a temporary buffer through `org-open-link-from-string'.
  9308. (with-current-buffer (or reference-buffer (current-buffer))
  9309. (cond
  9310. ((equal type "file")
  9311. (if (string-match "[*?{]" (file-name-nondirectory path))
  9312. (dired path)
  9313. ;; Look into `org-link-parameters' in order to find
  9314. ;; a DEDICATED-FUNCTION to open file. The function
  9315. ;; will be applied on raw link instead of parsed
  9316. ;; link due to the limitation in `org-add-link-type'
  9317. ;; ("open" function called with a single argument).
  9318. ;; If no such function is found, fallback to
  9319. ;; `org-open-file'.
  9320. (let* ((option (org-element-property :search-option context))
  9321. (app (org-element-property :application context))
  9322. (dedicated-function
  9323. (org-link-get-parameter
  9324. (if app (concat type "+" app) type)
  9325. :follow)))
  9326. (if dedicated-function
  9327. (funcall dedicated-function
  9328. (concat path
  9329. (and option (concat "::" option))))
  9330. (apply #'org-open-file
  9331. path
  9332. (cond (arg)
  9333. ((equal app "emacs") 'emacs)
  9334. ((equal app "sys") 'system))
  9335. (cond ((not option) nil)
  9336. ((string-match-p "\\`[0-9]+\\'" option)
  9337. (list (string-to-number option)))
  9338. (t (list nil
  9339. (org-link-unescape option)))))))))
  9340. ((functionp (org-link-get-parameter type :follow))
  9341. (funcall (org-link-get-parameter type :follow) path))
  9342. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9343. (unless (run-hook-with-args-until-success
  9344. 'org-open-link-functions path)
  9345. (if (not arg) (org-mark-ring-push)
  9346. (switch-to-buffer-other-window
  9347. (org-get-buffer-for-internal-link (current-buffer))))
  9348. (let ((destination
  9349. (org-with-wide-buffer
  9350. (if (equal type "radio")
  9351. (org-search-radio-target
  9352. (org-element-property :path context))
  9353. (org-link-search
  9354. (if (member type '("custom-id" "coderef"))
  9355. (org-element-property :raw-link context)
  9356. path)
  9357. ;; Prevent fuzzy links from matching
  9358. ;; themselves.
  9359. (and (equal type "fuzzy")
  9360. (+ 2 (org-element-property :begin context)))))
  9361. (point))))
  9362. (unless (and (<= (point-min) destination)
  9363. (>= (point-max) destination))
  9364. (widen))
  9365. (goto-char destination))))
  9366. (t (browse-url-at-point))))))
  9367. (t (user-error "No link found")))))
  9368. (run-hook-with-args 'org-follow-link-hook)))
  9369. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9370. "Offer links in the current entry and return the selected link.
  9371. If there is only one link, return it.
  9372. If NTH is an integer, return the NTH link found.
  9373. If ZERO is a string, check also this string for a link, and if
  9374. there is one, return it."
  9375. (with-current-buffer buffer
  9376. (org-with-wide-buffer
  9377. (goto-char marker)
  9378. (let ((cnt ?0)
  9379. have-zero end links link c)
  9380. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9381. (push (match-string 0 zero) links)
  9382. (setq cnt (1- cnt) have-zero t))
  9383. (save-excursion
  9384. (org-back-to-heading t)
  9385. (setq end (save-excursion (outline-next-heading) (point)))
  9386. (while (re-search-forward org-any-link-re end t)
  9387. (push (match-string 0) links))
  9388. (setq links (org-uniquify (reverse links))))
  9389. (cond
  9390. ((null links)
  9391. (message "No links"))
  9392. ((equal (length links) 1)
  9393. (setq link (car links)))
  9394. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9395. (setq link (nth (if have-zero nth (1- nth)) links)))
  9396. (t ; we have to select a link
  9397. (save-excursion
  9398. (save-window-excursion
  9399. (delete-other-windows)
  9400. (with-output-to-temp-buffer "*Select Link*"
  9401. (dolist (l links)
  9402. (cond
  9403. ((not (string-match org-bracket-link-regexp l))
  9404. (princ (format "[%c] %s\n" (cl-incf cnt)
  9405. (org-unbracket-string "<" ">" l))))
  9406. ((match-end 3)
  9407. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9408. (match-string 3 l) (match-string 1 l))))
  9409. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9410. (match-string 1 l)))))))
  9411. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9412. (message "Select link to open, RET to open all:")
  9413. (setq c (read-char-exclusive))
  9414. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9415. (when (equal c ?q) (user-error "Abort"))
  9416. (if (equal c ?\C-m)
  9417. (setq link links)
  9418. (setq nth (- c ?0))
  9419. (when have-zero (setq nth (1+ nth)))
  9420. (unless (and (integerp nth) (>= (length links) nth))
  9421. (user-error "Invalid link selection"))
  9422. (setq link (nth (1- nth) links)))))
  9423. (cons link end)))))
  9424. ;; TODO: These functions are deprecated since `org-open-at-point'
  9425. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9426. (defun org-open-file-with-system (path)
  9427. "Open file at PATH using the system way of opening it."
  9428. (org-open-file path 'system))
  9429. (defun org-open-file-with-emacs (path)
  9430. "Open file at PATH in Emacs."
  9431. (org-open-file path 'emacs))
  9432. ;;; File search
  9433. (defvar org-create-file-search-functions nil
  9434. "List of functions to construct the right search string for a file link.
  9435. These functions are called in turn with point at the location to
  9436. which the link should point.
  9437. A function in the hook should first test if it would like to
  9438. handle this file type, for example by checking the `major-mode'
  9439. or the file extension. If it decides not to handle this file, it
  9440. should just return nil to give other functions a chance. If it
  9441. does handle the file, it must return the search string to be used
  9442. when following the link. The search string will be part of the
  9443. file link, given after a double colon, and `org-open-at-point'
  9444. will automatically search for it. If special measures must be
  9445. taken to make the search successful, another function should be
  9446. added to the companion hook `org-execute-file-search-functions',
  9447. which see.
  9448. A function in this hook may also use `setq' to set the variable
  9449. `description' to provide a suggestion for the descriptive text to
  9450. be used for this link when it gets inserted into an Org buffer
  9451. with \\[org-insert-link].")
  9452. (defvar org-execute-file-search-functions nil
  9453. "List of functions to execute a file search triggered by a link.
  9454. Functions added to this hook must accept a single argument, the
  9455. search string that was part of the file link, the part after the
  9456. double colon. The function must first check if it would like to
  9457. handle this search, for example by checking the `major-mode' or
  9458. the file extension. If it decides not to handle this search, it
  9459. should just return nil to give other functions a chance. If it
  9460. does handle the search, it must return a non-nil value to keep
  9461. other functions from trying.
  9462. Each function can access the current prefix argument through the
  9463. variable `current-prefix-arg'. Note that a single prefix is used
  9464. to force opening a link in Emacs, so it may be good to only use a
  9465. numeric or double prefix to guide the search function.
  9466. In case this is needed, a function in this hook can also restore
  9467. the window configuration before `org-open-at-point' was called using:
  9468. (set-window-configuration org-window-config-before-follow-link)")
  9469. (defun org-search-radio-target (target)
  9470. "Search a radio target matching TARGET in current buffer.
  9471. White spaces are not significant."
  9472. (let ((re (format "<<<%s>>>"
  9473. (mapconcat #'regexp-quote
  9474. (split-string target)
  9475. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9476. (origin (point)))
  9477. (goto-char (point-min))
  9478. (catch :radio-match
  9479. (while (re-search-forward re nil t)
  9480. (backward-char)
  9481. (let ((object (org-element-context)))
  9482. (when (eq (org-element-type object) 'radio-target)
  9483. (goto-char (org-element-property :begin object))
  9484. (org-show-context 'link-search)
  9485. (throw :radio-match nil))))
  9486. (goto-char origin)
  9487. (user-error "No match for radio target: %s" target))))
  9488. (defun org-link-search (s &optional avoid-pos stealth)
  9489. "Search for a search string S.
  9490. If S starts with \"#\", it triggers a custom ID search.
  9491. If S is enclosed within parenthesis, it initiates a coderef
  9492. search.
  9493. If S is surrounded by forward slashes, it is interpreted as
  9494. a regular expression. In Org mode files, this will create an
  9495. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9496. to list matches. If the current buffer is in `dired-mode', grep
  9497. will be used to search in all files.
  9498. When AVOID-POS is given, ignore matches near that position.
  9499. When optional argument STEALTH is non-nil, do not modify
  9500. visibility around point, thus ignoring `org-show-context-detail'
  9501. variable.
  9502. Search is case-insensitive and ignores white spaces. Return type
  9503. of matched result, which is either `dedicated' or `fuzzy'."
  9504. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9505. (let* ((case-fold-search t)
  9506. (origin (point))
  9507. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9508. (starred (eq (string-to-char normalized) ?*))
  9509. (words (split-string (if starred (substring s 1) s)))
  9510. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9511. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9512. type)
  9513. (cond
  9514. ;; Check if there are any special search functions.
  9515. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9516. ((eq (string-to-char s) ?#)
  9517. ;; Look for a custom ID S if S starts with "#".
  9518. (let* ((id (substring normalized 1))
  9519. (match (org-find-property "CUSTOM_ID" id)))
  9520. (if match (progn (goto-char match) (setf type 'dedicated))
  9521. (error "No match for custom ID: %s" id))))
  9522. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9523. ;; Look for coderef targets if S is enclosed within parenthesis.
  9524. (let ((coderef (match-string-no-properties 1 normalized))
  9525. (re (substring s-single-re 1 -1)))
  9526. (goto-char (point-min))
  9527. (catch :coderef-match
  9528. (while (re-search-forward re nil t)
  9529. (let ((element (org-element-at-point)))
  9530. (when (and (memq (org-element-type element)
  9531. '(example-block src-block))
  9532. ;; Build proper regexp according to current
  9533. ;; block's label format.
  9534. (let ((label-fmt
  9535. (regexp-quote
  9536. (or (org-element-property :label-fmt element)
  9537. org-coderef-label-format))))
  9538. (save-excursion
  9539. (beginning-of-line)
  9540. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9541. (format label-fmt coderef))))))
  9542. (setq type 'dedicated)
  9543. (goto-char (match-beginning 1))
  9544. (throw :coderef-match nil))))
  9545. (goto-char origin)
  9546. (error "No match for coderef: %s" coderef))))
  9547. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9548. ;; Look for a regular expression.
  9549. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9550. (match-string 1 s)))
  9551. ;; From here, we handle fuzzy links.
  9552. ;;
  9553. ;; Look for targets, only if not in a headline search.
  9554. ((and (not starred)
  9555. (let ((target (format "<<%s>>" s-multi-re)))
  9556. (catch :target-match
  9557. (goto-char (point-min))
  9558. (while (re-search-forward target nil t)
  9559. (backward-char)
  9560. (let ((context (org-element-context)))
  9561. (when (eq (org-element-type context) 'target)
  9562. (setq type 'dedicated)
  9563. (goto-char (org-element-property :begin context))
  9564. (throw :target-match t))))
  9565. nil))))
  9566. ;; Look for elements named after S, only if not in a headline
  9567. ;; search.
  9568. ((and (not starred)
  9569. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9570. (catch :name-match
  9571. (goto-char (point-min))
  9572. (while (re-search-forward name nil t)
  9573. (let ((element (org-element-at-point)))
  9574. (when (equal words
  9575. (split-string
  9576. (org-element-property :name element)))
  9577. (setq type 'dedicated)
  9578. (beginning-of-line)
  9579. (throw :name-match t))))
  9580. nil))))
  9581. ;; Regular text search. Prefer headlines in Org mode buffers.
  9582. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9583. ;; statistics cookies and tags.
  9584. ((and (derived-mode-p 'org-mode)
  9585. (let ((title-re
  9586. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9587. org-outline-regexp-bol
  9588. org-comment-string
  9589. (mapconcat #'regexp-quote words ".+")))
  9590. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9591. (comment-re (eval-when-compile
  9592. (format "\\`%s[ \t]+" org-comment-string))))
  9593. (goto-char (point-min))
  9594. (catch :found
  9595. (while (re-search-forward title-re nil t)
  9596. (when (equal words
  9597. (split-string
  9598. (replace-regexp-in-string
  9599. cookie-re ""
  9600. (replace-regexp-in-string
  9601. comment-re "" (org-get-heading t t t)))))
  9602. (throw :found t)))
  9603. nil)))
  9604. (beginning-of-line)
  9605. (setq type 'dedicated))
  9606. ;; Offer to create non-existent headline depending on
  9607. ;; `org-link-search-must-match-exact-headline'.
  9608. ((and (derived-mode-p 'org-mode)
  9609. (not org-link-search-inhibit-query)
  9610. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9611. (yes-or-no-p "No match - create this as a new heading? "))
  9612. (goto-char (point-max))
  9613. (unless (bolp) (newline))
  9614. (org-insert-heading nil t t)
  9615. (insert s "\n")
  9616. (beginning-of-line 0))
  9617. ;; Only headlines are looked after. No need to process
  9618. ;; further: throw an error.
  9619. ((and (derived-mode-p 'org-mode)
  9620. (or starred org-link-search-must-match-exact-headline))
  9621. (goto-char origin)
  9622. (error "No match for fuzzy expression: %s" normalized))
  9623. ;; Regular text search.
  9624. ((catch :fuzzy-match
  9625. (goto-char (point-min))
  9626. (while (re-search-forward s-multi-re nil t)
  9627. ;; Skip match if it contains AVOID-POS or it is included in
  9628. ;; a link with a description but outside the description.
  9629. (unless (or (and avoid-pos
  9630. (<= (match-beginning 0) avoid-pos)
  9631. (> (match-end 0) avoid-pos))
  9632. (and (save-match-data
  9633. (org-in-regexp org-bracket-link-regexp))
  9634. (match-beginning 3)
  9635. (or (> (match-beginning 3) (point))
  9636. (<= (match-end 3) (point)))
  9637. (org-element-lineage
  9638. (save-match-data (org-element-context))
  9639. '(link) t)))
  9640. (goto-char (match-beginning 0))
  9641. (setq type 'fuzzy)
  9642. (throw :fuzzy-match t)))
  9643. nil))
  9644. ;; All failed. Throw an error.
  9645. (t (goto-char origin)
  9646. (error "No match for fuzzy expression: %s" normalized)))
  9647. ;; Disclose surroundings of match, if appropriate.
  9648. (when (and (derived-mode-p 'org-mode) (not stealth))
  9649. (org-show-context 'link-search))
  9650. type))
  9651. (defun org-get-buffer-for-internal-link (buffer)
  9652. "Return a buffer to be used for displaying the link target of internal links."
  9653. (cond
  9654. ((not org-display-internal-link-with-indirect-buffer)
  9655. buffer)
  9656. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9657. (message "Buffer is already a clone, not making another one")
  9658. ;; we also do not modify visibility in this case
  9659. buffer)
  9660. (t ; make a new indirect buffer for displaying the link
  9661. (let* ((bn (buffer-name buffer))
  9662. (ibn (concat bn "(Clone)"))
  9663. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9664. (with-current-buffer ib (org-overview))
  9665. ib))))
  9666. (defun org-do-occur (regexp &optional cleanup)
  9667. "Call the Emacs command `occur'.
  9668. If CLEANUP is non-nil, remove the printout of the regular expression
  9669. in the *Occur* buffer. This is useful if the regex is long and not useful
  9670. to read."
  9671. (occur regexp)
  9672. (when cleanup
  9673. (let ((cwin (selected-window)) win beg end)
  9674. (when (setq win (get-buffer-window "*Occur*"))
  9675. (select-window win))
  9676. (goto-char (point-min))
  9677. (when (re-search-forward "match[a-z]+" nil t)
  9678. (setq beg (match-end 0))
  9679. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9680. (setq end (1- (match-beginning 0)))))
  9681. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9682. (goto-char (point-min))
  9683. (select-window cwin))))
  9684. ;;; The mark ring for links jumps
  9685. (defvar org-mark-ring nil
  9686. "Mark ring for positions before jumps in Org mode.")
  9687. (defvar org-mark-ring-last-goto nil
  9688. "Last position in the mark ring used to go back.")
  9689. ;; Fill and close the ring
  9690. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9691. (dotimes (_ org-mark-ring-length)
  9692. (push (make-marker) org-mark-ring))
  9693. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9694. org-mark-ring)
  9695. (defun org-mark-ring-push (&optional pos buffer)
  9696. "Put the current position or POS into the mark ring and rotate it."
  9697. (interactive)
  9698. (setq pos (or pos (point)))
  9699. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9700. (move-marker (car org-mark-ring)
  9701. (or pos (point))
  9702. (or buffer (current-buffer)))
  9703. (message "%s"
  9704. (substitute-command-keys
  9705. "Position saved to mark ring, go back with \
  9706. `\\[org-mark-ring-goto]'.")))
  9707. (defun org-mark-ring-goto (&optional n)
  9708. "Jump to the previous position in the mark ring.
  9709. With prefix arg N, jump back that many stored positions. When
  9710. called several times in succession, walk through the entire ring.
  9711. Org mode commands jumping to a different position in the current file,
  9712. or to another Org file, automatically push the old position onto the ring."
  9713. (interactive "p")
  9714. (let (p m)
  9715. (if (eq last-command this-command)
  9716. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9717. (setq p org-mark-ring))
  9718. (setq org-mark-ring-last-goto p)
  9719. (setq m (car p))
  9720. (pop-to-buffer-same-window (marker-buffer m))
  9721. (goto-char m)
  9722. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9723. (defun org-add-angle-brackets (s)
  9724. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9725. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9726. s)
  9727. ;;; Following specific links
  9728. (defvar org-agenda-buffer-tmp-name)
  9729. (defvar org-agenda-start-on-weekday)
  9730. (defun org-follow-timestamp-link ()
  9731. "Open an agenda view for the time-stamp date/range at point."
  9732. (cond
  9733. ((org-at-date-range-p t)
  9734. (let ((org-agenda-start-on-weekday)
  9735. (t1 (match-string 1))
  9736. (t2 (match-string 2)) tt1 tt2)
  9737. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9738. tt2 (time-to-days (org-time-string-to-time t2)))
  9739. (let ((org-agenda-buffer-tmp-name
  9740. (format "*Org Agenda(a:%s)"
  9741. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9742. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9743. ((org-at-timestamp-p 'lax)
  9744. (let ((org-agenda-buffer-tmp-name
  9745. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9746. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9747. (substring (match-string 1) 0 10)))
  9748. 1)))
  9749. (t (error "This should not happen"))))
  9750. ;;; Following file links
  9751. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9752. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9753. (declare-function mailcap-mime-info
  9754. "mailcap" (string &optional request no-decode))
  9755. (defvar org-wait nil)
  9756. (defun org-open-file (path &optional in-emacs line search)
  9757. "Open the file at PATH.
  9758. First, this expands any special file name abbreviations. Then the
  9759. configuration variable `org-file-apps' is checked if it contains an
  9760. entry for this file type, and if yes, the corresponding command is launched.
  9761. If no application is found, Emacs simply visits the file.
  9762. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9763. With a double \\[universal-argument] \\[universal-argument] \
  9764. prefix arg, Org tries to avoid opening in Emacs
  9765. and to use an external application to visit the file.
  9766. Optional LINE specifies a line to go to, optional SEARCH a string
  9767. to search for. If LINE or SEARCH is given, the file will be
  9768. opened in Emacs, unless an entry from org-file-apps that makes
  9769. use of groups in a regexp matches.
  9770. If you want to change the way frames are used when following a
  9771. link, please customize `org-link-frame-setup'.
  9772. If the file does not exist, an error is thrown."
  9773. (let* ((file (if (equal path "")
  9774. buffer-file-name
  9775. (substitute-in-file-name (expand-file-name path))))
  9776. (file-apps (append org-file-apps (org-default-apps)))
  9777. (apps (cl-remove-if
  9778. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9779. (apps-dlink (cl-remove-if-not
  9780. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9781. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9782. (dirp (unless remp (file-directory-p file)))
  9783. (file (if (and dirp org-open-directory-means-index-dot-org)
  9784. (concat (file-name-as-directory file) "index.org")
  9785. file))
  9786. (a-m-a-p (assq 'auto-mode apps))
  9787. (dfile (downcase file))
  9788. ;; Reconstruct the original link from the PATH, LINE and
  9789. ;; SEARCH args.
  9790. (link (cond (line (concat file "::" (number-to-string line)))
  9791. (search (concat file "::" search))
  9792. (t file)))
  9793. (dlink (downcase link))
  9794. (ext
  9795. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9796. (match-string 1 dfile)))
  9797. (save-position-maybe
  9798. (let ((old-buffer (current-buffer))
  9799. (old-pos (point))
  9800. (old-mode major-mode))
  9801. (lambda ()
  9802. (and (derived-mode-p 'org-mode)
  9803. (eq old-mode 'org-mode)
  9804. (or (not (eq old-buffer (current-buffer)))
  9805. (not (eq old-pos (point))))
  9806. (org-mark-ring-push old-pos old-buffer)))))
  9807. cmd link-match-data)
  9808. (cond
  9809. ((member in-emacs '((16) system))
  9810. (setq cmd (cdr (assq 'system apps))))
  9811. (in-emacs (setq cmd 'emacs))
  9812. (t
  9813. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9814. (and dirp (cdr (assq 'directory apps)))
  9815. ;; First, try matching against apps-dlink if we
  9816. ;; get a match here, store the match data for
  9817. ;; later.
  9818. (let ((match (assoc-default dlink apps-dlink
  9819. 'string-match)))
  9820. (if match
  9821. (progn (setq link-match-data (match-data))
  9822. match)
  9823. (progn (setq in-emacs (or in-emacs line search))
  9824. nil))) ; if we have no match in apps-dlink,
  9825. ; always open the file in emacs if line or search
  9826. ; is given (for backwards compatibility)
  9827. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9828. 'string-match)
  9829. (cdr (assoc ext apps))
  9830. (cdr (assq t apps))))))
  9831. (when (eq cmd 'system)
  9832. (setq cmd (cdr (assq 'system apps))))
  9833. (when (eq cmd 'default)
  9834. (setq cmd (cdr (assoc t apps))))
  9835. (when (eq cmd 'mailcap)
  9836. (require 'mailcap)
  9837. (mailcap-parse-mailcaps)
  9838. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9839. (command (mailcap-mime-info mime-type)))
  9840. (if (stringp command)
  9841. (setq cmd command)
  9842. (setq cmd 'emacs))))
  9843. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9844. (not (file-exists-p file))
  9845. (not org-open-non-existing-files))
  9846. (user-error "No such file: %s" file))
  9847. (cond
  9848. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9849. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9850. (while (string-match "['\"]%s['\"]" cmd)
  9851. (setq cmd (replace-match "%s" t t cmd)))
  9852. (setq cmd (replace-regexp-in-string
  9853. "%s"
  9854. (shell-quote-argument (convert-standard-filename file))
  9855. cmd
  9856. nil t))
  9857. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9858. (save-match-data
  9859. (let ((match-index 1)
  9860. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9861. (set-match-data link-match-data)
  9862. (while (<= match-index number-of-groups)
  9863. (let ((regex (concat "%" (number-to-string match-index)))
  9864. (replace-with (match-string match-index dlink)))
  9865. (while (string-match regex cmd)
  9866. (setq cmd (replace-match replace-with t t cmd))))
  9867. (setq match-index (+ match-index 1)))))
  9868. (save-window-excursion
  9869. (message "Running %s...done" cmd)
  9870. (start-process-shell-command cmd nil cmd)
  9871. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9872. ((or (stringp cmd)
  9873. (eq cmd 'emacs))
  9874. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9875. (widen)
  9876. (cond (line (org-goto-line line)
  9877. (when (derived-mode-p 'org-mode) (org-reveal)))
  9878. (search (condition-case err
  9879. (org-link-search search)
  9880. ;; Save position before error-ing out so user
  9881. ;; can easily move back to the original buffer.
  9882. (error (funcall save-position-maybe)
  9883. (error (nth 1 err)))))))
  9884. ((functionp cmd)
  9885. (save-match-data
  9886. (set-match-data link-match-data)
  9887. (condition-case nil
  9888. (funcall cmd file link)
  9889. ;; FIXME: Remove this check when most default installations
  9890. ;; of Emacs have at least Org 9.0.
  9891. ((debug wrong-number-of-arguments wrong-type-argument
  9892. invalid-function)
  9893. (user-error "Please see Org News for version 9.0 about \
  9894. `org-file-apps'--Lisp error: %S" cmd)))))
  9895. ((consp cmd)
  9896. ;; FIXME: Remove this check when most default installations of
  9897. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9898. ;; fall back to `org-link-frame-setup' for an old usage of
  9899. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9900. (user-error "Please see Org News for version 9.0 about \
  9901. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9902. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9903. (funcall save-position-maybe)))
  9904. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9905. "This function returns non-nil if `entry' uses a regular
  9906. expression which should be matched against the whole link by
  9907. org-open-file.
  9908. It assumes that is the case when the entry uses a regular
  9909. expression which has at least one grouping construct and the
  9910. action is either a lisp form or a command string containing
  9911. `%1', i.e. using at least one subexpression match as a
  9912. parameter."
  9913. (let ((selector (car entry))
  9914. (action (cdr entry)))
  9915. (if (stringp selector)
  9916. (and (> (regexp-opt-depth selector) 0)
  9917. (or (and (stringp action)
  9918. (string-match "%[0-9]" action))
  9919. (consp action)))
  9920. nil)))
  9921. (defun org-default-apps ()
  9922. "Return the default applications for this operating system."
  9923. (cond
  9924. ((eq system-type 'darwin)
  9925. org-file-apps-defaults-macosx)
  9926. ((eq system-type 'windows-nt)
  9927. org-file-apps-defaults-windowsnt)
  9928. (t org-file-apps-defaults-gnu)))
  9929. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9930. "Convert extensions to regular expressions in the cars of LIST.
  9931. Also, weed out any non-string entries, because the return value is used
  9932. only for regexp matching.
  9933. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9934. point to the symbol `emacs', indicating that the file should
  9935. be opened in Emacs."
  9936. (append
  9937. (delq nil
  9938. (mapcar (lambda (x)
  9939. (unless (not (stringp (car x)))
  9940. (if (string-match "\\W" (car x))
  9941. x
  9942. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9943. list))
  9944. (when add-auto-mode
  9945. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9946. (defvar ange-ftp-name-format)
  9947. (defun org-file-remote-p (file)
  9948. "Test whether FILE specifies a location on a remote system.
  9949. Return non-nil if the location is indeed remote.
  9950. For example, the filename \"/user@host:/foo\" specifies a location
  9951. on the system \"/user@host:\"."
  9952. (cond ((fboundp 'file-remote-p)
  9953. (file-remote-p file))
  9954. ((fboundp 'tramp-handle-file-remote-p)
  9955. (tramp-handle-file-remote-p file))
  9956. ((and (boundp 'ange-ftp-name-format)
  9957. (string-match (car ange-ftp-name-format) file))
  9958. t)))
  9959. ;;;; Refiling
  9960. (defun org-get-org-file ()
  9961. "Read a filename, with default directory `org-directory'."
  9962. (let ((default (or org-default-notes-file remember-data-file)))
  9963. (read-file-name (format "File name [%s]: " default)
  9964. (file-name-as-directory org-directory)
  9965. default)))
  9966. (defun org-notes-order-reversed-p ()
  9967. "Check if the current file should receive notes in reversed order."
  9968. (cond
  9969. ((not org-reverse-note-order) nil)
  9970. ((eq t org-reverse-note-order) t)
  9971. ((not (listp org-reverse-note-order)) nil)
  9972. (t (catch 'exit
  9973. (dolist (entry org-reverse-note-order)
  9974. (when (string-match (car entry) buffer-file-name)
  9975. (throw 'exit (cdr entry))))))))
  9976. (defvar org-refile-target-table nil
  9977. "The list of refile targets, created by `org-refile'.")
  9978. (defvar org-agenda-new-buffers nil
  9979. "Buffers created to visit agenda files.")
  9980. (defvar org-refile-cache nil
  9981. "Cache for refile targets.")
  9982. (defvar org-refile-markers nil
  9983. "All the markers used for caching refile locations.")
  9984. (defun org-refile-marker (pos)
  9985. "Get a new refile marker, but only if caching is in use."
  9986. (if (not org-refile-use-cache)
  9987. pos
  9988. (let ((m (make-marker)))
  9989. (move-marker m pos)
  9990. (push m org-refile-markers)
  9991. m)))
  9992. (defun org-refile-cache-clear ()
  9993. "Clear the refile cache and disable all the markers."
  9994. (dolist (m org-refile-markers) (move-marker m nil))
  9995. (setq org-refile-markers nil)
  9996. (setq org-refile-cache nil)
  9997. (message "Refile cache has been cleared"))
  9998. (defun org-refile-cache-check-set (set)
  9999. "Check if all the markers in the cache still have live buffers."
  10000. (let (marker)
  10001. (catch 'exit
  10002. (while (and set (setq marker (nth 3 (pop set))))
  10003. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10004. (when (and marker (null (marker-buffer marker)))
  10005. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10006. (sit-for 3)
  10007. (throw 'exit nil)))
  10008. t)))
  10009. (defun org-refile-cache-put (set &rest identifiers)
  10010. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10011. (let* ((key (sha1 (prin1-to-string identifiers)))
  10012. (entry (assoc key org-refile-cache)))
  10013. (if entry
  10014. (setcdr entry set)
  10015. (push (cons key set) org-refile-cache))))
  10016. (defun org-refile-cache-get (&rest identifiers)
  10017. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10018. (cond
  10019. ((not org-refile-cache) nil)
  10020. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10021. (t
  10022. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10023. org-refile-cache))))
  10024. (and set (org-refile-cache-check-set set) set)))))
  10025. (defvar org-outline-path-cache nil
  10026. "Alist between buffer positions and outline paths.
  10027. It value is an alist (POSITION . PATH) where POSITION is the
  10028. buffer position at the beginning of an entry and PATH is a list
  10029. of strings describing the outline path for that entry, in reverse
  10030. order.")
  10031. (defun org-refile-get-targets (&optional default-buffer)
  10032. "Produce a table with refile targets."
  10033. (let ((case-fold-search nil)
  10034. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10035. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10036. targets tgs files desc descre)
  10037. (message "Getting targets...")
  10038. (with-current-buffer (or default-buffer (current-buffer))
  10039. (dolist (entry entries)
  10040. (setq files (car entry) desc (cdr entry))
  10041. (cond
  10042. ((null files) (setq files (list (current-buffer))))
  10043. ((eq files 'org-agenda-files)
  10044. (setq files (org-agenda-files 'unrestricted)))
  10045. ((and (symbolp files) (fboundp files))
  10046. (setq files (funcall files)))
  10047. ((and (symbolp files) (boundp files))
  10048. (setq files (symbol-value files))))
  10049. (when (stringp files) (setq files (list files)))
  10050. (cond
  10051. ((eq (car desc) :tag)
  10052. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10053. ((eq (car desc) :todo)
  10054. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10055. ((eq (car desc) :regexp)
  10056. (setq descre (cdr desc)))
  10057. ((eq (car desc) :level)
  10058. (setq descre (concat "^\\*\\{" (number-to-string
  10059. (if org-odd-levels-only
  10060. (1- (* 2 (cdr desc)))
  10061. (cdr desc)))
  10062. "\\}[ \t]")))
  10063. ((eq (car desc) :maxlevel)
  10064. (setq descre (concat "^\\*\\{1," (number-to-string
  10065. (if org-odd-levels-only
  10066. (1- (* 2 (cdr desc)))
  10067. (cdr desc)))
  10068. "\\}[ \t]")))
  10069. (t (error "Bad refiling target description %s" desc)))
  10070. (dolist (f files)
  10071. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10072. (or
  10073. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10074. (progn
  10075. (when (bufferp f)
  10076. (setq f (buffer-file-name (buffer-base-buffer f))))
  10077. (setq f (and f (expand-file-name f)))
  10078. (when (eq org-refile-use-outline-path 'file)
  10079. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10080. (when (eq org-refile-use-outline-path 'buffer-name)
  10081. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10082. (when (eq org-refile-use-outline-path 'full-file-path)
  10083. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10084. (org-with-wide-buffer
  10085. (goto-char (point-min))
  10086. (setq org-outline-path-cache nil)
  10087. (while (re-search-forward descre nil t)
  10088. (beginning-of-line)
  10089. (let ((case-fold-search nil))
  10090. (looking-at org-complex-heading-regexp))
  10091. (let ((begin (point))
  10092. (heading (match-string-no-properties 4)))
  10093. (unless (or (and
  10094. org-refile-target-verify-function
  10095. (not
  10096. (funcall org-refile-target-verify-function)))
  10097. (not heading))
  10098. (let ((re (format org-complex-heading-regexp-format
  10099. (regexp-quote heading)))
  10100. (target
  10101. (if (not org-refile-use-outline-path) heading
  10102. (mapconcat
  10103. #'identity
  10104. (append
  10105. (pcase org-refile-use-outline-path
  10106. (`file (list (file-name-nondirectory
  10107. (buffer-file-name
  10108. (buffer-base-buffer)))))
  10109. (`full-file-path
  10110. (list (buffer-file-name
  10111. (buffer-base-buffer))))
  10112. (`buffer-name
  10113. (list (buffer-name
  10114. (buffer-base-buffer))))
  10115. (_ nil))
  10116. (mapcar (lambda (s) (replace-regexp-in-string
  10117. "/" "\\/" s nil t))
  10118. (org-get-outline-path t t)))
  10119. "/"))))
  10120. (push (list target f re (org-refile-marker (point)))
  10121. tgs)))
  10122. (when (= (point) begin)
  10123. ;; Verification function has not moved point.
  10124. (end-of-line)))))))
  10125. (when org-refile-use-cache
  10126. (org-refile-cache-put tgs (buffer-file-name) descre))
  10127. (setq targets (append tgs targets))))))
  10128. (message "Getting targets...done")
  10129. (delete-dups (nreverse targets))))
  10130. (defun org--get-outline-path-1 (&optional use-cache)
  10131. "Return outline path to current headline.
  10132. Outline path is a list of strings, in reverse order. When
  10133. optional argument USE-CACHE is non-nil, make use of a cache. See
  10134. `org-get-outline-path' for details.
  10135. Assume buffer is widened and point is on a headline."
  10136. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10137. (let ((p (point))
  10138. (heading (let ((case-fold-search nil))
  10139. (looking-at org-complex-heading-regexp)
  10140. (if (not (match-end 4)) ""
  10141. ;; Remove statistics cookies.
  10142. (org-trim
  10143. (org-link-display-format
  10144. (replace-regexp-in-string
  10145. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10146. (match-string-no-properties 4))))))))
  10147. (if (org-up-heading-safe)
  10148. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10149. (when use-cache
  10150. (push (cons p path) org-outline-path-cache))
  10151. path)
  10152. ;; This is a new root node. Since we assume we are moving
  10153. ;; forward, we can drop previous cache so as to limit number
  10154. ;; of associations there.
  10155. (let ((path (list heading)))
  10156. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10157. path)))))
  10158. (defun org-get-outline-path (&optional with-self use-cache)
  10159. "Return the outline path to the current entry.
  10160. An outline path is a list of ancestors for current headline, as
  10161. a list of strings. Statistics cookies are removed and links are
  10162. replaced with their description, if any, or their path otherwise.
  10163. When optional argument WITH-SELF is non-nil, the path also
  10164. includes the current headline.
  10165. When optional argument USE-CACHE is non-nil, cache outline paths
  10166. between calls to this function so as to avoid backtracking. This
  10167. argument is useful when planning to find more than one outline
  10168. path in the same document. In that case, there are two
  10169. conditions to satisfy:
  10170. - `org-outline-path-cache' is set to nil before starting the
  10171. process;
  10172. - outline paths are computed by increasing buffer positions."
  10173. (org-with-wide-buffer
  10174. (and (or (and with-self (org-back-to-heading t))
  10175. (org-up-heading-safe))
  10176. (reverse (org--get-outline-path-1 use-cache)))))
  10177. (defun org-format-outline-path (path &optional width prefix separator)
  10178. "Format the outline path PATH for display.
  10179. WIDTH is the maximum number of characters that is available.
  10180. PREFIX is a prefix to be included in the returned string,
  10181. such as the file name.
  10182. SEPARATOR is inserted between the different parts of the path,
  10183. the default is \"/\"."
  10184. (setq width (or width 79))
  10185. (setq path (delq nil path))
  10186. (unless (> width 0)
  10187. (user-error "Argument `width' must be positive"))
  10188. (setq separator (or separator "/"))
  10189. (let* ((org-odd-levels-only nil)
  10190. (fpath (concat
  10191. prefix (and prefix path separator)
  10192. (mapconcat
  10193. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10194. (cl-loop for head in path
  10195. for n from 0
  10196. collect (org-add-props
  10197. head nil 'face
  10198. (nth (% n org-n-level-faces) org-level-faces)))
  10199. separator))))
  10200. (when (> (length fpath) width)
  10201. (if (< width 7)
  10202. ;; It's unlikely that `width' will be this small, but don't
  10203. ;; waste characters by adding ".." if it is.
  10204. (setq fpath (substring fpath 0 width))
  10205. (setf (substring fpath (- width 2)) "..")))
  10206. fpath))
  10207. (defun org-display-outline-path (&optional file current separator just-return-string)
  10208. "Display the current outline path in the echo area.
  10209. If FILE is non-nil, prepend the output with the file name.
  10210. If CURRENT is non-nil, append the current heading to the output.
  10211. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10212. the different parts of the path and defaults to \"/\".
  10213. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10214. (interactive "P")
  10215. (let* (case-fold-search
  10216. (bfn (buffer-file-name (buffer-base-buffer)))
  10217. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10218. res)
  10219. (when current (setq path (append path
  10220. (save-excursion
  10221. (org-back-to-heading t)
  10222. (when (looking-at org-complex-heading-regexp)
  10223. (list (match-string 4)))))))
  10224. (setq res
  10225. (org-format-outline-path
  10226. path
  10227. (1- (frame-width))
  10228. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10229. separator))
  10230. (if just-return-string
  10231. (org-no-properties res)
  10232. (org-unlogged-message "%s" res))))
  10233. (defvar org-refile-history nil
  10234. "History for refiling operations.")
  10235. (defvar org-after-refile-insert-hook nil
  10236. "Hook run after `org-refile' has inserted its stuff at the new location.
  10237. Note that this is still *before* the stuff will be removed from
  10238. the *old* location.")
  10239. (defvar org-capture-last-stored-marker)
  10240. (defvar org-refile-keep nil
  10241. "Non-nil means `org-refile' will copy instead of refile.")
  10242. (defun org-copy ()
  10243. "Like `org-refile', but copy."
  10244. (interactive)
  10245. (let ((org-refile-keep t))
  10246. (funcall 'org-refile nil nil nil "Copy")))
  10247. (defun org-refile (&optional arg default-buffer rfloc msg)
  10248. "Move the entry or entries at point to another heading.
  10249. The list of target headings is compiled using the information in
  10250. `org-refile-targets', which see.
  10251. At the target location, the entry is filed as a subitem of the
  10252. target heading. Depending on `org-reverse-note-order', the new
  10253. subitem will either be the first or the last subitem.
  10254. If there is an active region, all entries in that region will be
  10255. refiled. However, the region must fulfill the requirement that
  10256. the first heading sets the top-level of the moved text.
  10257. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10258. location
  10259. and not actually move anything.
  10260. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10261. location where the last
  10262. refiling operation has put the subtree.
  10263. With a numeric prefix argument of `2', refile to the running clock.
  10264. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10265. being set to t and copy to the target location, don't move it.
  10266. Beware that keeping refiled entries may result in duplicated ID
  10267. properties.
  10268. RFLOC can be a refile location obtained in a different way.
  10269. MSG is a string to replace \"Refile\" in the default prompt with
  10270. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10271. See also `org-refile-use-outline-path'.
  10272. If you are using target caching (see `org-refile-use-cache'), you
  10273. have to clear the target cache in order to find new targets.
  10274. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10275. prefix argument (`C-u C-u C-u C-c C-w')."
  10276. (interactive "P")
  10277. (if (member arg '(0 (64)))
  10278. (org-refile-cache-clear)
  10279. (let* ((actionmsg (cond (msg msg)
  10280. ((equal arg 3) "Refile (and keep)")
  10281. (t "Refile")))
  10282. (regionp (org-region-active-p))
  10283. (region-start (and regionp (region-beginning)))
  10284. (region-end (and regionp (region-end)))
  10285. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10286. pos it nbuf file level reversed)
  10287. (setq last-command nil)
  10288. (when regionp
  10289. (goto-char region-start)
  10290. (or (bolp) (goto-char (point-at-bol)))
  10291. (setq region-start (point))
  10292. (unless (or (org-kill-is-subtree-p
  10293. (buffer-substring region-start region-end))
  10294. (prog1 org-refile-active-region-within-subtree
  10295. (let ((s (point-at-eol)))
  10296. (org-toggle-heading)
  10297. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10298. (user-error "The region is not a (sequence of) subtree(s)")))
  10299. (if (equal arg '(16))
  10300. (org-refile-goto-last-stored)
  10301. (when (or
  10302. (and (equal arg 2)
  10303. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10304. (prog1
  10305. (setq it (list (or org-clock-heading "running clock")
  10306. (buffer-file-name
  10307. (marker-buffer org-clock-hd-marker))
  10308. ""
  10309. (marker-position org-clock-hd-marker)))
  10310. (setq arg nil)))
  10311. (setq it
  10312. (or rfloc
  10313. (let (heading-text)
  10314. (save-excursion
  10315. (unless (and arg (listp arg))
  10316. (org-back-to-heading t)
  10317. (setq heading-text
  10318. (replace-regexp-in-string
  10319. org-bracket-link-regexp
  10320. "\\3"
  10321. (or (nth 4 (org-heading-components))
  10322. ""))))
  10323. (org-refile-get-location
  10324. (cond ((and arg (listp arg)) "Goto")
  10325. (regionp (concat actionmsg " region to"))
  10326. (t (concat actionmsg " subtree \""
  10327. heading-text "\" to")))
  10328. default-buffer
  10329. (and (not (equal '(4) arg))
  10330. org-refile-allow-creating-parent-nodes)))))))
  10331. (setq file (nth 1 it)
  10332. pos (nth 3 it))
  10333. (when (and (not arg)
  10334. pos
  10335. (equal (buffer-file-name) file)
  10336. (if regionp
  10337. (and (>= pos region-start)
  10338. (<= pos region-end))
  10339. (and (>= pos (point))
  10340. (< pos (save-excursion
  10341. (org-end-of-subtree t t))))))
  10342. (error "Cannot refile to position inside the tree or region"))
  10343. (setq nbuf (or (find-buffer-visiting file)
  10344. (find-file-noselect file)))
  10345. (if (and arg (not (equal arg 3)))
  10346. (progn
  10347. (pop-to-buffer-same-window nbuf)
  10348. (goto-char (cond (pos)
  10349. ((org-notes-order-reversed-p) (point-min))
  10350. (t (point-max))))
  10351. (org-show-context 'org-goto))
  10352. (if regionp
  10353. (progn
  10354. (org-kill-new (buffer-substring region-start region-end))
  10355. (org-save-markers-in-region region-start region-end))
  10356. (org-copy-subtree 1 nil t))
  10357. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10358. (find-file-noselect file)))
  10359. (setq reversed (org-notes-order-reversed-p))
  10360. (org-with-wide-buffer
  10361. (if pos
  10362. (progn
  10363. (goto-char pos)
  10364. (setq level (org-get-valid-level (funcall outline-level) 1))
  10365. (goto-char
  10366. (if reversed
  10367. (or (outline-next-heading) (point-max))
  10368. (or (save-excursion (org-get-next-sibling))
  10369. (org-end-of-subtree t t)
  10370. (point-max)))))
  10371. (setq level 1)
  10372. (if (not reversed)
  10373. (goto-char (point-max))
  10374. (goto-char (point-min))
  10375. (or (outline-next-heading) (goto-char (point-max)))))
  10376. (unless (bolp) (newline))
  10377. (org-paste-subtree level nil nil t)
  10378. (when org-log-refile
  10379. (org-add-log-setup 'refile nil nil org-log-refile)
  10380. (unless (eq org-log-refile 'note)
  10381. (save-excursion (org-add-log-note))))
  10382. (and org-auto-align-tags
  10383. (let ((org-loop-over-headlines-in-active-region nil))
  10384. (org-set-tags nil t)))
  10385. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10386. :last-refile)))
  10387. (when bookmark-name
  10388. (with-demoted-errors
  10389. (bookmark-set bookmark-name))))
  10390. ;; If we are refiling for capture, make sure that the
  10391. ;; last-capture pointers point here
  10392. (when (bound-and-true-p org-capture-is-refiling)
  10393. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10394. :last-capture-marker)))
  10395. (when bookmark-name
  10396. (with-demoted-errors
  10397. (bookmark-set bookmark-name))))
  10398. (move-marker org-capture-last-stored-marker (point)))
  10399. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10400. (run-hooks 'org-after-refile-insert-hook)))
  10401. (unless org-refile-keep
  10402. (if regionp
  10403. (delete-region (point) (+ (point) (- region-end region-start)))
  10404. (org-preserve-local-variables
  10405. (delete-region
  10406. (and (org-back-to-heading t) (point))
  10407. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10408. (when (featurep 'org-inlinetask)
  10409. (org-inlinetask-remove-END-maybe))
  10410. (setq org-markers-to-move nil)
  10411. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10412. (defun org-refile-goto-last-stored ()
  10413. "Go to the location where the last refile was stored."
  10414. (interactive)
  10415. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10416. (message "This is the location of the last refile"))
  10417. (defun org-refile--get-location (refloc tbl)
  10418. "When user refile to REFLOC, find the associated target in TBL.
  10419. Also check `org-refile-target-table'."
  10420. (car (delq
  10421. nil
  10422. (mapcar
  10423. (lambda (r) (or (assoc r tbl)
  10424. (assoc r org-refile-target-table)))
  10425. (list (replace-regexp-in-string "/$" "" refloc)
  10426. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10427. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10428. "Prompt the user for a refile location, using PROMPT.
  10429. PROMPT should not be suffixed with a colon and a space, because
  10430. this function appends the default value from
  10431. `org-refile-history' automatically, if that is not empty."
  10432. (let ((org-refile-targets org-refile-targets)
  10433. (org-refile-use-outline-path org-refile-use-outline-path))
  10434. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10435. (unless org-refile-target-table
  10436. (user-error "No refile targets"))
  10437. (let* ((cbuf (current-buffer))
  10438. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10439. (cfunc (if (and org-refile-use-outline-path
  10440. org-outline-path-complete-in-steps)
  10441. #'org-olpath-completing-read
  10442. #'completing-read))
  10443. (extra (if org-refile-use-outline-path "/" ""))
  10444. (cbnex (concat (buffer-name) extra))
  10445. (filename (and cfn (expand-file-name cfn)))
  10446. (tbl (mapcar
  10447. (lambda (x)
  10448. (if (and (not (member org-refile-use-outline-path
  10449. '(file full-file-path)))
  10450. (not (equal filename (nth 1 x))))
  10451. (cons (concat (car x) extra " ("
  10452. (file-name-nondirectory (nth 1 x)) ")")
  10453. (cdr x))
  10454. (cons (concat (car x) extra) (cdr x))))
  10455. org-refile-target-table))
  10456. (completion-ignore-case t)
  10457. cdef
  10458. (prompt (concat prompt
  10459. (or (and (car org-refile-history)
  10460. (concat " (default " (car org-refile-history) ")"))
  10461. (and (assoc cbnex tbl) (setq cdef cbnex)
  10462. (concat " (default " cbnex ")"))) ": "))
  10463. pa answ parent-target child parent old-hist)
  10464. (setq old-hist org-refile-history)
  10465. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10466. nil 'org-refile-history (or cdef (car org-refile-history))))
  10467. (if (setq pa (org-refile--get-location answ tbl))
  10468. (progn
  10469. (org-refile-check-position pa)
  10470. (when (or (not org-refile-history)
  10471. (not (eq old-hist org-refile-history))
  10472. (not (equal (car pa) (car org-refile-history))))
  10473. (setq org-refile-history
  10474. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10475. org-refile-history
  10476. (cdr org-refile-history))))
  10477. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10478. (pop org-refile-history)))
  10479. pa)
  10480. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10481. (progn
  10482. (setq parent (match-string 1 answ)
  10483. child (match-string 2 answ))
  10484. (setq parent-target (org-refile--get-location parent tbl))
  10485. (when (and parent-target
  10486. (or (eq new-nodes t)
  10487. (and (eq new-nodes 'confirm)
  10488. (y-or-n-p (format "Create new node \"%s\"? "
  10489. child)))))
  10490. (org-refile-new-child parent-target child)))
  10491. (user-error "Invalid target location")))))
  10492. (declare-function org-string-nw-p "org-macs" (s))
  10493. (defun org-refile-check-position (refile-pointer)
  10494. "Check if the refile pointer matches the headline to which it points."
  10495. (let* ((file (nth 1 refile-pointer))
  10496. (re (nth 2 refile-pointer))
  10497. (pos (nth 3 refile-pointer))
  10498. buffer)
  10499. (if (and (not (markerp pos)) (not file))
  10500. (user-error "Please indicate a target file in the refile path")
  10501. (when (org-string-nw-p re)
  10502. (setq buffer (if (markerp pos)
  10503. (marker-buffer pos)
  10504. (or (find-buffer-visiting file)
  10505. (find-file-noselect file))))
  10506. (with-current-buffer buffer
  10507. (org-with-wide-buffer
  10508. (goto-char pos)
  10509. (beginning-of-line 1)
  10510. (unless (looking-at-p re)
  10511. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10512. (defun org-refile-new-child (parent-target child)
  10513. "Use refile target PARENT-TARGET to add new CHILD below it."
  10514. (unless parent-target
  10515. (error "Cannot find parent for new node"))
  10516. (let ((file (nth 1 parent-target))
  10517. (pos (nth 3 parent-target))
  10518. level)
  10519. (with-current-buffer (or (find-buffer-visiting file)
  10520. (find-file-noselect file))
  10521. (org-with-wide-buffer
  10522. (if pos
  10523. (goto-char pos)
  10524. (goto-char (point-max))
  10525. (unless (bolp) (newline)))
  10526. (when (looking-at org-outline-regexp)
  10527. (setq level (funcall outline-level))
  10528. (org-end-of-subtree t t))
  10529. (org-back-over-empty-lines)
  10530. (insert "\n" (make-string
  10531. (if pos (org-get-valid-level level 1) 1) ?*)
  10532. " " child "\n")
  10533. (beginning-of-line 0)
  10534. (list (concat (car parent-target) "/" child) file "" (point))))))
  10535. (defun org-olpath-completing-read (prompt collection &rest args)
  10536. "Read an outline path like a file name."
  10537. (let ((thetable collection))
  10538. (apply #'completing-read
  10539. prompt
  10540. (lambda (string predicate &optional flag)
  10541. (cond
  10542. ((eq flag nil) (try-completion string thetable))
  10543. ((eq flag t)
  10544. (let ((l (length string)))
  10545. (mapcar (lambda (x)
  10546. (let ((r (substring x l))
  10547. (f (if (string-match " ([^)]*)$" x)
  10548. (match-string 0 x)
  10549. "")))
  10550. (if (string-match "/" r)
  10551. (concat string (substring r 0 (match-end 0)) f)
  10552. x)))
  10553. (all-completions string thetable predicate))))
  10554. ;; Exact match?
  10555. ((eq flag 'lambda) (assoc string thetable))))
  10556. args)))
  10557. ;;;; Dynamic blocks
  10558. (defun org-find-dblock (name)
  10559. "Find the first dynamic block with name NAME in the buffer.
  10560. If not found, stay at current position and return nil."
  10561. (let ((case-fold-search t) pos)
  10562. (save-excursion
  10563. (goto-char (point-min))
  10564. (setq pos (and (re-search-forward
  10565. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10566. (match-beginning 0))))
  10567. (when pos (goto-char pos))
  10568. pos))
  10569. (defun org-create-dblock (plist)
  10570. "Create a dynamic block section, with parameters taken from PLIST.
  10571. PLIST must contain a :name entry which is used as the name of the block."
  10572. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10573. (end-of-line 1)
  10574. (newline))
  10575. (let ((col (current-column))
  10576. (name (plist-get plist :name)))
  10577. (insert "#+BEGIN: " name)
  10578. (while plist
  10579. (if (eq (car plist) :name)
  10580. (setq plist (cddr plist))
  10581. (insert " " (prin1-to-string (pop plist)))))
  10582. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10583. (beginning-of-line -2)))
  10584. (defun org-prepare-dblock ()
  10585. "Prepare dynamic block for refresh.
  10586. This empties the block, puts the cursor at the insert position and returns
  10587. the property list including an extra property :name with the block name."
  10588. (unless (looking-at org-dblock-start-re)
  10589. (user-error "Not at a dynamic block"))
  10590. (let* ((begdel (1+ (match-end 0)))
  10591. (name (org-no-properties (match-string 1)))
  10592. (params (append (list :name name)
  10593. (read (concat "(" (match-string 3) ")")))))
  10594. (save-excursion
  10595. (beginning-of-line 1)
  10596. (skip-chars-forward " \t")
  10597. (setq params (plist-put params :indentation-column (current-column))))
  10598. (unless (re-search-forward org-dblock-end-re nil t)
  10599. (error "Dynamic block not terminated"))
  10600. (setq params
  10601. (append params
  10602. (list :content (buffer-substring
  10603. begdel (match-beginning 0)))))
  10604. (delete-region begdel (match-beginning 0))
  10605. (goto-char begdel)
  10606. (open-line 1)
  10607. params))
  10608. (defun org-map-dblocks (&optional command)
  10609. "Apply COMMAND to all dynamic blocks in the current buffer.
  10610. If COMMAND is not given, use `org-update-dblock'."
  10611. (let ((cmd (or command 'org-update-dblock)))
  10612. (save-excursion
  10613. (goto-char (point-min))
  10614. (while (re-search-forward org-dblock-start-re nil t)
  10615. (goto-char (match-beginning 0))
  10616. (save-excursion
  10617. (condition-case nil
  10618. (funcall cmd)
  10619. (error (message "Error during update of dynamic block"))))
  10620. (unless (re-search-forward org-dblock-end-re nil t)
  10621. (error "Dynamic block not terminated"))))))
  10622. (defun org-dblock-update (&optional arg)
  10623. "User command for updating dynamic blocks.
  10624. Update the dynamic block at point. With prefix ARG, update all dynamic
  10625. blocks in the buffer."
  10626. (interactive "P")
  10627. (if arg
  10628. (org-update-all-dblocks)
  10629. (or (looking-at org-dblock-start-re)
  10630. (org-beginning-of-dblock))
  10631. (org-update-dblock)))
  10632. (defun org-update-dblock ()
  10633. "Update the dynamic block at point.
  10634. This means to empty the block, parse for parameters and then call
  10635. the correct writing function."
  10636. (interactive)
  10637. (save-excursion
  10638. (let* ((win (selected-window))
  10639. (pos (point))
  10640. (line (org-current-line))
  10641. (params (org-prepare-dblock))
  10642. (name (plist-get params :name))
  10643. (indent (plist-get params :indentation-column))
  10644. (cmd (intern (concat "org-dblock-write:" name))))
  10645. (message "Updating dynamic block `%s' at line %d..." name line)
  10646. (funcall cmd params)
  10647. (message "Updating dynamic block `%s' at line %d...done" name line)
  10648. (goto-char pos)
  10649. (when (and indent (> indent 0))
  10650. (setq indent (make-string indent ?\ ))
  10651. (save-excursion
  10652. (select-window win)
  10653. (org-beginning-of-dblock)
  10654. (forward-line 1)
  10655. (while (not (looking-at org-dblock-end-re))
  10656. (insert indent)
  10657. (beginning-of-line 2))
  10658. (when (looking-at org-dblock-end-re)
  10659. (and (looking-at "[ \t]+")
  10660. (replace-match ""))
  10661. (insert indent)))))))
  10662. (defun org-beginning-of-dblock ()
  10663. "Find the beginning of the dynamic block at point.
  10664. Error if there is no such block at point."
  10665. (let ((pos (point))
  10666. beg)
  10667. (end-of-line 1)
  10668. (if (and (re-search-backward org-dblock-start-re nil t)
  10669. (setq beg (match-beginning 0))
  10670. (re-search-forward org-dblock-end-re nil t)
  10671. (> (match-end 0) pos))
  10672. (goto-char beg)
  10673. (goto-char pos)
  10674. (error "Not in a dynamic block"))))
  10675. (defun org-update-all-dblocks ()
  10676. "Update all dynamic blocks in the buffer.
  10677. This function can be used in a hook."
  10678. (interactive)
  10679. (when (derived-mode-p 'org-mode)
  10680. (org-map-dblocks 'org-update-dblock)))
  10681. ;;;; Completion
  10682. (declare-function org-export-backend-options "ox" (cl-x) t)
  10683. (defun org-get-export-keywords ()
  10684. "Return a list of all currently understood export keywords.
  10685. Export keywords include options, block names, attributes and
  10686. keywords relative to each registered export back-end."
  10687. (let (keywords)
  10688. (dolist (backend
  10689. (bound-and-true-p org-export-registered-backends)
  10690. (delq nil keywords))
  10691. ;; Back-end name (for keywords, like #+LATEX:)
  10692. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10693. (dolist (option-entry (org-export-backend-options backend))
  10694. ;; Back-end options.
  10695. (push (nth 1 option-entry) keywords)))))
  10696. (defconst org-options-keywords
  10697. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10698. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10699. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10700. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10701. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10702. (defcustom org-structure-template-alist
  10703. '((?a . "export ascii")
  10704. (?c . "center")
  10705. (?C . "comment")
  10706. (?e . "example")
  10707. (?E . "export")
  10708. (?h . "export html")
  10709. (?l . "export latex")
  10710. (?q . "quote")
  10711. (?s . "src")
  10712. (?v . "verse"))
  10713. "Structure completion elements.
  10714. This is an alist of characters and values. When
  10715. `org-insert-structure-template' is called, an additional key is
  10716. read. The key is first looked up in this alist, and the
  10717. corresponding structure is inserted, with \"#+BEGIN_\" and
  10718. \"#+END_\" added automatically."
  10719. :group 'org-edit-structure
  10720. :type '(repeat
  10721. (cons (character :tag "Key")
  10722. (string :tag "Template")))
  10723. :package-version '(Org . "9.2"))
  10724. (defun org-insert-structure-template (type)
  10725. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10726. First read a character, which can be one of the keys in
  10727. `org-structure-template-alist'. When it is <TAB>, prompt the
  10728. user for a string to use. With an active region, wrap the region
  10729. in the block. Otherwise, insert an empty block."
  10730. (interactive
  10731. (list
  10732. (let* ((key (read-key "Key: "))
  10733. (struct-string
  10734. (or (cdr (assq key org-structure-template-alist))
  10735. (and (= key ?\t)
  10736. (read-string "Structure type: "))
  10737. (user-error "`%c' has no structure definition" key))))
  10738. struct-string)))
  10739. (let* ((region? (use-region-p))
  10740. (s (if region? (region-beginning) (point)))
  10741. (e (copy-marker (if region? (region-end) (point)) t))
  10742. column)
  10743. (when (string-match-p
  10744. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10745. type)
  10746. (org-escape-code-in-region s e))
  10747. (goto-char s)
  10748. (setq column (current-indentation))
  10749. (beginning-of-line)
  10750. (indent-to column)
  10751. (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
  10752. (goto-char e)
  10753. (if (bolp)
  10754. (progn
  10755. (skip-chars-backward " \n\t")
  10756. (forward-line))
  10757. (end-of-line)
  10758. (insert "\n"))
  10759. (indent-to column)
  10760. (insert (format "#+end_%s\n"
  10761. (car (split-string type))))
  10762. (when (or (not region?)
  10763. (string-match-p "src\\|\\`export\\'" type))
  10764. (goto-char s)
  10765. (end-of-line))
  10766. (set-marker e nil)))
  10767. ;;;; TODO, DEADLINE, Comments
  10768. (defun org-toggle-comment ()
  10769. "Change the COMMENT state of an entry."
  10770. (interactive)
  10771. (save-excursion
  10772. (org-back-to-heading)
  10773. (let ((case-fold-search nil))
  10774. (looking-at org-complex-heading-regexp))
  10775. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10776. (skip-chars-forward " \t")
  10777. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10778. (if (org-in-commented-heading-p t)
  10779. (delete-region (point)
  10780. (progn (search-forward " " (line-end-position) 'move)
  10781. (skip-chars-forward " \t")
  10782. (point)))
  10783. (insert org-comment-string)
  10784. (unless (eolp) (insert " ")))))
  10785. (defvar org-last-todo-state-is-todo nil
  10786. "This is non-nil when the last TODO state change led to a TODO state.
  10787. If the last change removed the TODO tag or switched to DONE, then
  10788. this is nil.")
  10789. (defvar org-setting-tags nil) ; dynamically skipped
  10790. (defvar org-todo-setup-filter-hook nil
  10791. "Hook for functions that pre-filter todo specs.
  10792. Each function takes a todo spec and returns either nil or the spec
  10793. transformed into canonical form." )
  10794. (defvar org-todo-get-default-hook nil
  10795. "Hook for functions that get a default item for todo.
  10796. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10797. nil or a string to be used for the todo mark." )
  10798. (defvar org-agenda-headline-snapshot-before-repeat)
  10799. (defun org-current-effective-time ()
  10800. "Return current time adjusted for `org-extend-today-until' variable."
  10801. (let* ((ct (org-current-time))
  10802. (dct (decode-time ct))
  10803. (ct1
  10804. (cond
  10805. (org-use-last-clock-out-time-as-effective-time
  10806. (or (org-clock-get-last-clock-out-time) ct))
  10807. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10808. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10809. (t ct))))
  10810. ct1))
  10811. (defun org-todo-yesterday (&optional arg)
  10812. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10813. (interactive "P")
  10814. (if (eq major-mode 'org-agenda-mode)
  10815. (apply 'org-agenda-todo-yesterday arg)
  10816. (let* ((org-use-effective-time t)
  10817. (hour (nth 2 (decode-time (org-current-time))))
  10818. (org-extend-today-until (1+ hour)))
  10819. (org-todo arg))))
  10820. (defvar org-block-entry-blocking ""
  10821. "First entry preventing the TODO state change.")
  10822. (defun org-cancel-repeater ()
  10823. "Cancel a repeater by setting its numeric value to zero."
  10824. (interactive)
  10825. (save-excursion
  10826. (org-back-to-heading t)
  10827. (let ((bound1 (point))
  10828. (bound0 (save-excursion (outline-next-heading) (point))))
  10829. (when (and (re-search-forward
  10830. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10831. org-deadline-time-regexp "\\)\\|\\("
  10832. org-ts-regexp "\\)")
  10833. bound0 t)
  10834. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10835. bound1 t))
  10836. (replace-match "0" t nil nil 1)))))
  10837. (defvar org-state)
  10838. (defvar org-blocked-by-checkboxes)
  10839. (defun org-todo (&optional arg)
  10840. "Change the TODO state of an item.
  10841. The state of an item is given by a keyword at the start of the heading,
  10842. like
  10843. *** TODO Write paper
  10844. *** DONE Call mom
  10845. The different keywords are specified in the variable `org-todo-keywords'.
  10846. By default the available states are \"TODO\" and \"DONE\". So, for this
  10847. example: when the item starts with TODO, it is changed to DONE.
  10848. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10849. DONE are present, add TODO at the beginning of the heading.
  10850. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10851. state.
  10852. With numeric prefix ARG, switch to that state.
  10853. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10854. next set of TODO \
  10855. keywords (nextset).
  10856. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10857. prefix, circumvent any state blocking.
  10858. With a numeric prefix arg of 0, inhibit note taking for the change.
  10859. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10860. When called through ELisp, arg is also interpreted in the following way:
  10861. `none' -> empty state
  10862. \"\" -> switch to empty state
  10863. `done' -> switch to DONE
  10864. `nextset' -> switch to the next set of keywords
  10865. `previousset' -> switch to the previous set of keywords
  10866. \"WAITING\" -> switch to the specified keyword, but only if it
  10867. really is a member of `org-todo-keywords'."
  10868. (interactive "P")
  10869. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10870. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10871. 'region-start-level 'region))
  10872. org-loop-over-headlines-in-active-region)
  10873. (org-map-entries
  10874. `(org-todo ,arg)
  10875. org-loop-over-headlines-in-active-region
  10876. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10877. (when (equal arg '(16)) (setq arg 'nextset))
  10878. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10879. (let ((org-blocker-hook org-blocker-hook)
  10880. commentp
  10881. case-fold-search)
  10882. (when (equal arg '(64))
  10883. (setq arg nil org-blocker-hook nil))
  10884. (when (and org-blocker-hook
  10885. (or org-inhibit-blocking
  10886. (org-entry-get nil "NOBLOCKING")))
  10887. (setq org-blocker-hook nil))
  10888. (save-excursion
  10889. (catch 'exit
  10890. (org-back-to-heading t)
  10891. (when (org-in-commented-heading-p t)
  10892. (org-toggle-comment)
  10893. (setq commentp t))
  10894. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10895. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10896. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10897. (let* ((match-data (match-data))
  10898. (startpos (copy-marker (line-beginning-position)))
  10899. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10900. (org-log-done org-log-done)
  10901. (org-log-repeat org-log-repeat)
  10902. (org-todo-log-states org-todo-log-states)
  10903. (org-inhibit-logging
  10904. (if (equal arg 0)
  10905. (progn (setq arg nil) 'note) org-inhibit-logging))
  10906. (this (match-string 1))
  10907. (hl-pos (match-beginning 0))
  10908. (head (org-get-todo-sequence-head this))
  10909. (ass (assoc head org-todo-kwd-alist))
  10910. (interpret (nth 1 ass))
  10911. (done-word (nth 3 ass))
  10912. (final-done-word (nth 4 ass))
  10913. (org-last-state (or this ""))
  10914. (completion-ignore-case t)
  10915. (member (member this org-todo-keywords-1))
  10916. (tail (cdr member))
  10917. (org-state (cond
  10918. ((and org-todo-key-trigger
  10919. (or (and (equal arg '(4))
  10920. (eq org-use-fast-todo-selection 'prefix))
  10921. (and (not arg) org-use-fast-todo-selection
  10922. (not (eq org-use-fast-todo-selection
  10923. 'prefix)))))
  10924. ;; Use fast selection.
  10925. (org-fast-todo-selection))
  10926. ((and (equal arg '(4))
  10927. (or (not org-use-fast-todo-selection)
  10928. (not org-todo-key-trigger)))
  10929. ;; Read a state with completion.
  10930. (completing-read
  10931. "State: " (mapcar #'list org-todo-keywords-1)
  10932. nil t))
  10933. ((eq arg 'right)
  10934. (if this
  10935. (if tail (car tail) nil)
  10936. (car org-todo-keywords-1)))
  10937. ((eq arg 'left)
  10938. (unless (equal member org-todo-keywords-1)
  10939. (if this
  10940. (nth (- (length org-todo-keywords-1)
  10941. (length tail) 2)
  10942. org-todo-keywords-1)
  10943. (org-last org-todo-keywords-1))))
  10944. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10945. (setq arg nil))) ;hack to fall back to cycling
  10946. (arg
  10947. ;; User or caller requests a specific state.
  10948. (cond
  10949. ((equal arg "") nil)
  10950. ((eq arg 'none) nil)
  10951. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10952. ((eq arg 'nextset)
  10953. (or (car (cdr (member head org-todo-heads)))
  10954. (car org-todo-heads)))
  10955. ((eq arg 'previousset)
  10956. (let ((org-todo-heads (reverse org-todo-heads)))
  10957. (or (car (cdr (member head org-todo-heads)))
  10958. (car org-todo-heads))))
  10959. ((car (member arg org-todo-keywords-1)))
  10960. ((stringp arg)
  10961. (user-error "State `%s' not valid in this file" arg))
  10962. ((nth (1- (prefix-numeric-value arg))
  10963. org-todo-keywords-1))))
  10964. ((null member) (or head (car org-todo-keywords-1)))
  10965. ((equal this final-done-word) nil) ;-> make empty
  10966. ((null tail) nil) ;-> first entry
  10967. ((memq interpret '(type priority))
  10968. (if (eq this-command last-command)
  10969. (car tail)
  10970. (if (> (length tail) 0)
  10971. (or done-word (car org-done-keywords))
  10972. nil)))
  10973. (t
  10974. (car tail))))
  10975. (org-state (or
  10976. (run-hook-with-args-until-success
  10977. 'org-todo-get-default-hook org-state org-last-state)
  10978. org-state))
  10979. (next (if org-state (concat " " org-state " ") " "))
  10980. (change-plist (list :type 'todo-state-change :from this :to org-state
  10981. :position startpos))
  10982. dolog now-done-p)
  10983. (when org-blocker-hook
  10984. (let (org-blocked-by-checkboxes block-reason)
  10985. (setq org-last-todo-state-is-todo
  10986. (not (member this org-done-keywords)))
  10987. (unless (save-excursion
  10988. (save-match-data
  10989. (org-with-wide-buffer
  10990. (run-hook-with-args-until-failure
  10991. 'org-blocker-hook change-plist))))
  10992. (setq block-reason (if org-blocked-by-checkboxes
  10993. "contained checkboxes"
  10994. (format "\"%s\"" org-block-entry-blocking)))
  10995. (if (called-interactively-p 'interactive)
  10996. (user-error "TODO state change from %s to %s blocked (by %s)"
  10997. this org-state block-reason)
  10998. ;; Fail silently.
  10999. (message "TODO state change from %s to %s blocked (by %s)"
  11000. this org-state block-reason)
  11001. (throw 'exit nil)))))
  11002. (store-match-data match-data)
  11003. (replace-match next t t)
  11004. (cond ((equal this org-state)
  11005. (message "TODO state was already %s" (org-trim next)))
  11006. ((not (pos-visible-in-window-p hl-pos))
  11007. (message "TODO state changed to %s" (org-trim next))))
  11008. (unless head
  11009. (setq head (org-get-todo-sequence-head org-state)
  11010. ass (assoc head org-todo-kwd-alist)
  11011. interpret (nth 1 ass)
  11012. done-word (nth 3 ass)
  11013. final-done-word (nth 4 ass)))
  11014. (when (memq arg '(nextset previousset))
  11015. (message "Keyword-Set %d/%d: %s"
  11016. (- (length org-todo-sets) -1
  11017. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11018. (length org-todo-sets)
  11019. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11020. (setq org-last-todo-state-is-todo
  11021. (not (member org-state org-done-keywords)))
  11022. (setq now-done-p (and (member org-state org-done-keywords)
  11023. (not (member this org-done-keywords))))
  11024. (and logging (org-local-logging logging))
  11025. (when (and (or org-todo-log-states org-log-done)
  11026. (not (eq org-inhibit-logging t))
  11027. (not (memq arg '(nextset previousset))))
  11028. ;; We need to look at recording a time and note.
  11029. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11030. (nth 2 (assoc this org-todo-log-states))))
  11031. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11032. (setq dolog 'time))
  11033. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11034. (and org-state
  11035. (member org-state org-not-done-keywords)
  11036. (not (member this org-not-done-keywords))))
  11037. ;; This is now a todo state and was not one before
  11038. ;; If there was a CLOSED time stamp, get rid of it.
  11039. (org-add-planning-info nil nil 'closed))
  11040. (when (and now-done-p org-log-done)
  11041. ;; It is now done, and it was not done before.
  11042. (org-add-planning-info 'closed (org-current-effective-time))
  11043. (when (and (not dolog) (eq 'note org-log-done))
  11044. (org-add-log-setup 'done org-state this 'note)))
  11045. (when (and org-state dolog)
  11046. ;; This is a non-nil state, and we need to log it.
  11047. (org-add-log-setup 'state org-state this dolog)))
  11048. ;; Fixup tag positioning.
  11049. (org-todo-trigger-tag-changes org-state)
  11050. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11051. (when org-provide-todo-statistics
  11052. (org-update-parent-todo-statistics))
  11053. (run-hooks 'org-after-todo-state-change-hook)
  11054. (when (and arg (not (member org-state org-done-keywords)))
  11055. (setq head (org-get-todo-sequence-head org-state)))
  11056. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11057. ;; Do we need to trigger a repeat?
  11058. (when now-done-p
  11059. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11060. ;; This is for the agenda, take a snapshot of the headline.
  11061. (save-match-data
  11062. (setq org-agenda-headline-snapshot-before-repeat
  11063. (org-get-heading))))
  11064. (org-auto-repeat-maybe org-state))
  11065. ;; Fixup cursor location if close to the keyword.
  11066. (when (and (outline-on-heading-p)
  11067. (not (bolp))
  11068. (save-excursion (beginning-of-line 1)
  11069. (looking-at org-todo-line-regexp))
  11070. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11071. (goto-char (or (match-end 2) (match-end 1)))
  11072. (and (looking-at " ") (just-one-space)))
  11073. (when org-trigger-hook
  11074. (save-excursion
  11075. (run-hook-with-args 'org-trigger-hook change-plist)))
  11076. (when commentp (org-toggle-comment))))))))
  11077. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11078. "Block turning an entry into a TODO, using the hierarchy.
  11079. This checks whether the current task should be blocked from state
  11080. changes. Such blocking occurs when:
  11081. 1. The task has children which are not all in a completed state.
  11082. 2. A task has a parent with the property :ORDERED:, and there
  11083. are siblings prior to the current task with incomplete
  11084. status.
  11085. 3. The parent of the task is blocked because it has siblings that should
  11086. be done first, or is child of a block grandparent TODO entry."
  11087. (if (not org-enforce-todo-dependencies)
  11088. t ; if locally turned off don't block
  11089. (catch 'dont-block
  11090. ;; If this is not a todo state change, or if this entry is already DONE,
  11091. ;; do not block
  11092. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11093. (member (plist-get change-plist :from)
  11094. (cons 'done org-done-keywords))
  11095. (member (plist-get change-plist :to)
  11096. (cons 'todo org-not-done-keywords))
  11097. (not (plist-get change-plist :to)))
  11098. (throw 'dont-block t))
  11099. ;; If this task has children, and any are undone, it's blocked
  11100. (save-excursion
  11101. (org-back-to-heading t)
  11102. (let ((this-level (funcall outline-level)))
  11103. (outline-next-heading)
  11104. (let ((child-level (funcall outline-level)))
  11105. (while (and (not (eobp))
  11106. (> child-level this-level))
  11107. ;; this todo has children, check whether they are all
  11108. ;; completed
  11109. (when (and (not (org-entry-is-done-p))
  11110. (org-entry-is-todo-p))
  11111. (setq org-block-entry-blocking (org-get-heading))
  11112. (throw 'dont-block nil))
  11113. (outline-next-heading)
  11114. (setq child-level (funcall outline-level))))))
  11115. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11116. ;; any previous siblings are undone, it's blocked
  11117. (save-excursion
  11118. (org-back-to-heading t)
  11119. (let* ((pos (point))
  11120. (parent-pos (and (org-up-heading-safe) (point)))
  11121. (case-fold-search nil))
  11122. (unless parent-pos (throw 'dont-block t)) ; no parent
  11123. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11124. (forward-line 1)
  11125. (re-search-forward org-not-done-heading-regexp pos t))
  11126. (setq org-block-entry-blocking (match-string 0))
  11127. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11128. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11129. (while t
  11130. (goto-char parent-pos)
  11131. (unless (looking-at org-not-done-heading-regexp)
  11132. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11133. (setq pos (point))
  11134. (setq parent-pos (and (org-up-heading-safe) (point)))
  11135. (unless parent-pos (throw 'dont-block t)) ; no parent
  11136. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11137. (forward-line 1)
  11138. (re-search-forward org-not-done-heading-regexp pos t)
  11139. (setq org-block-entry-blocking (org-get-heading)))
  11140. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11141. (defcustom org-track-ordered-property-with-tag nil
  11142. "Should the ORDERED property also be shown as a tag?
  11143. The ORDERED property decides if an entry should require subtasks to be
  11144. completed in sequence. Since a property is not very visible, setting
  11145. this option means that toggling the ORDERED property with the command
  11146. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11147. not relevant for the behavior, but it makes things more visible.
  11148. Note that toggling the tag with tags commands will not change the property
  11149. and therefore not influence behavior!
  11150. This can be t, meaning the tag ORDERED should be used, It can also be a
  11151. string to select a different tag for this task."
  11152. :group 'org-todo
  11153. :type '(choice
  11154. (const :tag "No tracking" nil)
  11155. (const :tag "Track with ORDERED tag" t)
  11156. (string :tag "Use other tag")))
  11157. (defun org-toggle-ordered-property ()
  11158. "Toggle the ORDERED property of the current entry.
  11159. For better visibility, you can track the value of this property with a tag.
  11160. See variable `org-track-ordered-property-with-tag'."
  11161. (interactive)
  11162. (let* ((t1 org-track-ordered-property-with-tag)
  11163. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11164. (save-excursion
  11165. (org-back-to-heading)
  11166. (if (org-entry-get nil "ORDERED")
  11167. (progn
  11168. (org-delete-property "ORDERED")
  11169. (and tag (org-toggle-tag tag 'off))
  11170. (message "Subtasks can be completed in arbitrary order"))
  11171. (org-entry-put nil "ORDERED" "t")
  11172. (and tag (org-toggle-tag tag 'on))
  11173. (message "Subtasks must be completed in sequence")))))
  11174. (defun org-block-todo-from-checkboxes (change-plist)
  11175. "Block turning an entry into a TODO, using checkboxes.
  11176. This checks whether the current task should be blocked from state
  11177. changes because there are unchecked boxes in this entry."
  11178. (if (not org-enforce-todo-checkbox-dependencies)
  11179. t ; if locally turned off don't block
  11180. (catch 'dont-block
  11181. ;; If this is not a todo state change, or if this entry is already DONE,
  11182. ;; do not block
  11183. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11184. (member (plist-get change-plist :from)
  11185. (cons 'done org-done-keywords))
  11186. (member (plist-get change-plist :to)
  11187. (cons 'todo org-not-done-keywords))
  11188. (not (plist-get change-plist :to)))
  11189. (throw 'dont-block t))
  11190. ;; If this task has checkboxes that are not checked, it's blocked
  11191. (save-excursion
  11192. (org-back-to-heading t)
  11193. (let ((beg (point)) end)
  11194. (outline-next-heading)
  11195. (setq end (point))
  11196. (goto-char beg)
  11197. (when (org-list-search-forward
  11198. (concat (org-item-beginning-re)
  11199. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11200. "\\[[- ]\\]")
  11201. end t)
  11202. (when (boundp 'org-blocked-by-checkboxes)
  11203. (setq org-blocked-by-checkboxes t))
  11204. (throw 'dont-block nil))))
  11205. t))) ; do not block
  11206. (defun org-entry-blocked-p ()
  11207. "Non-nil if entry at point is blocked."
  11208. (and (not (org-entry-get nil "NOBLOCKING"))
  11209. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11210. (not (run-hook-with-args-until-failure
  11211. 'org-blocker-hook
  11212. (list :type 'todo-state-change
  11213. :position (point)
  11214. :from 'todo
  11215. :to 'done)))))
  11216. (defun org-update-statistics-cookies (all)
  11217. "Update the statistics cookie, either from TODO or from checkboxes.
  11218. This should be called with the cursor in a line with a statistics
  11219. cookie. When called with a \\[universal-argument] prefix, update
  11220. all statistics cookies in the buffer."
  11221. (interactive "P")
  11222. (if all
  11223. (progn
  11224. (org-update-checkbox-count 'all)
  11225. (org-map-entries 'org-update-parent-todo-statistics))
  11226. (if (not (org-at-heading-p))
  11227. (org-update-checkbox-count)
  11228. (let ((pos (point-marker))
  11229. end l1 l2)
  11230. (ignore-errors (org-back-to-heading t))
  11231. (if (not (org-at-heading-p))
  11232. (org-update-checkbox-count)
  11233. (setq l1 (org-outline-level))
  11234. (setq end (save-excursion
  11235. (outline-next-heading)
  11236. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11237. (point)))
  11238. (if (and (save-excursion
  11239. (re-search-forward
  11240. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11241. (not (save-excursion (re-search-forward
  11242. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11243. (org-update-checkbox-count)
  11244. (if (and l2 (> l2 l1))
  11245. (progn
  11246. (goto-char end)
  11247. (org-update-parent-todo-statistics))
  11248. (goto-char pos)
  11249. (beginning-of-line 1)
  11250. (while (re-search-forward
  11251. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11252. (point-at-eol) t)
  11253. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11254. (goto-char pos)
  11255. (move-marker pos nil)))))
  11256. (defvar org-entry-property-inherited-from) ;; defined below
  11257. (defun org-update-parent-todo-statistics ()
  11258. "Update any statistics cookie in the parent of the current headline.
  11259. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11260. the entire subtree and this will travel up the hierarchy and update
  11261. statistics everywhere."
  11262. (let* ((prop (save-excursion (org-up-heading-safe)
  11263. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11264. (recursive (or (not org-hierarchical-todo-statistics)
  11265. (and prop (string-match "\\<recursive\\>" prop))))
  11266. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11267. 0))
  11268. (first t)
  11269. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11270. level ltoggle l1 new ndel
  11271. (cnt-all 0) (cnt-done 0) is-percent kwd
  11272. checkbox-beg cookie-present)
  11273. (catch 'exit
  11274. (save-excursion
  11275. (beginning-of-line 1)
  11276. (setq ltoggle (funcall outline-level))
  11277. ;; Three situations are to consider:
  11278. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11279. ;; to the top-level ancestor on the headline;
  11280. ;; 2. If parent has "recursive" property, repeat up to the
  11281. ;; headline setting that property, taking inheritance into
  11282. ;; account;
  11283. ;; 3. Else, move up to direct parent and proceed only once.
  11284. (while (and (setq level (org-up-heading-safe))
  11285. (or recursive first)
  11286. (>= (point) lim))
  11287. (setq first nil cookie-present nil)
  11288. (unless (and level
  11289. (not (string-match
  11290. "\\<checkbox\\>"
  11291. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11292. "")))))
  11293. (throw 'exit nil))
  11294. (while (re-search-forward box-re (point-at-eol) t)
  11295. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11296. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11297. (save-match-data
  11298. (unless (outline-next-heading) (throw 'exit nil))
  11299. (while (and (looking-at org-complex-heading-regexp)
  11300. (> (setq l1 (length (match-string 1))) level))
  11301. (setq kwd (and (or recursive (= l1 ltoggle))
  11302. (match-string 2)))
  11303. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11304. (and (eq org-provide-todo-statistics t)
  11305. (or (member kwd org-done-keywords)))
  11306. (and (listp org-provide-todo-statistics)
  11307. (stringp (car org-provide-todo-statistics))
  11308. (or (member kwd org-provide-todo-statistics)
  11309. (member kwd org-done-keywords)))
  11310. (and (listp org-provide-todo-statistics)
  11311. (listp (car org-provide-todo-statistics))
  11312. (or (member kwd (car org-provide-todo-statistics))
  11313. (and (member kwd org-done-keywords)
  11314. (member kwd (cadr org-provide-todo-statistics))))))
  11315. (setq cnt-all (1+ cnt-all))
  11316. (and (eq org-provide-todo-statistics t)
  11317. kwd
  11318. (setq cnt-all (1+ cnt-all))))
  11319. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11320. (member kwd org-done-keywords))
  11321. (and (listp org-provide-todo-statistics)
  11322. (listp (car org-provide-todo-statistics))
  11323. (member kwd org-done-keywords)
  11324. (member kwd (cadr org-provide-todo-statistics)))
  11325. (and (listp org-provide-todo-statistics)
  11326. (stringp (car org-provide-todo-statistics))
  11327. (member kwd org-done-keywords)))
  11328. (setq cnt-done (1+ cnt-done)))
  11329. (outline-next-heading)))
  11330. (setq new
  11331. (if is-percent
  11332. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11333. (max 1 cnt-all)))
  11334. (format "[%d/%d]" cnt-done cnt-all))
  11335. ndel (- (match-end 0) checkbox-beg))
  11336. (goto-char checkbox-beg)
  11337. (insert new)
  11338. (delete-region (point) (+ (point) ndel))
  11339. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11340. (when cookie-present
  11341. (run-hook-with-args 'org-after-todo-statistics-hook
  11342. cnt-done (- cnt-all cnt-done))))))
  11343. (run-hooks 'org-todo-statistics-hook)))
  11344. (defvar org-after-todo-statistics-hook nil
  11345. "Hook that is called after a TODO statistics cookie has been updated.
  11346. Each function is called with two arguments: the number of not-done entries
  11347. and the number of done entries.
  11348. For example, the following function, when added to this hook, will switch
  11349. an entry to DONE when all children are done, and back to TODO when new
  11350. entries are set to a TODO status. Note that this hook is only called
  11351. when there is a statistics cookie in the headline!
  11352. (defun org-summary-todo (n-done n-not-done)
  11353. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11354. (let (org-log-done org-log-states) ; turn off logging
  11355. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11356. ")
  11357. (defvar org-todo-statistics-hook nil
  11358. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11359. This hook runs even if there is no statistics cookie present, in which case
  11360. `org-after-todo-statistics-hook' would not run.")
  11361. (defun org-todo-trigger-tag-changes (state)
  11362. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11363. (let ((l org-todo-state-tags-triggers)
  11364. changes)
  11365. (when (or (not state) (equal state ""))
  11366. (setq changes (append changes (cdr (assoc "" l)))))
  11367. (when (and (stringp state) (> (length state) 0))
  11368. (setq changes (append changes (cdr (assoc state l)))))
  11369. (when (member state org-not-done-keywords)
  11370. (setq changes (append changes (cdr (assq 'todo l)))))
  11371. (when (member state org-done-keywords)
  11372. (setq changes (append changes (cdr (assq 'done l)))))
  11373. (dolist (c changes)
  11374. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11375. (defun org-local-logging (value)
  11376. "Get logging settings from a property VALUE."
  11377. ;; Directly set the variables, they are already local.
  11378. (setq org-log-done nil
  11379. org-log-repeat nil
  11380. org-todo-log-states nil)
  11381. (dolist (w (split-string value))
  11382. (let (a)
  11383. (cond
  11384. ((setq a (assoc w org-startup-options))
  11385. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11386. (set (nth 1 a) (nth 2 a))))
  11387. ((setq a (org-extract-log-state-settings w))
  11388. (and (member (car a) org-todo-keywords-1)
  11389. (push a org-todo-log-states)))))))
  11390. (defun org-get-todo-sequence-head (kwd)
  11391. "Return the head of the TODO sequence to which KWD belongs.
  11392. If KWD is not set, check if there is a text property remembering the
  11393. right sequence."
  11394. (let (p)
  11395. (cond
  11396. ((not kwd)
  11397. (or (get-text-property (point-at-bol) 'org-todo-head)
  11398. (progn
  11399. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11400. nil (point-at-eol)))
  11401. (get-text-property p 'org-todo-head))))
  11402. ((not (member kwd org-todo-keywords-1))
  11403. (car org-todo-keywords-1))
  11404. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11405. (defun org-fast-todo-selection ()
  11406. "Fast TODO keyword selection with single keys.
  11407. Returns the new TODO keyword, or nil if no state change should occur."
  11408. (let* ((fulltable org-todo-key-alist)
  11409. (done-keywords org-done-keywords) ;; needed for the faces.
  11410. (maxlen (apply 'max (mapcar
  11411. (lambda (x)
  11412. (if (stringp (car x)) (string-width (car x)) 0))
  11413. fulltable)))
  11414. (expert nil)
  11415. (fwidth (+ maxlen 3 1 3))
  11416. (ncol (/ (- (window-width) 4) fwidth))
  11417. tg cnt e c tbl
  11418. groups ingroup)
  11419. (save-excursion
  11420. (save-window-excursion
  11421. (if expert
  11422. (set-buffer (get-buffer-create " *Org todo*"))
  11423. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11424. (erase-buffer)
  11425. (setq-local org-done-keywords done-keywords)
  11426. (setq tbl fulltable cnt 0)
  11427. (while (setq e (pop tbl))
  11428. (cond
  11429. ((equal e '(:startgroup))
  11430. (push '() groups) (setq ingroup t)
  11431. (unless (= cnt 0)
  11432. (setq cnt 0)
  11433. (insert "\n"))
  11434. (insert "{ "))
  11435. ((equal e '(:endgroup))
  11436. (setq ingroup nil cnt 0)
  11437. (insert "}\n"))
  11438. ((equal e '(:newline))
  11439. (unless (= cnt 0)
  11440. (setq cnt 0)
  11441. (insert "\n")
  11442. (setq e (car tbl))
  11443. (while (equal (car tbl) '(:newline))
  11444. (insert "\n")
  11445. (setq tbl (cdr tbl)))))
  11446. (t
  11447. (setq tg (car e) c (cdr e))
  11448. (when ingroup (push tg (car groups)))
  11449. (setq tg (org-add-props tg nil 'face
  11450. (org-get-todo-face tg)))
  11451. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11452. (insert "[" c "] " tg (make-string
  11453. (- fwidth 4 (length tg)) ?\ ))
  11454. (when (= (setq cnt (1+ cnt)) ncol)
  11455. (insert "\n")
  11456. (when ingroup (insert " "))
  11457. (setq cnt 0)))))
  11458. (insert "\n")
  11459. (goto-char (point-min))
  11460. (unless expert (org-fit-window-to-buffer))
  11461. (message "[a-z..]:Set [SPC]:clear")
  11462. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11463. (cond
  11464. ((or (= c ?\C-g)
  11465. (and (= c ?q) (not (rassoc c fulltable))))
  11466. (setq quit-flag t))
  11467. ((= c ?\ ) nil)
  11468. ((setq e (rassoc c fulltable) tg (car e))
  11469. tg)
  11470. (t (setq quit-flag t)))))))
  11471. (defun org-entry-is-todo-p ()
  11472. (member (org-get-todo-state) org-not-done-keywords))
  11473. (defun org-entry-is-done-p ()
  11474. (member (org-get-todo-state) org-done-keywords))
  11475. (defun org-get-todo-state ()
  11476. "Return the TODO keyword of the current subtree."
  11477. (save-excursion
  11478. (org-back-to-heading t)
  11479. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11480. (match-end 2)
  11481. (match-string 2))))
  11482. (defun org-at-date-range-p (&optional inactive-ok)
  11483. "Non-nil if point is inside a date range.
  11484. When optional argument INACTIVE-OK is non-nil, also consider
  11485. inactive time ranges.
  11486. When this function returns a non-nil value, match data is set
  11487. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11488. on INACTIVE-OK."
  11489. (interactive)
  11490. (save-excursion
  11491. (catch 'exit
  11492. (let ((pos (point)))
  11493. (skip-chars-backward "^[<\r\n")
  11494. (skip-chars-backward "<[")
  11495. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11496. (>= (match-end 0) pos)
  11497. (throw 'exit t))
  11498. (skip-chars-backward "^<[\r\n")
  11499. (skip-chars-backward "<[")
  11500. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11501. (>= (match-end 0) pos)
  11502. (throw 'exit t)))
  11503. nil)))
  11504. (defun org-get-repeat (&optional timestamp)
  11505. "Check if there is a time-stamp with repeater in this entry.
  11506. Return the repeater, as a string, or nil. Also return nil when
  11507. this function is called before first heading.
  11508. When optional argument TIMESTAMP is a string, extract the
  11509. repeater from there instead."
  11510. (save-match-data
  11511. (cond (timestamp
  11512. (and (string-match org-repeat-re timestamp)
  11513. (match-string-no-properties 1 timestamp)))
  11514. ((org-before-first-heading-p) nil)
  11515. (t
  11516. (save-excursion
  11517. (org-back-to-heading t)
  11518. (let ((end (org-entry-end-position)))
  11519. (catch :repeat
  11520. (while (re-search-forward org-repeat-re end t)
  11521. (when (save-match-data (org-at-timestamp-p 'agenda))
  11522. (throw :repeat (match-string-no-properties 1)))))))))))
  11523. (defvar org-last-changed-timestamp)
  11524. (defvar org-last-inserted-timestamp)
  11525. (defvar org-log-post-message)
  11526. (defvar org-log-note-purpose)
  11527. (defvar org-log-note-how nil)
  11528. (defvar org-log-note-extra)
  11529. (defun org-auto-repeat-maybe (done-word)
  11530. "Check if the current headline contains a repeated time-stamp.
  11531. If yes, set TODO state back to what it was and change the base date
  11532. of repeating deadline/scheduled time stamps to new date.
  11533. This function is run automatically after each state change to a DONE state."
  11534. (let* ((repeat (org-get-repeat))
  11535. (aa (assoc org-last-state org-todo-kwd-alist))
  11536. (interpret (nth 1 aa))
  11537. (head (nth 2 aa))
  11538. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11539. (msg "Entry repeats: ")
  11540. (org-log-done nil)
  11541. (org-todo-log-states nil)
  11542. (end (copy-marker (org-entry-end-position))))
  11543. (unwind-protect
  11544. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11545. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11546. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11547. org-todo-repeat-to-state)))
  11548. (org-todo (cond
  11549. ((and to-state (member to-state org-todo-keywords-1))
  11550. to-state)
  11551. ((eq interpret 'type) org-last-state)
  11552. (head)
  11553. (t 'none))))
  11554. (org-back-to-heading t)
  11555. (org-add-planning-info nil nil 'closed)
  11556. ;; When `org-log-repeat' is non-nil or entry contains
  11557. ;; a clock, set LAST_REPEAT property.
  11558. (when (or org-log-repeat
  11559. (catch :clock
  11560. (save-excursion
  11561. (while (re-search-forward org-clock-line-re end t)
  11562. (when (org-at-clock-log-p) (throw :clock t))))))
  11563. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11564. (org-time-stamp-format t t)
  11565. (current-time))))
  11566. (when org-log-repeat
  11567. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11568. (memq 'org-add-log-note post-command-hook))
  11569. ;; We are already setup for some record.
  11570. (when (eq org-log-repeat 'note)
  11571. ;; Make sure we take a note, not only a time stamp.
  11572. (setq org-log-note-how 'note))
  11573. ;; Set up for taking a record.
  11574. (org-add-log-setup 'state
  11575. (or done-word (car org-done-keywords))
  11576. org-last-state
  11577. org-log-repeat)))
  11578. (let ((planning-re (regexp-opt
  11579. (list org-scheduled-string org-deadline-string))))
  11580. (while (re-search-forward org-ts-regexp end t)
  11581. (let* ((ts (match-string 0))
  11582. (planning? (org-at-planning-p))
  11583. (type (if (not planning?) "Plain:"
  11584. (save-excursion
  11585. (re-search-backward
  11586. planning-re (line-beginning-position) t)
  11587. (match-string 0)))))
  11588. (cond
  11589. ;; Ignore fake time-stamps (e.g., within comments).
  11590. ((not (org-at-timestamp-p 'agenda)))
  11591. ;; Time-stamps without a repeater are usually
  11592. ;; skipped. However, a SCHEDULED time-stamp without
  11593. ;; one is removed, as they are no longer relevant.
  11594. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11595. ts))
  11596. (when (equal type org-scheduled-string)
  11597. (org-remove-timestamp-with-keyword type)))
  11598. (t
  11599. (let ((n (string-to-number (match-string 2 ts)))
  11600. (what (match-string 3 ts)))
  11601. (when (equal what "w") (setq n (* n 7) what "d"))
  11602. (when (and (equal what "h")
  11603. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11604. ts)))
  11605. (user-error
  11606. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11607. has been set"
  11608. n))
  11609. ;; Preparation, see if we need to modify the start
  11610. ;; date for the change.
  11611. (when (match-end 1)
  11612. (let ((time (save-match-data
  11613. (org-time-string-to-time ts))))
  11614. (cond
  11615. ((equal (match-string 1 ts) ".")
  11616. ;; Shift starting date to today
  11617. (org-timestamp-change
  11618. (- (org-today) (time-to-days time))
  11619. 'day))
  11620. ((equal (match-string 1 ts) "+")
  11621. (let ((nshiftmax 10)
  11622. (nshift 0))
  11623. (while (or (= nshift 0)
  11624. (not (time-less-p (current-time) time)))
  11625. (when (= (cl-incf nshift) nshiftmax)
  11626. (or (y-or-n-p
  11627. (format "%d repeater intervals were not \
  11628. enough to shift date past today. Continue? "
  11629. nshift))
  11630. (user-error "Abort")))
  11631. (org-timestamp-change n (cdr (assoc what whata)))
  11632. (org-in-regexp org-ts-regexp3)
  11633. (setq ts (match-string 1))
  11634. (setq time
  11635. (save-match-data
  11636. (org-time-string-to-time ts)))))
  11637. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11638. ;; Rematch, so that we have everything in place
  11639. ;; for the real shift.
  11640. (org-in-regexp org-ts-regexp3)
  11641. (setq ts (match-string 1))
  11642. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11643. ts)))))
  11644. (save-excursion
  11645. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11646. (setq msg
  11647. (concat
  11648. msg type " " org-last-changed-timestamp " "))))))))
  11649. (setq org-log-post-message msg)
  11650. (message "%s" msg))
  11651. (set-marker end nil))))
  11652. (defun org-show-todo-tree (arg)
  11653. "Make a compact tree which shows all headlines marked with TODO.
  11654. The tree will show the lines where the regexp matches, and all higher
  11655. headlines above the match.
  11656. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11657. With a numeric prefix N, construct a sparse tree for the Nth element
  11658. of `org-todo-keywords-1'."
  11659. (interactive "P")
  11660. (let ((case-fold-search nil)
  11661. (kwd-re
  11662. (cond ((null arg) org-not-done-regexp)
  11663. ((equal arg '(4))
  11664. (let ((kwd
  11665. (completing-read "Keyword (or KWD1|KWD2|...): "
  11666. (mapcar #'list org-todo-keywords-1))))
  11667. (concat "\\("
  11668. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11669. "\\)\\>")))
  11670. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11671. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11672. org-todo-keywords-1)))
  11673. (t (user-error "Invalid prefix argument: %s" arg)))))
  11674. (message "%d TODO entries found"
  11675. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11676. (defun org--deadline-or-schedule (arg type time)
  11677. "Insert DEADLINE or SCHEDULE information in current entry.
  11678. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11679. `org-schedule' for information about ARG and TIME arguments."
  11680. (let* ((deadline? (eq type 'deadline))
  11681. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11682. (log (if deadline? org-log-redeadline org-log-reschedule))
  11683. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11684. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11685. ;; Save repeater cookie from either TIME or current scheduled
  11686. ;; time stamp. We are going to insert it back at the end of
  11687. ;; the process.
  11688. (repeater (or (and (org-string-nw-p time)
  11689. ;; We use `org-repeat-re' because we need
  11690. ;; to tell the difference between a real
  11691. ;; repeater and a time delta, e.g. "+2d".
  11692. (string-match org-repeat-re time)
  11693. (match-string 1 time))
  11694. (and (org-string-nw-p old-date)
  11695. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11696. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11697. old-date)
  11698. (match-string 1 old-date)))))
  11699. (pcase arg
  11700. (`(4)
  11701. (when (and old-date log)
  11702. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11703. nil old-date log))
  11704. (org-remove-timestamp-with-keyword keyword)
  11705. (message (if deadline? "Item no longer has a deadline."
  11706. "Item is no longer scheduled.")))
  11707. (`(16)
  11708. (save-excursion
  11709. (org-back-to-heading t)
  11710. (let ((regexp (if deadline? org-deadline-time-regexp
  11711. org-scheduled-time-regexp)))
  11712. (if (not (re-search-forward regexp (line-end-position 2) t))
  11713. (user-error (if deadline? "No deadline information to update"
  11714. "No scheduled information to update"))
  11715. (let* ((rpl0 (match-string 1))
  11716. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11717. (msg (if deadline? "Warn starting from" "Delay until")))
  11718. (replace-match
  11719. (concat keyword
  11720. " <" rpl
  11721. (format " -%dd"
  11722. (abs (- (time-to-days
  11723. (save-match-data
  11724. (org-read-date
  11725. nil t nil msg old-date-time)))
  11726. (time-to-days old-date-time))))
  11727. ">") t t))))))
  11728. (_
  11729. (org-add-planning-info type time 'closed)
  11730. (when (and old-date
  11731. log
  11732. (not (equal old-date org-last-inserted-timestamp)))
  11733. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11734. org-last-inserted-timestamp
  11735. old-date
  11736. log))
  11737. (when repeater
  11738. (save-excursion
  11739. (org-back-to-heading t)
  11740. (when (re-search-forward
  11741. (concat keyword " " org-last-inserted-timestamp)
  11742. (line-end-position 2)
  11743. t)
  11744. (goto-char (1- (match-end 0)))
  11745. (insert " " repeater)
  11746. (setq org-last-inserted-timestamp
  11747. (concat (substring org-last-inserted-timestamp 0 -1)
  11748. " " repeater
  11749. (substring org-last-inserted-timestamp -1))))))
  11750. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11751. org-last-inserted-timestamp)))))
  11752. (defun org-deadline (arg &optional time)
  11753. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11754. With one universal prefix argument, remove any deadline from the item.
  11755. With two universal prefix arguments, prompt for a warning delay.
  11756. With argument TIME, set the deadline at the corresponding date. TIME
  11757. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11758. (interactive "P")
  11759. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11760. (org-map-entries
  11761. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11762. nil
  11763. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11764. 'region-start-level
  11765. 'region)
  11766. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11767. (org--deadline-or-schedule arg 'deadline time)))
  11768. (defun org-schedule (arg &optional time)
  11769. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11770. With one universal prefix argument, remove any scheduling date from the item.
  11771. With two universal prefix arguments, prompt for a delay cookie.
  11772. With argument TIME, scheduled at the corresponding date. TIME can
  11773. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11774. (interactive "P")
  11775. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11776. (org-map-entries
  11777. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11778. nil
  11779. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11780. 'region-start-level
  11781. 'region)
  11782. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11783. (org--deadline-or-schedule arg 'scheduled time)))
  11784. (defun org-get-scheduled-time (pom &optional inherit)
  11785. "Get the scheduled time as a time tuple, of a format suitable
  11786. for calling org-schedule with, or if there is no scheduling,
  11787. returns nil."
  11788. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11789. (when time
  11790. (apply 'encode-time (org-parse-time-string time)))))
  11791. (defun org-get-deadline-time (pom &optional inherit)
  11792. "Get the deadline as a time tuple, of a format suitable for
  11793. calling org-deadline with, or if there is no scheduling, returns
  11794. nil."
  11795. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11796. (when time
  11797. (apply 'encode-time (org-parse-time-string time)))))
  11798. (defun org-remove-timestamp-with-keyword (keyword)
  11799. "Remove all time stamps with KEYWORD in the current entry."
  11800. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11801. beg)
  11802. (save-excursion
  11803. (org-back-to-heading t)
  11804. (setq beg (point))
  11805. (outline-next-heading)
  11806. (while (re-search-backward re beg t)
  11807. (replace-match "")
  11808. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11809. (equal (char-before) ?\ ))
  11810. (backward-delete-char 1)
  11811. (when (string-match "^[ \t]*$" (buffer-substring
  11812. (point-at-bol) (point-at-eol)))
  11813. (delete-region (point-at-bol)
  11814. (min (point-max) (1+ (point-at-eol))))))))))
  11815. (defvar org-time-was-given) ; dynamically scoped parameter
  11816. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11817. (defun org-at-planning-p ()
  11818. "Non-nil when point is on a planning info line."
  11819. ;; This is as accurate and faster than `org-element-at-point' since
  11820. ;; planning info location is fixed in the section.
  11821. (org-with-wide-buffer
  11822. (beginning-of-line)
  11823. (and (looking-at-p org-planning-line-re)
  11824. (eq (point)
  11825. (ignore-errors
  11826. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11827. (org-back-to-heading t)
  11828. (org-with-limited-levels (org-back-to-heading t)))
  11829. (line-beginning-position 2))))))
  11830. (defun org-add-planning-info (what &optional time &rest remove)
  11831. "Insert new timestamp with keyword in the planning line.
  11832. WHAT indicates what kind of time stamp to add. It is a symbol
  11833. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11834. the time to use. If none is given, the user is prompted for
  11835. a date. REMOVE indicates what kind of entries to remove. An old
  11836. WHAT entry will also be removed."
  11837. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11838. (catch 'exit
  11839. (when (and (memq what '(scheduled deadline))
  11840. (or (not time)
  11841. (and (stringp time)
  11842. (string-match "^[-+]+[0-9]" time))))
  11843. ;; Try to get a default date/time from existing timestamp
  11844. (save-excursion
  11845. (org-back-to-heading t)
  11846. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11847. (when (re-search-forward (if (eq what 'scheduled)
  11848. org-scheduled-time-regexp
  11849. org-deadline-time-regexp)
  11850. end t)
  11851. (setq ts (match-string 1)
  11852. default-time (apply 'encode-time (org-parse-time-string ts))
  11853. default-input (and ts (org-get-compact-tod ts)))))))
  11854. (when what
  11855. (setq time
  11856. (if (stringp time)
  11857. ;; This is a string (relative or absolute), set
  11858. ;; proper date.
  11859. (apply #'encode-time
  11860. (org-read-date-analyze
  11861. time default-time (decode-time default-time)))
  11862. ;; If necessary, get the time from the user
  11863. (or time (org-read-date nil 'to-time nil nil
  11864. default-time default-input)))))
  11865. (org-with-wide-buffer
  11866. (org-back-to-heading t)
  11867. (forward-line)
  11868. (unless (bolp) (insert "\n"))
  11869. (cond ((looking-at-p org-planning-line-re)
  11870. ;; Move to current indentation.
  11871. (skip-chars-forward " \t")
  11872. ;; Check if we have to remove something.
  11873. (dolist (type (if what (cons what remove) remove))
  11874. (save-excursion
  11875. (when (re-search-forward
  11876. (cl-case type
  11877. (closed org-closed-time-regexp)
  11878. (deadline org-deadline-time-regexp)
  11879. (scheduled org-scheduled-time-regexp)
  11880. (otherwise
  11881. (error "Invalid planning type: %s" type)))
  11882. (line-end-position) t)
  11883. ;; Delete until next keyword or end of line.
  11884. (delete-region
  11885. (match-beginning 0)
  11886. (if (re-search-forward org-keyword-time-not-clock-regexp
  11887. (line-end-position)
  11888. t)
  11889. (match-beginning 0)
  11890. (line-end-position))))))
  11891. ;; If there is nothing more to add and no more keyword
  11892. ;; is left, remove the line completely.
  11893. (if (and (looking-at-p "[ \t]*$") (not what))
  11894. (delete-region (line-beginning-position)
  11895. (line-beginning-position 2))
  11896. ;; If we removed last keyword, do not leave trailing
  11897. ;; white space at the end of line.
  11898. (let ((p (point)))
  11899. (save-excursion
  11900. (end-of-line)
  11901. (unless (= (skip-chars-backward " \t" p) 0)
  11902. (delete-region (point) (line-end-position)))))))
  11903. ((not what) (throw 'exit nil)) ; Nothing to do.
  11904. (t (insert-before-markers "\n")
  11905. (backward-char 1)
  11906. (when org-adapt-indentation
  11907. (indent-to-column (1+ (org-outline-level))))))
  11908. (when what
  11909. ;; Insert planning keyword.
  11910. (insert (cl-case what
  11911. (closed org-closed-string)
  11912. (deadline org-deadline-string)
  11913. (scheduled org-scheduled-string)
  11914. (otherwise (error "Invalid planning type: %s" what)))
  11915. " ")
  11916. ;; Insert associated timestamp.
  11917. (let ((ts (org-insert-time-stamp
  11918. time
  11919. (or org-time-was-given
  11920. (and (eq what 'closed) org-log-done-with-time))
  11921. (eq what 'closed)
  11922. nil nil (list org-end-time-was-given))))
  11923. (unless (eolp) (insert " "))
  11924. ts))))))
  11925. (defvar org-log-note-marker (make-marker)
  11926. "Marker pointing at the entry where the note is to be inserted.")
  11927. (defvar org-log-note-purpose nil)
  11928. (defvar org-log-note-state nil)
  11929. (defvar org-log-note-previous-state nil)
  11930. (defvar org-log-note-extra nil)
  11931. (defvar org-log-note-window-configuration nil)
  11932. (defvar org-log-note-return-to (make-marker))
  11933. (defvar org-log-note-effective-time nil
  11934. "Remembered current time so that dynamically scoped
  11935. `org-extend-today-until' affects timestamps in state change log")
  11936. (defvar org-log-post-message nil
  11937. "Message to be displayed after a log note has been stored.
  11938. The auto-repeater uses this.")
  11939. (defun org-add-note ()
  11940. "Add a note to the current entry.
  11941. This is done in the same way as adding a state change note."
  11942. (interactive)
  11943. (org-add-log-setup 'note))
  11944. (defun org-log-beginning (&optional create)
  11945. "Return expected start of log notes in current entry.
  11946. When optional argument CREATE is non-nil, the function creates
  11947. a drawer to store notes, if necessary. Returned position ignores
  11948. narrowing."
  11949. (org-with-wide-buffer
  11950. (let ((drawer (org-log-into-drawer)))
  11951. (cond
  11952. (drawer
  11953. (org-end-of-meta-data)
  11954. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11955. (end (if (org-at-heading-p) (point)
  11956. (save-excursion (outline-next-heading) (point))))
  11957. (case-fold-search t))
  11958. (catch 'exit
  11959. ;; Try to find existing drawer.
  11960. (while (re-search-forward regexp end t)
  11961. (let ((element (org-element-at-point)))
  11962. (when (eq (org-element-type element) 'drawer)
  11963. (let ((cend (org-element-property :contents-end element)))
  11964. (when (and (not org-log-states-order-reversed) cend)
  11965. (goto-char cend)))
  11966. (throw 'exit nil))))
  11967. ;; No drawer found. Create one, if permitted.
  11968. (when create
  11969. (unless (bolp) (insert "\n"))
  11970. (let ((beg (point)))
  11971. (insert ":" drawer ":\n:END:\n")
  11972. (org-indent-region beg (point)))
  11973. (end-of-line -1)))))
  11974. (t
  11975. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11976. (skip-chars-forward " \t\n")
  11977. (beginning-of-line)
  11978. (unless org-log-states-order-reversed
  11979. (org-skip-over-state-notes)
  11980. (skip-chars-backward " \t\n")
  11981. (forward-line)))))
  11982. (if (bolp) (point) (line-beginning-position 2))))
  11983. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11984. "Set up the post command hook to take a note.
  11985. If this is about to TODO state change, the new state is expected in STATE.
  11986. HOW is an indicator what kind of note should be created.
  11987. EXTRA is additional text that will be inserted into the notes buffer."
  11988. (move-marker org-log-note-marker (point))
  11989. (setq org-log-note-purpose purpose
  11990. org-log-note-state state
  11991. org-log-note-previous-state prev-state
  11992. org-log-note-how how
  11993. org-log-note-extra extra
  11994. org-log-note-effective-time (org-current-effective-time))
  11995. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11996. (defun org-skip-over-state-notes ()
  11997. "Skip past the list of State notes in an entry."
  11998. (when (ignore-errors (goto-char (org-in-item-p)))
  11999. (let* ((struct (org-list-struct))
  12000. (prevs (org-list-prevs-alist struct))
  12001. (regexp
  12002. (concat "[ \t]*- +"
  12003. (replace-regexp-in-string
  12004. " +" " +"
  12005. (org-replace-escapes
  12006. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12007. `(("%d" . ,org-ts-regexp-inactive)
  12008. ("%D" . ,org-ts-regexp)
  12009. ("%s" . "\"\\S-+\"")
  12010. ("%S" . "\"\\S-+\"")
  12011. ("%t" . ,org-ts-regexp-inactive)
  12012. ("%T" . ,org-ts-regexp)
  12013. ("%u" . ".*?")
  12014. ("%U" . ".*?")))))))
  12015. (while (looking-at-p regexp)
  12016. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12017. (org-list-get-item-end (point) struct)))))))
  12018. (defun org-add-log-note (&optional _purpose)
  12019. "Pop up a window for taking a note, and add this note later."
  12020. (remove-hook 'post-command-hook 'org-add-log-note)
  12021. (setq org-log-note-window-configuration (current-window-configuration))
  12022. (delete-other-windows)
  12023. (move-marker org-log-note-return-to (point))
  12024. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12025. (goto-char org-log-note-marker)
  12026. (org-switch-to-buffer-other-window "*Org Note*")
  12027. (erase-buffer)
  12028. (if (memq org-log-note-how '(time state))
  12029. (org-store-log-note)
  12030. (let ((org-inhibit-startup t)) (org-mode))
  12031. (insert (format "# Insert note for %s.
  12032. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12033. (cond
  12034. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12035. ((eq org-log-note-purpose 'done) "closed todo item")
  12036. ((eq org-log-note-purpose 'state)
  12037. (format "state change from \"%s\" to \"%s\""
  12038. (or org-log-note-previous-state "")
  12039. (or org-log-note-state "")))
  12040. ((eq org-log-note-purpose 'reschedule)
  12041. "rescheduling")
  12042. ((eq org-log-note-purpose 'delschedule)
  12043. "no longer scheduled")
  12044. ((eq org-log-note-purpose 'redeadline)
  12045. "changing deadline")
  12046. ((eq org-log-note-purpose 'deldeadline)
  12047. "removing deadline")
  12048. ((eq org-log-note-purpose 'refile)
  12049. "refiling")
  12050. ((eq org-log-note-purpose 'note)
  12051. "this entry")
  12052. (t (error "This should not happen")))))
  12053. (when org-log-note-extra (insert org-log-note-extra))
  12054. (setq-local org-finish-function 'org-store-log-note)
  12055. (run-hooks 'org-log-buffer-setup-hook)))
  12056. (defvar org-note-abort nil) ; dynamically scoped
  12057. (defun org-store-log-note ()
  12058. "Finish taking a log note, and insert it to where it belongs."
  12059. (let ((txt (prog1 (buffer-string)
  12060. (kill-buffer)))
  12061. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12062. lines)
  12063. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12064. (setq txt (replace-match "" t t txt)))
  12065. (when (string-match "\\s-+\\'" txt)
  12066. (setq txt (replace-match "" t t txt)))
  12067. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12068. (when (org-string-nw-p note)
  12069. (setq note
  12070. (org-replace-escapes
  12071. note
  12072. (list (cons "%u" (user-login-name))
  12073. (cons "%U" user-full-name)
  12074. (cons "%t" (format-time-string
  12075. (org-time-stamp-format 'long 'inactive)
  12076. org-log-note-effective-time))
  12077. (cons "%T" (format-time-string
  12078. (org-time-stamp-format 'long nil)
  12079. org-log-note-effective-time))
  12080. (cons "%d" (format-time-string
  12081. (org-time-stamp-format nil 'inactive)
  12082. org-log-note-effective-time))
  12083. (cons "%D" (format-time-string
  12084. (org-time-stamp-format nil nil)
  12085. org-log-note-effective-time))
  12086. (cons "%s" (cond
  12087. ((not org-log-note-state) "")
  12088. ((string-match-p org-ts-regexp
  12089. org-log-note-state)
  12090. (format "\"[%s]\""
  12091. (substring org-log-note-state 1 -1)))
  12092. (t (format "\"%s\"" org-log-note-state))))
  12093. (cons "%S"
  12094. (cond
  12095. ((not org-log-note-previous-state) "")
  12096. ((string-match-p org-ts-regexp
  12097. org-log-note-previous-state)
  12098. (format "\"[%s]\""
  12099. (substring
  12100. org-log-note-previous-state 1 -1)))
  12101. (t (format "\"%s\""
  12102. org-log-note-previous-state)))))))
  12103. (when lines (setq note (concat note " \\\\")))
  12104. (push note lines))
  12105. (when (and lines (not org-note-abort))
  12106. (with-current-buffer (marker-buffer org-log-note-marker)
  12107. (org-with-wide-buffer
  12108. ;; Find location for the new note.
  12109. (goto-char org-log-note-marker)
  12110. (set-marker org-log-note-marker nil)
  12111. ;; Note associated to a clock is to be located right after
  12112. ;; the clock. Do not move point.
  12113. (unless (eq org-log-note-purpose 'clock-out)
  12114. (goto-char (org-log-beginning t)))
  12115. ;; Make sure point is at the beginning of an empty line.
  12116. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12117. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12118. ;; In an existing list, add a new item at the top level.
  12119. ;; Otherwise, indent line like a regular one.
  12120. (let ((itemp (org-in-item-p)))
  12121. (if itemp
  12122. (indent-line-to
  12123. (let ((struct (save-excursion
  12124. (goto-char itemp) (org-list-struct))))
  12125. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12126. (org-indent-line)))
  12127. (insert (org-list-bullet-string "-") (pop lines))
  12128. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12129. (dolist (line lines)
  12130. (insert "\n")
  12131. (indent-line-to ind)
  12132. (insert line)))
  12133. (message "Note stored")
  12134. (org-back-to-heading t)
  12135. (org-cycle-hide-drawers 'children))
  12136. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12137. ;; from within `org-add-log-note' because `buffer-undo-list'
  12138. ;; is then modified outside of `org-with-remote-undo'.
  12139. (when (eq this-command 'org-agenda-todo)
  12140. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12141. ;; Don't add undo information when called from `org-agenda-todo'.
  12142. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12143. (set-window-configuration org-log-note-window-configuration)
  12144. (with-current-buffer (marker-buffer org-log-note-return-to)
  12145. (goto-char org-log-note-return-to))
  12146. (move-marker org-log-note-return-to nil)
  12147. (when org-log-post-message (message "%s" org-log-post-message))))
  12148. (defun org-remove-empty-drawer-at (pos)
  12149. "Remove an empty drawer at position POS.
  12150. POS may also be a marker."
  12151. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12152. (org-with-wide-buffer
  12153. (goto-char pos)
  12154. (let ((drawer (org-element-at-point)))
  12155. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12156. (not (org-element-property :contents-begin drawer)))
  12157. (delete-region (org-element-property :begin drawer)
  12158. (progn (goto-char (org-element-property :end drawer))
  12159. (skip-chars-backward " \r\t\n")
  12160. (forward-line)
  12161. (point))))))))
  12162. (defvar org-ts-type nil)
  12163. (defun org-sparse-tree (&optional arg type)
  12164. "Create a sparse tree, prompt for the details.
  12165. This command can create sparse trees. You first need to select the type
  12166. of match used to create the tree:
  12167. t Show all TODO entries.
  12168. T Show entries with a specific TODO keyword.
  12169. m Show entries selected by a tags/property match.
  12170. p Enter a property name and its value (both with completion on existing
  12171. names/values) and show entries with that property.
  12172. r Show entries matching a regular expression (`/' can be used as well).
  12173. b Show deadlines and scheduled items before a date.
  12174. a Show deadlines and scheduled items after a date.
  12175. d Show deadlines due within `org-deadline-warning-days'.
  12176. D Show deadlines and scheduled items between a date range."
  12177. (interactive "P")
  12178. (setq type (or type org-sparse-tree-default-date-type))
  12179. (setq org-ts-type type)
  12180. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12181. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12182. \[c]ycle through date types: %s"
  12183. (cl-case type
  12184. (all "all timestamps")
  12185. (scheduled "only scheduled")
  12186. (deadline "only deadline")
  12187. (active "only active timestamps")
  12188. (inactive "only inactive timestamps")
  12189. (closed "with a closed time-stamp")
  12190. (otherwise "scheduled/deadline")))
  12191. (let ((answer (read-char-exclusive)))
  12192. (cl-case answer
  12193. (?c
  12194. (org-sparse-tree
  12195. arg
  12196. (cadr
  12197. (memq type '(nil all scheduled deadline active inactive closed)))))
  12198. (?d (call-interactively 'org-check-deadlines))
  12199. (?b (call-interactively 'org-check-before-date))
  12200. (?a (call-interactively 'org-check-after-date))
  12201. (?D (call-interactively 'org-check-dates-range))
  12202. (?t (call-interactively 'org-show-todo-tree))
  12203. (?T (org-show-todo-tree '(4)))
  12204. (?m (call-interactively 'org-match-sparse-tree))
  12205. ((?p ?P)
  12206. (let* ((kwd (completing-read
  12207. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12208. (value (completing-read
  12209. "Value: " (mapcar #'list (org-property-values kwd)))))
  12210. (unless (string-match "\\`{.*}\\'" value)
  12211. (setq value (concat "\"" value "\"")))
  12212. (org-match-sparse-tree arg (concat kwd "=" value))))
  12213. ((?r ?R ?/) (call-interactively 'org-occur))
  12214. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12215. (defvar-local org-occur-highlights nil
  12216. "List of overlays used for occur matches.")
  12217. (defvar-local org-occur-parameters nil
  12218. "Parameters of the active org-occur calls.
  12219. This is a list, each call to org-occur pushes as cons cell,
  12220. containing the regular expression and the callback, onto the list.
  12221. The list can contain several entries if `org-occur' has been called
  12222. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12223. will only contain one set of parameters. When the highlights are
  12224. removed (for example with `C-c C-c', or with the next edit (depending
  12225. on `org-remove-highlights-with-change'), this variable is emptied
  12226. as well.")
  12227. (defun org-occur (regexp &optional keep-previous callback)
  12228. "Make a compact tree which shows all matches of REGEXP.
  12229. The tree will show the lines where the regexp matches, and any other context
  12230. defined in `org-show-context-detail', which see.
  12231. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12232. done by a previous call to `org-occur' will be kept, to allow stacking of
  12233. calls to this command.
  12234. Optional argument CALLBACK can be a function of no argument. In this case,
  12235. it is called with point at the end of the match, match data being set
  12236. accordingly. Current match is shown only if the return value is non-nil.
  12237. The function must neither move point nor alter narrowing."
  12238. (interactive "sRegexp: \nP")
  12239. (when (equal regexp "")
  12240. (user-error "Regexp cannot be empty"))
  12241. (unless keep-previous
  12242. (org-remove-occur-highlights nil nil t))
  12243. (push (cons regexp callback) org-occur-parameters)
  12244. (let ((cnt 0))
  12245. (save-excursion
  12246. (goto-char (point-min))
  12247. (when (or (not keep-previous) ; do not want to keep
  12248. (not org-occur-highlights)) ; no previous matches
  12249. ;; hide everything
  12250. (org-overview))
  12251. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12252. (isearch-no-upper-case-p regexp t)
  12253. org-occur-case-fold-search)))
  12254. (while (re-search-forward regexp nil t)
  12255. (when (or (not callback)
  12256. (save-match-data (funcall callback)))
  12257. (setq cnt (1+ cnt))
  12258. (when org-highlight-sparse-tree-matches
  12259. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12260. (org-show-context 'occur-tree)))))
  12261. (when org-remove-highlights-with-change
  12262. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12263. nil 'local))
  12264. (unless org-sparse-tree-open-archived-trees
  12265. (org-hide-archived-subtrees (point-min) (point-max)))
  12266. (run-hooks 'org-occur-hook)
  12267. (when (called-interactively-p 'interactive)
  12268. (message "%d match(es) for regexp %s" cnt regexp))
  12269. cnt))
  12270. (defun org-occur-next-match (&optional n _reset)
  12271. "Function for `next-error-function' to find sparse tree matches.
  12272. N is the number of matches to move, when negative move backwards.
  12273. This function always goes back to the starting point when no
  12274. match is found."
  12275. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12276. (search-func (if (< n 0)
  12277. 'previous-single-char-property-change
  12278. 'next-single-char-property-change))
  12279. (n (abs n))
  12280. (pos (point))
  12281. p1)
  12282. (catch 'exit
  12283. (while (setq p1 (funcall search-func (point) 'org-type))
  12284. (when (equal p1 limit)
  12285. (goto-char pos)
  12286. (user-error "No more matches"))
  12287. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12288. (setq n (1- n))
  12289. (when (= n 0)
  12290. (goto-char p1)
  12291. (throw 'exit (point))))
  12292. (goto-char p1))
  12293. (goto-char p1)
  12294. (user-error "No more matches"))))
  12295. (defun org-show-context (&optional key)
  12296. "Make sure point and context are visible.
  12297. Optional argument KEY, when non-nil, is a symbol. See
  12298. `org-show-context-detail' for allowed values and how much is to
  12299. be shown."
  12300. (org-show-set-visibility
  12301. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12302. ((cdr (assq key org-show-context-detail)))
  12303. (t (cdr (assq 'default org-show-context-detail))))))
  12304. (defun org-show-set-visibility (detail)
  12305. "Set visibility around point according to DETAIL.
  12306. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12307. `tree', `canonical' or t. See `org-show-context-detail' for more
  12308. information."
  12309. ;; Show current heading and possibly its entry, following headline
  12310. ;; or all children.
  12311. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12312. (org-flag-heading nil)
  12313. (org-show-entry)
  12314. ;; If point is hidden within a drawer or a block, make sure to
  12315. ;; expose it.
  12316. (dolist (o (overlays-at (point)))
  12317. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12318. (delete-overlay o)))
  12319. (unless (org-before-first-heading-p)
  12320. (org-with-limited-levels
  12321. (cl-case detail
  12322. ((tree canonical t) (org-show-children))
  12323. ((nil minimal ancestors))
  12324. (t (save-excursion
  12325. (outline-next-heading)
  12326. (org-flag-heading nil)))))))
  12327. ;; Show all siblings.
  12328. (when (eq detail 'lineage) (org-show-siblings))
  12329. ;; Show ancestors, possibly with their children.
  12330. (when (memq detail '(ancestors lineage tree canonical t))
  12331. (save-excursion
  12332. (while (org-up-heading-safe)
  12333. (org-flag-heading nil)
  12334. (when (memq detail '(canonical t)) (org-show-entry))
  12335. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12336. (defvar org-reveal-start-hook nil
  12337. "Hook run before revealing a location.")
  12338. (defun org-reveal (&optional siblings)
  12339. "Show current entry, hierarchy above it, and the following headline.
  12340. This can be used to show a consistent set of context around
  12341. locations exposed with `org-show-context'.
  12342. With optional argument SIBLINGS, on each level of the hierarchy all
  12343. siblings are shown. This repairs the tree structure to what it would
  12344. look like when opened with hierarchical calls to `org-cycle'.
  12345. With a \\[universal-argument] \\[universal-argument] prefix, \
  12346. go to the parent and show the entire tree."
  12347. (interactive "P")
  12348. (run-hooks 'org-reveal-start-hook)
  12349. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12350. ((equal siblings '(16))
  12351. (save-excursion
  12352. (when (org-up-heading-safe)
  12353. (org-show-subtree)
  12354. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12355. (t (org-show-set-visibility 'lineage))))
  12356. (defun org-highlight-new-match (beg end)
  12357. "Highlight from BEG to END and mark the highlight is an occur headline."
  12358. (let ((ov (make-overlay beg end)))
  12359. (overlay-put ov 'face 'secondary-selection)
  12360. (overlay-put ov 'org-type 'org-occur)
  12361. (push ov org-occur-highlights)))
  12362. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12363. "Remove the occur highlights from the buffer.
  12364. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12365. from the `before-change-functions' in the current buffer."
  12366. (interactive)
  12367. (unless org-inhibit-highlight-removal
  12368. (mapc #'delete-overlay org-occur-highlights)
  12369. (setq org-occur-highlights nil)
  12370. (setq org-occur-parameters nil)
  12371. (unless noremove
  12372. (remove-hook 'before-change-functions
  12373. 'org-remove-occur-highlights 'local))))
  12374. ;;;; Priorities
  12375. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12376. "Regular expression matching the priority indicator.")
  12377. (defvar org-remove-priority-next-time nil)
  12378. (defun org-priority-up ()
  12379. "Increase the priority of the current item."
  12380. (interactive)
  12381. (org-priority 'up))
  12382. (defun org-priority-down ()
  12383. "Decrease the priority of the current item."
  12384. (interactive)
  12385. (org-priority 'down))
  12386. (defun org-priority (&optional action _show)
  12387. "Change the priority of an item.
  12388. ACTION can be `set', `up', `down', or a character."
  12389. (interactive "P")
  12390. (if (equal action '(4))
  12391. (org-show-priority)
  12392. (unless org-enable-priority-commands
  12393. (user-error "Priority commands are disabled"))
  12394. (setq action (or action 'set))
  12395. (let (current new news have remove)
  12396. (save-excursion
  12397. (org-back-to-heading t)
  12398. (when (looking-at org-priority-regexp)
  12399. (setq current (string-to-char (match-string 2))
  12400. have t))
  12401. (cond
  12402. ((eq action 'remove)
  12403. (setq remove t new ?\ ))
  12404. ((or (eq action 'set)
  12405. (integerp action))
  12406. (if (not (eq action 'set))
  12407. (setq new action)
  12408. (message "Priority %c-%c, SPC to remove: "
  12409. org-highest-priority org-lowest-priority)
  12410. (save-match-data
  12411. (setq new (read-char-exclusive))))
  12412. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12413. (= (upcase org-lowest-priority) org-lowest-priority))
  12414. (setq new (upcase new)))
  12415. (cond ((equal new ?\ ) (setq remove t))
  12416. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12417. (user-error "Priority must be between `%c' and `%c'"
  12418. org-highest-priority org-lowest-priority))))
  12419. ((eq action 'up)
  12420. (setq new (if have
  12421. (1- current) ; normal cycling
  12422. ;; last priority was empty
  12423. (if (eq last-command this-command)
  12424. org-lowest-priority ; wrap around empty to lowest
  12425. ;; default
  12426. (if org-priority-start-cycle-with-default
  12427. org-default-priority
  12428. (1- org-default-priority))))))
  12429. ((eq action 'down)
  12430. (setq new (if have
  12431. (1+ current) ; normal cycling
  12432. ;; last priority was empty
  12433. (if (eq last-command this-command)
  12434. org-highest-priority ; wrap around empty to highest
  12435. ;; default
  12436. (if org-priority-start-cycle-with-default
  12437. org-default-priority
  12438. (1+ org-default-priority))))))
  12439. (t (user-error "Invalid action")))
  12440. (when (or (< (upcase new) org-highest-priority)
  12441. (> (upcase new) org-lowest-priority))
  12442. (if (and (memq action '(up down))
  12443. (not have) (not (eq last-command this-command)))
  12444. ;; `new' is from default priority
  12445. (error
  12446. "The default can not be set, see `org-default-priority' why")
  12447. ;; normal cycling: `new' is beyond highest/lowest priority
  12448. ;; and is wrapped around to the empty priority
  12449. (setq remove t)))
  12450. (setq news (format "%c" new))
  12451. (if have
  12452. (if remove
  12453. (replace-match "" t t nil 1)
  12454. (replace-match news t t nil 2))
  12455. (if remove
  12456. (user-error "No priority cookie found in line")
  12457. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12458. (if (match-end 2)
  12459. (progn
  12460. (goto-char (match-end 2))
  12461. (insert " [#" news "]"))
  12462. (goto-char (match-beginning 3))
  12463. (insert "[#" news "] "))))
  12464. (org-set-tags nil 'align))
  12465. (if remove
  12466. (message "Priority removed")
  12467. (message "Priority of current item set to %s" news)))))
  12468. (defun org-show-priority ()
  12469. "Show the priority of the current item.
  12470. This priority is composed of the main priority given with the [#A] cookies,
  12471. and by additional input from the age of a schedules or deadline entry."
  12472. (interactive)
  12473. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12474. (org-get-at-bol 'priority)
  12475. (save-excursion
  12476. (save-match-data
  12477. (beginning-of-line)
  12478. (and (looking-at org-heading-regexp)
  12479. (org-get-priority (match-string 0))))))))
  12480. (message "Priority is %d" (if pri pri -1000))))
  12481. (defun org-get-priority (s)
  12482. "Find priority cookie and return priority."
  12483. (save-match-data
  12484. (if (functionp org-get-priority-function)
  12485. (funcall org-get-priority-function)
  12486. (if (not (string-match org-priority-regexp s))
  12487. (* 1000 (- org-lowest-priority org-default-priority))
  12488. (* 1000 (- org-lowest-priority
  12489. (string-to-char (match-string 2 s))))))))
  12490. ;;;; Tags
  12491. (defvar org-agenda-archives-mode)
  12492. (defvar org-map-continue-from nil
  12493. "Position from where mapping should continue.
  12494. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12495. (defvar org-scanner-tags nil
  12496. "The current tag list while the tags scanner is running.")
  12497. (defvar org-trust-scanner-tags nil
  12498. "Should `org-get-tags-at' use the tags for the scanner.
  12499. This is for internal dynamical scoping only.
  12500. When this is non-nil, the function `org-get-tags-at' will return the value
  12501. of `org-scanner-tags' instead of building the list by itself. This
  12502. can lead to large speed-ups when the tags scanner is used in a file with
  12503. many entries, and when the list of tags is retrieved, for example to
  12504. obtain a list of properties. Building the tags list for each entry in such
  12505. a file becomes an N^2 operation - but with this variable set, it scales
  12506. as N.")
  12507. (defvar org--matcher-tags-todo-only nil)
  12508. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12509. "Scan headline tags with inheritance and produce output ACTION.
  12510. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12511. or `agenda' to produce an entry list for an agenda view. It can also be
  12512. a Lisp form or a function that should be called at each matched headline, in
  12513. this case the return value is a list of all return values from these calls.
  12514. MATCHER is a function accepting three arguments, returning
  12515. a non-nil value whenever a given set of tags qualifies a headline
  12516. for inclusion. See `org-make-tags-matcher' for more information.
  12517. As a special case, it can also be set to t (respectively nil) in
  12518. order to match all (respectively none) headline.
  12519. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12520. included in the output.
  12521. START-LEVEL can be a string with asterisks, reducing the scope to
  12522. headlines matching this string."
  12523. (require 'org-agenda)
  12524. (let* ((re (concat "^"
  12525. (if start-level
  12526. ;; Get the correct level to match
  12527. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12528. org-outline-regexp)
  12529. " *\\(\\<\\("
  12530. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12531. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12532. (props (list 'face 'default
  12533. 'done-face 'org-agenda-done
  12534. 'undone-face 'default
  12535. 'mouse-face 'highlight
  12536. 'org-not-done-regexp org-not-done-regexp
  12537. 'org-todo-regexp org-todo-regexp
  12538. 'org-complex-heading-regexp org-complex-heading-regexp
  12539. 'help-echo
  12540. (format "mouse-2 or RET jump to org file %s"
  12541. (abbreviate-file-name
  12542. (or (buffer-file-name (buffer-base-buffer))
  12543. (buffer-name (buffer-base-buffer)))))))
  12544. (org-map-continue-from nil)
  12545. lspos tags tags-list
  12546. (tags-alist (list (cons 0 org-file-tags)))
  12547. (llast 0) rtn rtn1 level category i txt
  12548. todo marker entry priority
  12549. ts-date ts-date-type ts-date-pair)
  12550. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12551. (setq action (list 'lambda nil action)))
  12552. (save-excursion
  12553. (goto-char (point-min))
  12554. (when (eq action 'sparse-tree)
  12555. (org-overview)
  12556. (org-remove-occur-highlights))
  12557. (while (let (case-fold-search)
  12558. (re-search-forward re nil t))
  12559. (setq org-map-continue-from nil)
  12560. (catch :skip
  12561. (setq todo
  12562. ;; TODO: is the 1-2 difference a bug?
  12563. (when (match-end 1) (match-string-no-properties 2))
  12564. tags (when (match-end 4) (match-string-no-properties 4)))
  12565. (goto-char (setq lspos (match-beginning 0)))
  12566. (setq level (org-reduced-level (org-outline-level))
  12567. category (org-get-category))
  12568. (when (eq action 'agenda)
  12569. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12570. ts-date (car ts-date-pair)
  12571. ts-date-type (cdr ts-date-pair)))
  12572. (setq i llast llast level)
  12573. ;; remove tag lists from same and sublevels
  12574. (while (>= i level)
  12575. (when (setq entry (assoc i tags-alist))
  12576. (setq tags-alist (delete entry tags-alist)))
  12577. (setq i (1- i)))
  12578. ;; add the next tags
  12579. (when tags
  12580. (setq tags (org-split-string tags ":")
  12581. tags-alist
  12582. (cons (cons level tags) tags-alist)))
  12583. ;; compile tags for current headline
  12584. (setq tags-list
  12585. (if org-use-tag-inheritance
  12586. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12587. tags)
  12588. org-scanner-tags tags-list)
  12589. (when org-use-tag-inheritance
  12590. (setcdr (car tags-alist)
  12591. (mapcar (lambda (x)
  12592. (setq x (copy-sequence x))
  12593. (org-add-prop-inherited x))
  12594. (cdar tags-alist))))
  12595. (when (and tags org-use-tag-inheritance
  12596. (or (not (eq t org-use-tag-inheritance))
  12597. org-tags-exclude-from-inheritance))
  12598. ;; Selective inheritance, remove uninherited ones.
  12599. (setcdr (car tags-alist)
  12600. (org-remove-uninherited-tags (cdar tags-alist))))
  12601. (when (and
  12602. ;; eval matcher only when the todo condition is OK
  12603. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12604. (if (functionp matcher)
  12605. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12606. (funcall matcher todo tags-list level))
  12607. matcher))
  12608. ;; Call the skipper, but return t if it does not
  12609. ;; skip, so that the `and' form continues evaluating.
  12610. (progn
  12611. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12612. t)
  12613. ;; Check if timestamps are deselecting this entry
  12614. (or (not todo-only)
  12615. (and (member todo org-todo-keywords-1)
  12616. (or (not org-agenda-tags-todo-honor-ignore-options)
  12617. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12618. ;; select this headline
  12619. (cond
  12620. ((eq action 'sparse-tree)
  12621. (and org-highlight-sparse-tree-matches
  12622. (org-get-heading) (match-end 0)
  12623. (org-highlight-new-match
  12624. (match-beginning 1) (match-end 1)))
  12625. (org-show-context 'tags-tree))
  12626. ((eq action 'agenda)
  12627. (setq txt (org-agenda-format-item
  12628. ""
  12629. (concat
  12630. (if (eq org-tags-match-list-sublevels 'indented)
  12631. (make-string (1- level) ?.) "")
  12632. (org-get-heading))
  12633. (make-string level ?\s)
  12634. category
  12635. tags-list)
  12636. priority (org-get-priority txt))
  12637. (goto-char lspos)
  12638. (setq marker (org-agenda-new-marker))
  12639. (org-add-props txt props
  12640. 'org-marker marker 'org-hd-marker marker 'org-category category
  12641. 'todo-state todo
  12642. 'ts-date ts-date
  12643. 'priority priority
  12644. 'type (concat "tagsmatch" ts-date-type))
  12645. (push txt rtn))
  12646. ((functionp action)
  12647. (setq org-map-continue-from nil)
  12648. (save-excursion
  12649. (setq rtn1 (funcall action))
  12650. (push rtn1 rtn)))
  12651. (t (user-error "Invalid action")))
  12652. ;; if we are to skip sublevels, jump to end of subtree
  12653. (unless org-tags-match-list-sublevels
  12654. (org-end-of-subtree t)
  12655. (backward-char 1))))
  12656. ;; Get the correct position from where to continue
  12657. (if org-map-continue-from
  12658. (goto-char org-map-continue-from)
  12659. (and (= (point) lspos) (end-of-line 1)))))
  12660. (when (and (eq action 'sparse-tree)
  12661. (not org-sparse-tree-open-archived-trees))
  12662. (org-hide-archived-subtrees (point-min) (point-max)))
  12663. (nreverse rtn)))
  12664. (defun org-remove-uninherited-tags (tags)
  12665. "Remove all tags that are not inherited from the list TAGS."
  12666. (cond
  12667. ((eq org-use-tag-inheritance t)
  12668. (if org-tags-exclude-from-inheritance
  12669. (org-delete-all org-tags-exclude-from-inheritance tags)
  12670. tags))
  12671. ((not org-use-tag-inheritance) nil)
  12672. ((stringp org-use-tag-inheritance)
  12673. (delq nil (mapcar
  12674. (lambda (x)
  12675. (if (and (string-match org-use-tag-inheritance x)
  12676. (not (member x org-tags-exclude-from-inheritance)))
  12677. x nil))
  12678. tags)))
  12679. ((listp org-use-tag-inheritance)
  12680. (delq nil (mapcar
  12681. (lambda (x)
  12682. (if (member x org-use-tag-inheritance) x nil))
  12683. tags)))))
  12684. (defun org-match-sparse-tree (&optional todo-only match)
  12685. "Create a sparse tree according to tags string MATCH.
  12686. MATCH is a string with match syntax. It can contain a selection
  12687. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12688. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12689. those. See the manual for details.
  12690. If optional argument TODO-ONLY is non-nil, only select lines that
  12691. are also TODO tasks."
  12692. (interactive "P")
  12693. (org-agenda-prepare-buffers (list (current-buffer)))
  12694. (let ((org--matcher-tags-todo-only todo-only))
  12695. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12696. org--matcher-tags-todo-only)))
  12697. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12698. (defvar org-cached-props nil)
  12699. (defun org-cached-entry-get (pom property)
  12700. (if (or (eq t org-use-property-inheritance)
  12701. (and (stringp org-use-property-inheritance)
  12702. (let ((case-fold-search t))
  12703. (string-match-p org-use-property-inheritance property)))
  12704. (and (listp org-use-property-inheritance)
  12705. (member-ignore-case property org-use-property-inheritance)))
  12706. ;; Caching is not possible, check it directly.
  12707. (org-entry-get pom property 'inherit)
  12708. ;; Get all properties, so we can do complicated checks easily.
  12709. (cdr (assoc-string property
  12710. (or org-cached-props
  12711. (setq org-cached-props (org-entry-properties pom)))
  12712. t))))
  12713. (defun org-global-tags-completion-table (&optional files)
  12714. "Return the list of all tags in all agenda buffer/files.
  12715. Optional FILES argument is a list of files which can be used
  12716. instead of the agenda files."
  12717. (save-excursion
  12718. (org-uniquify
  12719. (delq nil
  12720. (apply #'append
  12721. (mapcar
  12722. (lambda (file)
  12723. (set-buffer (find-file-noselect file))
  12724. (mapcar (lambda (x)
  12725. (and (stringp (car-safe x))
  12726. (list (car-safe x))))
  12727. (or org-current-tag-alist (org-get-buffer-tags))))
  12728. (if (car-safe files) files
  12729. (org-agenda-files))))))))
  12730. (defun org-make-tags-matcher (match)
  12731. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12732. Returns a cons of the selection string MATCH and a function
  12733. implementing the matcher.
  12734. The matcher is to be called at an Org entry, with point on the
  12735. headline, and returns non-nil if the entry matches the selection
  12736. string MATCH. It must be called with three arguments: the TODO
  12737. keyword at the entry (or nil if none), the list of all tags at
  12738. the entry including inherited ones and the reduced level of the
  12739. headline. Additionally, the category of the entry, if any, must
  12740. be specified as the text property `org-category' on the headline.
  12741. This function sets the variable `org--matcher-tags-todo-only' to
  12742. a non-nil value if the matcher restricts matching to TODO
  12743. entries, otherwise it is not touched.
  12744. See also `org-scan-tags'."
  12745. (unless match
  12746. ;; Get a new match request, with completion against the global
  12747. ;; tags table and the local tags in current buffer.
  12748. (let ((org-last-tags-completion-table
  12749. (org-uniquify
  12750. (delq nil (append (org-get-buffer-tags)
  12751. (org-global-tags-completion-table))))))
  12752. (setq match
  12753. (completing-read
  12754. "Match: "
  12755. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12756. (let ((match0 match)
  12757. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12758. (start 0)
  12759. tagsmatch todomatch tagsmatcher todomatcher)
  12760. ;; Expand group tags.
  12761. (setq match (org-tags-expand match))
  12762. ;; Check if there is a TODO part of this match, which would be the
  12763. ;; part after a "/". To make sure that this slash is not part of
  12764. ;; a property value to be matched against, we also check that
  12765. ;; there is no / after that slash. First, find the last slash.
  12766. (let ((s 0))
  12767. (while (string-match "/+" match s)
  12768. (setq start (match-beginning 0))
  12769. (setq s (match-end 0))))
  12770. (if (and (string-match "/+" match start)
  12771. (not (string-match-p "\"" match start)))
  12772. ;; Match contains also a TODO-matching request.
  12773. (progn
  12774. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12775. (setq todomatch (substring match (match-end 0)))
  12776. (when (string-prefix-p "!" todomatch)
  12777. (setq org--matcher-tags-todo-only t)
  12778. (setq todomatch (substring todomatch 1)))
  12779. (when (string-match "\\`\\s-*\\'" todomatch)
  12780. (setq todomatch nil)))
  12781. ;; Only matching tags.
  12782. (setq tagsmatch match)
  12783. (setq todomatch nil))
  12784. ;; Make the tags matcher.
  12785. (when (org-string-nw-p tagsmatch)
  12786. (let ((orlist nil)
  12787. (orterms (org-split-string tagsmatch "|"))
  12788. term)
  12789. (while (setq term (pop orterms))
  12790. (while (and (equal (substring term -1) "\\") orterms)
  12791. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12792. (while (string-match re term)
  12793. (let* ((rest (substring term (match-end 0)))
  12794. (minus (and (match-end 1)
  12795. (equal (match-string 1 term) "-")))
  12796. (tag (save-match-data
  12797. (replace-regexp-in-string
  12798. "\\\\-" "-" (match-string 2 term))))
  12799. (regexp (eq (string-to-char tag) ?{))
  12800. (levelp (match-end 4))
  12801. (propp (match-end 5))
  12802. (mm
  12803. (cond
  12804. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12805. (levelp
  12806. `(,(org-op-to-function (match-string 3 term))
  12807. level
  12808. ,(string-to-number (match-string 4 term))))
  12809. (propp
  12810. (let* ((gv (pcase (upcase (match-string 5 term))
  12811. ("CATEGORY"
  12812. '(get-text-property (point) 'org-category))
  12813. ("TODO" 'todo)
  12814. (p `(org-cached-entry-get nil ,p))))
  12815. (pv (match-string 7 term))
  12816. (regexp (eq (string-to-char pv) ?{))
  12817. (strp (eq (string-to-char pv) ?\"))
  12818. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12819. (po (org-op-to-function (match-string 6 term)
  12820. (if timep 'time strp))))
  12821. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12822. (when timep (setq pv (org-matcher-time pv)))
  12823. (cond ((and regexp (eq po 'org<>))
  12824. `(not (string-match ,pv (or ,gv ""))))
  12825. (regexp `(string-match ,pv (or ,gv "")))
  12826. (strp `(,po (or ,gv "") ,pv))
  12827. (t
  12828. `(,po
  12829. (string-to-number (or ,gv ""))
  12830. ,(string-to-number pv))))))
  12831. (t `(member ,tag tags-list)))))
  12832. (push (if minus `(not ,mm) mm) tagsmatcher)
  12833. (setq term rest)))
  12834. (push `(and ,@tagsmatcher) orlist)
  12835. (setq tagsmatcher nil))
  12836. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12837. ;; Make the TODO matcher.
  12838. (when (org-string-nw-p todomatch)
  12839. (let ((orlist nil))
  12840. (dolist (term (org-split-string todomatch "|"))
  12841. (while (string-match re term)
  12842. (let* ((minus (and (match-end 1)
  12843. (equal (match-string 1 term) "-")))
  12844. (kwd (match-string 2 term))
  12845. (regexp (eq (string-to-char kwd) ?{))
  12846. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12847. `(equal todo ,kwd))))
  12848. (push (if minus `(not ,mm) mm) todomatcher))
  12849. (setq term (substring term (match-end 0))))
  12850. (push (if (> (length todomatcher) 1)
  12851. (cons 'and todomatcher)
  12852. (car todomatcher))
  12853. orlist)
  12854. (setq todomatcher nil))
  12855. (setq todomatcher (cons 'or orlist))))
  12856. ;; Return the string and function of the matcher. If no
  12857. ;; tags-specific or todo-specific matcher exists, match
  12858. ;; everything.
  12859. (let ((matcher (if (and tagsmatcher todomatcher)
  12860. `(and ,tagsmatcher ,todomatcher)
  12861. (or tagsmatcher todomatcher t))))
  12862. (when org--matcher-tags-todo-only
  12863. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12864. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12865. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12866. "Expand group tags in MATCH.
  12867. This replaces every group tag in MATCH with a regexp tag search.
  12868. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12869. will be replaced like this:
  12870. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12871. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12872. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12873. Replacing by a regexp preserves the structure of the match.
  12874. E.g., this expansion
  12875. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12876. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12877. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12878. A group tag in MATCH can contain regular expressions of its own.
  12879. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12880. will be replaced like this:
  12881. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12882. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12883. assumed to be a single group tag, and the function will return
  12884. the list of tags in this group.
  12885. When DOWNCASE is non-nil, expand downcased TAGS."
  12886. (if org-group-tags
  12887. (let* ((case-fold-search t)
  12888. (stable org-mode-syntax-table)
  12889. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12890. (taggroups (if downcased
  12891. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12892. taggroups)
  12893. taggroups))
  12894. (taggroups-keys (mapcar #'car taggroups))
  12895. (return-match (if downcased (downcase match) match))
  12896. (count 0)
  12897. (work-already-expanded tags-already-expanded)
  12898. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12899. ;; @ and _ are allowed as word-components in tags.
  12900. (modify-syntax-entry ?@ "w" stable)
  12901. (modify-syntax-entry ?_ "w" stable)
  12902. ;; Temporarily replace regexp-expressions in the match-expression.
  12903. (while (string-match "{.+?}" return-match)
  12904. (cl-incf count)
  12905. (push (match-string 0 return-match) regexps-in-match)
  12906. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12907. (while (and taggroups-keys
  12908. (with-syntax-table stable
  12909. (string-match
  12910. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12911. (regexp-opt taggroups-keys) "\\>\\)")
  12912. return-match)))
  12913. (let* ((dir (match-string 1 return-match))
  12914. (tag (match-string 2 return-match))
  12915. (tag (if downcased (downcase tag) tag)))
  12916. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12917. (member tag work-already-expanded))
  12918. (setq tags-in-group (assoc tag taggroups))
  12919. (push tag work-already-expanded)
  12920. ;; Recursively expand each tag in the group, if the tag hasn't
  12921. ;; already been expanded. Restore the match-data after all recursive calls.
  12922. (save-match-data
  12923. (let (tags-expanded)
  12924. (dolist (x (cdr tags-in-group))
  12925. (if (and (member x taggroups-keys)
  12926. (not (member x work-already-expanded)))
  12927. (setq tags-expanded
  12928. (delete-dups
  12929. (append
  12930. (org-tags-expand x t downcased
  12931. work-already-expanded)
  12932. tags-expanded)))
  12933. (setq tags-expanded
  12934. (append (list x) tags-expanded)))
  12935. (setq work-already-expanded
  12936. (delete-dups
  12937. (append tags-expanded
  12938. work-already-expanded))))
  12939. (setq tags-in-group
  12940. (delete-dups (cons (car tags-in-group)
  12941. tags-expanded)))))
  12942. ;; Filter tag-regexps from tags.
  12943. (setq regexp-in-group-escaped
  12944. (delq nil (mapcar (lambda (x)
  12945. (if (stringp x)
  12946. (and (equal "{" (substring x 0 1))
  12947. (equal "}" (substring x -1))
  12948. x)
  12949. x))
  12950. tags-in-group))
  12951. regexp-in-group
  12952. (mapcar (lambda (x)
  12953. (substring x 1 -1))
  12954. regexp-in-group-escaped)
  12955. tags-in-group
  12956. (delq nil (mapcar (lambda (x)
  12957. (if (stringp x)
  12958. (and (not (equal "{" (substring x 0 1)))
  12959. (not (equal "}" (substring x -1)))
  12960. x)
  12961. x))
  12962. tags-in-group)))
  12963. ;; If single-as-list, do no more in the while-loop.
  12964. (if (not single-as-list)
  12965. (progn
  12966. (when regexp-in-group
  12967. (setq regexp-in-group
  12968. (concat "\\|"
  12969. (mapconcat 'identity regexp-in-group
  12970. "\\|"))))
  12971. (setq tags-in-group
  12972. (concat dir
  12973. "{\\<"
  12974. (regexp-opt tags-in-group)
  12975. "\\>"
  12976. regexp-in-group
  12977. "}"))
  12978. (when (stringp tags-in-group)
  12979. (org-add-props tags-in-group '(grouptag t)))
  12980. (setq return-match
  12981. (replace-match tags-in-group t t return-match)))
  12982. (setq tags-in-group
  12983. (append regexp-in-group-escaped tags-in-group))))
  12984. (setq taggroups-keys (delete tag taggroups-keys))))
  12985. ;; Add the regular expressions back into the match-expression again.
  12986. (while regexps-in-match
  12987. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12988. (pop regexps-in-match)
  12989. return-match t t))
  12990. (cl-decf count))
  12991. (if single-as-list
  12992. (if tags-in-group tags-in-group (list return-match))
  12993. return-match))
  12994. (if single-as-list
  12995. (list (if downcased (downcase match) match))
  12996. match)))
  12997. (defun org-op-to-function (op &optional stringp)
  12998. "Turn an operator into the appropriate function."
  12999. (setq op
  13000. (cond
  13001. ((equal op "<" ) '(< string< org-time<))
  13002. ((equal op ">" ) '(> org-string> org-time>))
  13003. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13004. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13005. ((member op '("=" "==")) '(= string= org-time=))
  13006. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13007. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13008. (defun org<> (a b) (not (= a b)))
  13009. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13010. (defun org-string>= (a b) (not (string< a b)))
  13011. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13012. (defun org-string<> (a b) (not (string= a b)))
  13013. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13014. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13015. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13016. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13017. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13018. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13019. (defun org-2ft (s)
  13020. "Convert S to a floating point time.
  13021. If S is already a number, just return it. If it is a string, parse
  13022. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13023. (cond
  13024. ((numberp s) s)
  13025. ((stringp s)
  13026. (condition-case nil
  13027. (float-time (apply #'encode-time (org-parse-time-string s)))
  13028. (error 0.)))
  13029. (t 0.)))
  13030. (defun org-time-today ()
  13031. "Time in seconds today at 0:00.
  13032. Returns the float number of seconds since the beginning of the
  13033. epoch to the beginning of today (00:00)."
  13034. (float-time (apply 'encode-time
  13035. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13036. (defun org-matcher-time (s)
  13037. "Interpret a time comparison value."
  13038. (save-match-data
  13039. (cond
  13040. ((string= s "<now>") (float-time))
  13041. ((string= s "<today>") (org-time-today))
  13042. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13043. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13044. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13045. (+ (org-time-today)
  13046. (* (string-to-number (match-string 1 s))
  13047. (cdr (assoc (match-string 2 s)
  13048. '(("d" . 86400.0) ("w" . 604800.0)
  13049. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13050. (t (org-2ft s)))))
  13051. (defun org-match-any-p (re list)
  13052. "Does re match any element of list?"
  13053. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13054. (delq nil list))
  13055. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13056. (defvar org-tags-overlay (make-overlay 1 1))
  13057. (delete-overlay org-tags-overlay)
  13058. (defun org-get-local-tags-at (&optional pos)
  13059. "Get a list of tags defined in the current headline."
  13060. (org-get-tags-at pos 'local))
  13061. (defun org-get-local-tags ()
  13062. "Get a list of tags defined in the current headline."
  13063. (org-get-tags-at nil 'local))
  13064. (defun org-get-tags-at (&optional pos local)
  13065. "Get a list of all headline tags applicable at POS.
  13066. POS defaults to point. If tags are inherited, the list contains
  13067. the targets in the same sequence as the headlines appear, i.e.
  13068. the tags of the current headline come last.
  13069. When LOCAL is non-nil, only return tags from the current headline,
  13070. ignore inherited ones."
  13071. (interactive)
  13072. (if (and org-trust-scanner-tags
  13073. (or (not pos) (equal pos (point)))
  13074. (not local))
  13075. org-scanner-tags
  13076. (let (tags ltags lastpos parent)
  13077. (save-excursion
  13078. (save-restriction
  13079. (widen)
  13080. (goto-char (or pos (point)))
  13081. (save-match-data
  13082. (catch 'done
  13083. (condition-case nil
  13084. (progn
  13085. (org-back-to-heading t)
  13086. (while (not (equal lastpos (point)))
  13087. (setq lastpos (point))
  13088. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13089. (setq ltags (org-split-string
  13090. (match-string-no-properties 1) ":"))
  13091. (when parent
  13092. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13093. (setq tags (append
  13094. (if parent
  13095. (org-remove-uninherited-tags ltags)
  13096. ltags)
  13097. tags)))
  13098. (or org-use-tag-inheritance (throw 'done t))
  13099. (when local (throw 'done t))
  13100. (or (org-up-heading-safe) (error nil))
  13101. (setq parent t)))
  13102. (error nil)))))
  13103. (if local
  13104. tags
  13105. (reverse (delete-dups
  13106. (reverse (append
  13107. (org-remove-uninherited-tags
  13108. org-file-tags)
  13109. tags)))))))))
  13110. (defun org-add-prop-inherited (s)
  13111. (add-text-properties 0 (length s) '(inherited t) s)
  13112. s)
  13113. (defun org-toggle-tag (tag &optional onoff)
  13114. "Toggle the tag TAG for the current line.
  13115. If ONOFF is `on' or `off', don't toggle but set to this state."
  13116. (save-excursion
  13117. (org-back-to-heading t)
  13118. (let ((current
  13119. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13120. (line-end-position) t)
  13121. (let ((tags (match-string 1)))
  13122. ;; Clear current tags.
  13123. (replace-match "")
  13124. ;; Reverse the tags list so any new tag is appended to
  13125. ;; the current list of tags.
  13126. (nreverse (org-split-string tags ":")))))
  13127. res)
  13128. (pcase onoff
  13129. (`off (setq current (delete tag current)))
  13130. ((or `on (guard (not (member tag current))))
  13131. (setq res t)
  13132. (cl-pushnew tag current :test #'equal))
  13133. (_ (setq current (delete tag current))))
  13134. (end-of-line)
  13135. (if current
  13136. (progn
  13137. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13138. (org-set-tags nil t))
  13139. (delete-horizontal-space))
  13140. (run-hooks 'org-after-tags-change-hook)
  13141. res)))
  13142. (defun org--align-tags-here (to-col)
  13143. "Align tags on the current headline to TO-COL.
  13144. Assume point is on a headline."
  13145. (let ((pos (point)))
  13146. (beginning-of-line)
  13147. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13148. (>= pos (match-beginning 2)))
  13149. ;; No tags or point within tags: do not align.
  13150. (goto-char pos)
  13151. (goto-char (match-beginning 1))
  13152. (let ((shift (max (- (if (>= to-col 0) to-col
  13153. (- (abs to-col) (string-width (match-string 2))))
  13154. (current-column))
  13155. 1)))
  13156. (replace-match (make-string shift ?\s) nil nil nil 1)
  13157. ;; Preserve initial position, if possible. In any case, stop
  13158. ;; before tags.
  13159. (when (< pos (point)) (goto-char pos))))))
  13160. (defun org-set-tags-command (&optional arg just-align)
  13161. "Call the set-tags command for the current entry."
  13162. (interactive "P")
  13163. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13164. (org-set-tags arg just-align)
  13165. (save-excursion
  13166. (unless (and (org-region-active-p)
  13167. org-loop-over-headlines-in-active-region)
  13168. (org-back-to-heading t))
  13169. (org-set-tags arg just-align))))
  13170. (defun org-set-tags-to (data)
  13171. "Set the tags of the current entry to DATA, replacing the current tags.
  13172. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13173. If DATA is nil or the empty string, any tags will be removed."
  13174. (interactive "sTags: ")
  13175. (setq data
  13176. (cond
  13177. ((eq data nil) "")
  13178. ((equal data "") "")
  13179. ((stringp data)
  13180. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13181. ":"))
  13182. ((listp data)
  13183. (concat ":" (mapconcat 'identity data ":") ":"))))
  13184. (when data
  13185. (save-excursion
  13186. (org-back-to-heading t)
  13187. (when (let ((case-fold-search nil))
  13188. (looking-at org-complex-heading-regexp))
  13189. (if (match-end 5)
  13190. (progn
  13191. (goto-char (match-beginning 5))
  13192. (insert data)
  13193. (delete-region (point) (point-at-eol))
  13194. (org-set-tags nil 'align))
  13195. (goto-char (point-at-eol))
  13196. (insert " " data)
  13197. (org-set-tags nil 'align)))
  13198. (beginning-of-line 1)
  13199. (when (looking-at ".*?\\([ \t]+\\)$")
  13200. (delete-region (match-beginning 1) (match-end 1))))))
  13201. (defun org-align-all-tags ()
  13202. "Align the tags in all headings."
  13203. (interactive)
  13204. (save-excursion
  13205. (or (ignore-errors (org-back-to-heading t))
  13206. (outline-next-heading))
  13207. (if (org-at-heading-p)
  13208. (org-set-tags t)
  13209. (message "No headings"))))
  13210. (defvar org-indent-indentation-per-level)
  13211. (defun org-set-tags (&optional arg just-align)
  13212. "Set the tags for the current headline.
  13213. With prefix ARG, realign all tags in headings in the current buffer.
  13214. When JUST-ALIGN is non-nil, only align tags."
  13215. (interactive "P")
  13216. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13217. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13218. 'region-start-level
  13219. 'region))
  13220. org-loop-over-headlines-in-active-region)
  13221. (org-map-entries
  13222. ;; We don't use ARG and JUST-ALIGN here because these args
  13223. ;; are not useful when looping over headlines.
  13224. #'org-set-tags
  13225. org-loop-over-headlines-in-active-region
  13226. cl
  13227. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13228. (let ((org-setting-tags t))
  13229. (if arg
  13230. (save-excursion
  13231. (goto-char (point-min))
  13232. (while (re-search-forward org-outline-regexp-bol nil t)
  13233. (org-set-tags nil t)
  13234. (end-of-line))
  13235. (message "All tags realigned to column %d" org-tags-column))
  13236. (let* ((current (org-get-tags-string))
  13237. (tags
  13238. (if just-align current
  13239. ;; Get a new set of tags from the user.
  13240. (save-excursion
  13241. (let* ((seen)
  13242. (table
  13243. (setq
  13244. org-last-tags-completion-table
  13245. ;; Uniquify tags in alists, yet preserve
  13246. ;; structure (i.e., keywords).
  13247. (delq nil
  13248. (mapcar
  13249. (lambda (pair)
  13250. (let ((head (car pair)))
  13251. (cond ((symbolp head) pair)
  13252. ((member head seen) nil)
  13253. (t (push head seen)
  13254. pair))))
  13255. (append
  13256. (or org-current-tag-alist
  13257. (org-get-buffer-tags))
  13258. (and
  13259. org-complete-tags-always-offer-all-agenda-tags
  13260. (org-global-tags-completion-table
  13261. (org-agenda-files))))))))
  13262. (current-tags (org-split-string current ":"))
  13263. (inherited-tags
  13264. (nreverse (nthcdr (length current-tags)
  13265. (nreverse (org-get-tags-at))))))
  13266. (replace-regexp-in-string
  13267. "\\([-+&]+\\|,\\)"
  13268. ":"
  13269. (if (or (eq t org-use-fast-tag-selection)
  13270. (and org-use-fast-tag-selection
  13271. (delq nil (mapcar #'cdr table))))
  13272. (org-fast-tag-selection
  13273. current-tags inherited-tags table
  13274. (and org-fast-tag-selection-include-todo
  13275. org-todo-key-alist))
  13276. (let ((org-add-colon-after-tag-completion
  13277. (< 1 (length table))))
  13278. (org-trim
  13279. (completing-read
  13280. "Tags: "
  13281. #'org-tags-completion-function
  13282. nil nil current 'org-tags-history))))))))))
  13283. (when org-tags-sort-function
  13284. (setq tags
  13285. (mapconcat
  13286. #'identity
  13287. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13288. org-tags-sort-function)
  13289. ":")))
  13290. (if (or (string= ":" tags)
  13291. (string= "::" tags))
  13292. (setq tags ""))
  13293. (if (not (org-string-nw-p tags)) (setq tags "")
  13294. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13295. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13296. ;; Insert new tags at the correct column.
  13297. (unless (equal current tags)
  13298. (save-excursion
  13299. (beginning-of-line)
  13300. (let ((case-fold-search nil))
  13301. (looking-at org-complex-heading-regexp))
  13302. ;; Remove current tags, if any.
  13303. (when (match-end 5) (replace-match "" nil nil nil 5))
  13304. ;; Insert new tags, if any. Otherwise, remove trailing
  13305. ;; white spaces.
  13306. (end-of-line)
  13307. (if (not (equal tags ""))
  13308. ;; When text is being inserted on an invisible
  13309. ;; region boundary, it can be inadvertently sucked
  13310. ;; into invisibility.
  13311. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13312. (skip-chars-backward " \t")
  13313. (delete-region (point) (line-end-position)))))
  13314. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13315. ;; is on.
  13316. (unless (equal tags "")
  13317. (let* ((level (save-excursion
  13318. (beginning-of-line)
  13319. (skip-chars-forward "\\*")))
  13320. (offset (if (bound-and-true-p org-indent-mode)
  13321. (* (1- org-indent-indentation-per-level)
  13322. (1- level))
  13323. 0))
  13324. (tags-column
  13325. (+ org-tags-column
  13326. (if (> org-tags-column 0) (- offset) offset))))
  13327. (org--align-tags-here tags-column))))
  13328. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13329. (defun org-change-tag-in-region (beg end tag off)
  13330. "Add or remove TAG for each entry in the region.
  13331. This works in the agenda, and also in an Org buffer."
  13332. (interactive
  13333. (list (region-beginning) (region-end)
  13334. (let ((org-last-tags-completion-table
  13335. (if (derived-mode-p 'org-mode)
  13336. (org-uniquify
  13337. (delq nil (append (org-get-buffer-tags)
  13338. (org-global-tags-completion-table))))
  13339. (org-global-tags-completion-table))))
  13340. (completing-read
  13341. "Tag: " 'org-tags-completion-function nil nil nil
  13342. 'org-tags-history))
  13343. (progn
  13344. (message "[s]et or [r]emove? ")
  13345. (equal (read-char-exclusive) ?r))))
  13346. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13347. (let ((agendap (equal major-mode 'org-agenda-mode))
  13348. l1 l2 m buf pos newhead (cnt 0))
  13349. (goto-char end)
  13350. (setq l2 (1- (org-current-line)))
  13351. (goto-char beg)
  13352. (setq l1 (org-current-line))
  13353. (cl-loop for l from l1 to l2 do
  13354. (org-goto-line l)
  13355. (setq m (get-text-property (point) 'org-hd-marker))
  13356. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13357. (and agendap m))
  13358. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13359. pos (if agendap m (point)))
  13360. (with-current-buffer buf
  13361. (save-excursion
  13362. (save-restriction
  13363. (goto-char pos)
  13364. (setq cnt (1+ cnt))
  13365. (org-toggle-tag tag (if off 'off 'on))
  13366. (setq newhead (org-get-heading)))))
  13367. (and agendap (org-agenda-change-all-lines newhead m))))
  13368. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13369. (defun org-tags-completion-function (string _predicate &optional flag)
  13370. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13371. (confirm (lambda (x) (stringp (car x)))))
  13372. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13373. (setq s1 (match-string 1 string)
  13374. s2 (match-string 2 string))
  13375. (setq s1 "" s2 string))
  13376. (cond
  13377. ((eq flag nil)
  13378. ;; try completion
  13379. (setq rtn (try-completion s2 ctable confirm))
  13380. (when (stringp rtn)
  13381. (setq rtn
  13382. (concat s1 s2 (substring rtn (length s2))
  13383. (if (and org-add-colon-after-tag-completion
  13384. (assoc rtn ctable))
  13385. ":" ""))))
  13386. rtn)
  13387. ((eq flag t)
  13388. ;; all-completions
  13389. (all-completions s2 ctable confirm))
  13390. ((eq flag 'lambda)
  13391. ;; exact match?
  13392. (assoc s2 ctable)))))
  13393. (defun org-fast-tag-insert (kwd tags face &optional end)
  13394. "Insert KDW, and the TAGS, the latter with face FACE.
  13395. Also insert END."
  13396. (insert (format "%-12s" (concat kwd ":"))
  13397. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13398. (or end "")))
  13399. (defun org-fast-tag-show-exit (flag)
  13400. (save-excursion
  13401. (org-goto-line 3)
  13402. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13403. (replace-match ""))
  13404. (when flag
  13405. (end-of-line 1)
  13406. (org-move-to-column (- (window-width) 19) t)
  13407. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13408. (defun org-set-current-tags-overlay (current prefix)
  13409. "Add an overlay to CURRENT tag with PREFIX."
  13410. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13411. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13412. (org-overlay-display org-tags-overlay (concat prefix s))))
  13413. (defvar org-last-tag-selection-key nil)
  13414. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13415. "Fast tag selection with single keys.
  13416. CURRENT is the current list of tags in the headline, INHERITED is the
  13417. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13418. possibly with grouping information. TODO-TABLE is a similar table with
  13419. TODO keywords, should these have keys assigned to them.
  13420. If the keys are nil, a-z are automatically assigned.
  13421. Returns the new tags string, or nil to not change the current settings."
  13422. (let* ((fulltable (append table todo-table))
  13423. (maxlen (apply 'max (mapcar
  13424. (lambda (x)
  13425. (if (stringp (car x)) (string-width (car x)) 0))
  13426. fulltable)))
  13427. (buf (current-buffer))
  13428. (expert (eq org-fast-tag-selection-single-key 'expert))
  13429. (buffer-tags nil)
  13430. (fwidth (+ maxlen 3 1 3))
  13431. (ncol (/ (- (window-width) 4) fwidth))
  13432. (i-face 'org-done)
  13433. (c-face 'org-todo)
  13434. tg cnt e c char c1 c2 ntable tbl rtn
  13435. ov-start ov-end ov-prefix
  13436. (exit-after-next org-fast-tag-selection-single-key)
  13437. (done-keywords org-done-keywords)
  13438. groups ingroup intaggroup)
  13439. (save-excursion
  13440. (beginning-of-line 1)
  13441. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13442. (setq ov-start (match-beginning 1)
  13443. ov-end (match-end 1)
  13444. ov-prefix "")
  13445. (setq ov-start (1- (point-at-eol))
  13446. ov-end (1+ ov-start))
  13447. (skip-chars-forward "^\n\r")
  13448. (setq ov-prefix
  13449. (concat
  13450. (buffer-substring (1- (point)) (point))
  13451. (if (> (current-column) org-tags-column)
  13452. " "
  13453. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13454. (move-overlay org-tags-overlay ov-start ov-end)
  13455. (save-window-excursion
  13456. (if expert
  13457. (set-buffer (get-buffer-create " *Org tags*"))
  13458. (delete-other-windows)
  13459. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13460. (org-switch-to-buffer-other-window " *Org tags*"))
  13461. (erase-buffer)
  13462. (setq-local org-done-keywords done-keywords)
  13463. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13464. (org-fast-tag-insert "Current" current c-face "\n\n")
  13465. (org-fast-tag-show-exit exit-after-next)
  13466. (org-set-current-tags-overlay current ov-prefix)
  13467. (setq tbl fulltable char ?a cnt 0)
  13468. (while (setq e (pop tbl))
  13469. (cond
  13470. ((eq (car e) :startgroup)
  13471. (push '() groups) (setq ingroup t)
  13472. (unless (zerop cnt)
  13473. (setq cnt 0)
  13474. (insert "\n"))
  13475. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13476. ((eq (car e) :endgroup)
  13477. (setq ingroup nil cnt 0)
  13478. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13479. ((eq (car e) :startgrouptag)
  13480. (setq intaggroup t)
  13481. (unless (zerop cnt)
  13482. (setq cnt 0)
  13483. (insert "\n"))
  13484. (insert "[ "))
  13485. ((eq (car e) :endgrouptag)
  13486. (setq intaggroup nil cnt 0)
  13487. (insert "]\n"))
  13488. ((equal e '(:newline))
  13489. (unless (zerop cnt)
  13490. (setq cnt 0)
  13491. (insert "\n")
  13492. (setq e (car tbl))
  13493. (while (equal (car tbl) '(:newline))
  13494. (insert "\n")
  13495. (setq tbl (cdr tbl)))))
  13496. ((equal e '(:grouptags)) (insert " : "))
  13497. (t
  13498. (setq tg (copy-sequence (car e)) c2 nil)
  13499. (if (cdr e)
  13500. (setq c (cdr e))
  13501. ;; automatically assign a character.
  13502. (setq c1 (string-to-char
  13503. (downcase (substring
  13504. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13505. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13506. (while (or (rassoc char ntable) (rassoc char table))
  13507. (setq char (1+ char)))
  13508. (setq c2 c1))
  13509. (setq c (or c2 char)))
  13510. (when ingroup (push tg (car groups)))
  13511. (setq tg (org-add-props tg nil 'face
  13512. (cond
  13513. ((not (assoc tg table))
  13514. (org-get-todo-face tg))
  13515. ((member tg current) c-face)
  13516. ((member tg inherited) i-face))))
  13517. (when (equal (caar tbl) :grouptags)
  13518. (org-add-props tg nil 'face 'org-tag-group))
  13519. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13520. (insert "[" c "] " tg (make-string
  13521. (- fwidth 4 (length tg)) ?\ ))
  13522. (push (cons tg c) ntable)
  13523. (when (= (cl-incf cnt) ncol)
  13524. (insert "\n")
  13525. (when (or ingroup intaggroup) (insert " "))
  13526. (setq cnt 0)))))
  13527. (setq ntable (nreverse ntable))
  13528. (insert "\n")
  13529. (goto-char (point-min))
  13530. (unless expert (org-fit-window-to-buffer))
  13531. (setq rtn
  13532. (catch 'exit
  13533. (while t
  13534. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13535. (if (not groups) "no " "")
  13536. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13537. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13538. (setq org-last-tag-selection-key c)
  13539. (cond
  13540. ((= c ?\r) (throw 'exit t))
  13541. ((= c ?!)
  13542. (setq groups (not groups))
  13543. (goto-char (point-min))
  13544. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13545. ((= c ?\C-c)
  13546. (if (not expert)
  13547. (org-fast-tag-show-exit
  13548. (setq exit-after-next (not exit-after-next)))
  13549. (setq expert nil)
  13550. (delete-other-windows)
  13551. (set-window-buffer (split-window-vertically) " *Org tags*")
  13552. (org-switch-to-buffer-other-window " *Org tags*")
  13553. (org-fit-window-to-buffer)))
  13554. ((or (= c ?\C-g)
  13555. (and (= c ?q) (not (rassoc c ntable))))
  13556. (delete-overlay org-tags-overlay)
  13557. (setq quit-flag t))
  13558. ((= c ?\ )
  13559. (setq current nil)
  13560. (when exit-after-next (setq exit-after-next 'now)))
  13561. ((= c ?\t)
  13562. (condition-case nil
  13563. (setq tg (completing-read
  13564. "Tag: "
  13565. (or buffer-tags
  13566. (with-current-buffer buf
  13567. (setq buffer-tags
  13568. (org-get-buffer-tags))))))
  13569. (quit (setq tg "")))
  13570. (when (string-match "\\S-" tg)
  13571. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13572. (if (member tg current)
  13573. (setq current (delete tg current))
  13574. (push tg current)))
  13575. (when exit-after-next (setq exit-after-next 'now)))
  13576. ((setq e (rassoc c todo-table) tg (car e))
  13577. (with-current-buffer buf
  13578. (save-excursion (org-todo tg)))
  13579. (when exit-after-next (setq exit-after-next 'now)))
  13580. ((setq e (rassoc c ntable) tg (car e))
  13581. (if (member tg current)
  13582. (setq current (delete tg current))
  13583. (cl-loop for g in groups do
  13584. (when (member tg g)
  13585. (dolist (x g) (setq current (delete x current)))))
  13586. (push tg current))
  13587. (when exit-after-next (setq exit-after-next 'now))))
  13588. ;; Create a sorted list
  13589. (setq current
  13590. (sort current
  13591. (lambda (a b)
  13592. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13593. (when (eq exit-after-next 'now) (throw 'exit t))
  13594. (goto-char (point-min))
  13595. (beginning-of-line 2)
  13596. (delete-region (point) (point-at-eol))
  13597. (org-fast-tag-insert "Current" current c-face)
  13598. (org-set-current-tags-overlay current ov-prefix)
  13599. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13600. (setq tg (match-string 1))
  13601. (add-text-properties
  13602. (match-beginning 1) (match-end 1)
  13603. (list 'face
  13604. (cond
  13605. ((member tg current) c-face)
  13606. ((member tg inherited) i-face)
  13607. (t (get-text-property (match-beginning 1) 'face))))))
  13608. (goto-char (point-min)))))
  13609. (delete-overlay org-tags-overlay)
  13610. (if rtn
  13611. (mapconcat 'identity current ":")
  13612. nil))))
  13613. (defun org-get-tags-string ()
  13614. "Get the TAGS string in the current headline."
  13615. (unless (org-at-heading-p t)
  13616. (user-error "Not on a heading"))
  13617. (save-excursion
  13618. (beginning-of-line 1)
  13619. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13620. (match-string-no-properties 1)
  13621. "")))
  13622. (defun org-get-tags ()
  13623. "Get the list of tags specified in the current headline."
  13624. (org-split-string (org-get-tags-string) ":"))
  13625. (defun org-get-buffer-tags ()
  13626. "Get a table of all tags used in the buffer, for completion."
  13627. (org-with-wide-buffer
  13628. (goto-char (point-min))
  13629. (let ((tag-re (concat org-outline-regexp-bol
  13630. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13631. tags)
  13632. (while (re-search-forward tag-re nil t)
  13633. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13634. (push tag tags)))
  13635. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13636. ;;;; The mapping API
  13637. (defvar org-agenda-skip-comment-trees)
  13638. (defvar org-agenda-skip-function)
  13639. (defun org-map-entries (func &optional match scope &rest skip)
  13640. "Call FUNC at each headline selected by MATCH in SCOPE.
  13641. FUNC is a function or a lisp form. The function will be called without
  13642. arguments, with the cursor positioned at the beginning of the headline.
  13643. The return values of all calls to the function will be collected and
  13644. returned as a list.
  13645. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13646. does not need to preserve point. After evaluation, the cursor will be
  13647. moved to the end of the line (presumably of the headline of the
  13648. processed entry) and search continues from there. Under some
  13649. circumstances, this may not produce the wanted results. For example,
  13650. if you have removed (e.g. archived) the current (sub)tree it could
  13651. mean that the next entry will be skipped entirely. In such cases, you
  13652. can specify the position from where search should continue by making
  13653. FUNC set the variable `org-map-continue-from' to the desired buffer
  13654. position.
  13655. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13656. Only headlines that are matched by this query will be considered during
  13657. the iteration. When MATCH is nil or t, all headlines will be
  13658. visited by the iteration.
  13659. SCOPE determines the scope of this command. It can be any of:
  13660. nil The current buffer, respecting the restriction if any
  13661. tree The subtree started with the entry at point
  13662. region The entries within the active region, if any
  13663. region-start-level
  13664. The entries within the active region, but only those at
  13665. the same level than the first one.
  13666. file The current buffer, without restriction
  13667. file-with-archives
  13668. The current buffer, and any archives associated with it
  13669. agenda All agenda files
  13670. agenda-with-archives
  13671. All agenda files with any archive files associated with them
  13672. \(file1 file2 ...)
  13673. If this is a list, all files in the list will be scanned
  13674. The remaining args are treated as settings for the skipping facilities of
  13675. the scanner. The following items can be given here:
  13676. archive skip trees with the archive tag
  13677. comment skip trees with the COMMENT keyword
  13678. function or Emacs Lisp form:
  13679. will be used as value for `org-agenda-skip-function', so
  13680. whenever the function returns a position, FUNC will not be
  13681. called for that entry and search will continue from the
  13682. position returned
  13683. If your function needs to retrieve the tags including inherited tags
  13684. at the *current* entry, you can use the value of the variable
  13685. `org-scanner-tags' which will be much faster than getting the value
  13686. with `org-get-tags-at'. If your function gets properties with
  13687. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13688. to t around the call to `org-entry-properties' to get the same speedup.
  13689. Note that if your function moves around to retrieve tags and properties at
  13690. a *different* entry, you cannot use these techniques."
  13691. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13692. (not (org-region-active-p)))
  13693. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13694. (org-agenda-skip-archived-trees (memq 'archive skip))
  13695. (org-agenda-skip-comment-trees (memq 'comment skip))
  13696. (org-agenda-skip-function
  13697. (car (org-delete-all '(comment archive) skip)))
  13698. (org-tags-match-list-sublevels t)
  13699. (start-level (eq scope 'region-start-level))
  13700. matcher res
  13701. org-todo-keywords-for-agenda
  13702. org-done-keywords-for-agenda
  13703. org-todo-keyword-alist-for-agenda
  13704. org-tag-alist-for-agenda
  13705. org--matcher-tags-todo-only)
  13706. (cond
  13707. ((eq match t) (setq matcher t))
  13708. ((eq match nil) (setq matcher t))
  13709. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13710. (save-excursion
  13711. (save-restriction
  13712. (cond ((eq scope 'tree)
  13713. (org-back-to-heading t)
  13714. (org-narrow-to-subtree)
  13715. (setq scope nil))
  13716. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13717. (org-region-active-p))
  13718. ;; If needed, set start-level to a string like "2"
  13719. (when start-level
  13720. (save-excursion
  13721. (goto-char (region-beginning))
  13722. (unless (org-at-heading-p) (outline-next-heading))
  13723. (setq start-level (org-current-level))))
  13724. (narrow-to-region (region-beginning)
  13725. (save-excursion
  13726. (goto-char (region-end))
  13727. (unless (and (bolp) (org-at-heading-p))
  13728. (outline-next-heading))
  13729. (point)))
  13730. (setq scope nil)))
  13731. (if (not scope)
  13732. (progn
  13733. (org-agenda-prepare-buffers
  13734. (and buffer-file-name (list buffer-file-name)))
  13735. (setq res
  13736. (org-scan-tags
  13737. func matcher org--matcher-tags-todo-only start-level)))
  13738. ;; Get the right scope
  13739. (cond
  13740. ((and scope (listp scope) (symbolp (car scope)))
  13741. (setq scope (eval scope)))
  13742. ((eq scope 'agenda)
  13743. (setq scope (org-agenda-files t)))
  13744. ((eq scope 'agenda-with-archives)
  13745. (setq scope (org-agenda-files t))
  13746. (setq scope (org-add-archive-files scope)))
  13747. ((eq scope 'file)
  13748. (setq scope (and buffer-file-name (list buffer-file-name))))
  13749. ((eq scope 'file-with-archives)
  13750. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13751. (org-agenda-prepare-buffers scope)
  13752. (dolist (file scope)
  13753. (with-current-buffer (org-find-base-buffer-visiting file)
  13754. (org-with-wide-buffer
  13755. (goto-char (point-min))
  13756. (setq res
  13757. (append
  13758. res
  13759. (org-scan-tags
  13760. func matcher org--matcher-tags-todo-only)))))))))
  13761. res)))
  13762. ;;; Properties API
  13763. (defconst org-special-properties
  13764. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13765. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13766. "The special properties valid in Org mode.
  13767. These are properties that are not defined in the property drawer,
  13768. but in some other way.")
  13769. (defconst org-default-properties
  13770. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13771. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13772. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13773. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13774. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13775. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13776. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13777. "Some properties that are used by Org mode for various purposes.
  13778. Being in this list makes sure that they are offered for completion.")
  13779. (defun org--valid-property-p (property)
  13780. "Non nil when string PROPERTY is a valid property name."
  13781. (not
  13782. (or (equal property "")
  13783. (string-match-p "\\s-" property))))
  13784. (defun org--update-property-plist (key val props)
  13785. "Associate KEY to VAL in alist PROPS.
  13786. Modifications are made by side-effect. Return new alist."
  13787. (let* ((appending (string= (substring key -1) "+"))
  13788. (key (if appending (substring key 0 -1) key))
  13789. (old (assoc-string key props t)))
  13790. (if (not old) (cons (cons key val) props)
  13791. (setcdr old (if appending (concat (cdr old) " " val) val))
  13792. props)))
  13793. (defun org-get-property-block (&optional beg force)
  13794. "Return the (beg . end) range of the body of the property drawer.
  13795. BEG is the beginning of the current subtree, or of the part
  13796. before the first headline. If it is not given, it will be found.
  13797. If the drawer does not exist, create it if FORCE is non-nil, or
  13798. return nil."
  13799. (org-with-wide-buffer
  13800. (when beg (goto-char beg))
  13801. (unless (org-before-first-heading-p)
  13802. (let ((beg (cond (beg)
  13803. ((or (not (featurep 'org-inlinetask))
  13804. (org-inlinetask-in-task-p))
  13805. (org-back-to-heading t))
  13806. (t (org-with-limited-levels (org-back-to-heading t))))))
  13807. (forward-line)
  13808. (when (looking-at-p org-planning-line-re) (forward-line))
  13809. (cond ((looking-at org-property-drawer-re)
  13810. (forward-line)
  13811. (cons (point) (progn (goto-char (match-end 0))
  13812. (line-beginning-position))))
  13813. (force
  13814. (goto-char beg)
  13815. (org-insert-property-drawer)
  13816. (let ((pos (save-excursion (search-forward ":END:")
  13817. (line-beginning-position))))
  13818. (cons pos pos))))))))
  13819. (defun org-at-property-p ()
  13820. "Non-nil when point is inside a property drawer.
  13821. See `org-property-re' for match data, if applicable."
  13822. (save-excursion
  13823. (beginning-of-line)
  13824. (and (looking-at org-property-re)
  13825. (let ((property-drawer (save-match-data (org-get-property-block))))
  13826. (and property-drawer
  13827. (>= (point) (car property-drawer))
  13828. (< (point) (cdr property-drawer)))))))
  13829. (defun org-property-action ()
  13830. "Do an action on properties."
  13831. (interactive)
  13832. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13833. (let ((c (read-char-exclusive)))
  13834. (cl-case c
  13835. (?s (call-interactively #'org-set-property))
  13836. (?d (call-interactively #'org-delete-property))
  13837. (?D (call-interactively #'org-delete-property-globally))
  13838. (?c (call-interactively #'org-compute-property-at-point))
  13839. (otherwise (user-error "No such property action %c" c)))))
  13840. (defun org-inc-effort ()
  13841. "Increment the value of the effort property in the current entry."
  13842. (interactive)
  13843. (org-set-effort nil t))
  13844. (defvar org-clock-effort) ; Defined in org-clock.el.
  13845. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13846. (defun org-set-effort (&optional value increment)
  13847. "Set the effort property of the current entry.
  13848. With numerical prefix arg, use the nth allowed value, 0 stands for the
  13849. 10th allowed value.
  13850. When INCREMENT is non-nil, set the property to the next allowed value."
  13851. (interactive "P")
  13852. (when (equal value 0) (setq value 10))
  13853. (let* ((completion-ignore-case t)
  13854. (prop org-effort-property)
  13855. (cur (org-entry-get nil prop))
  13856. (allowed (org-property-get-allowed-values nil prop 'table))
  13857. (existing (mapcar 'list (org-property-values prop)))
  13858. (heading (nth 4 (org-heading-components)))
  13859. rpl
  13860. (val (cond
  13861. ((stringp value) value)
  13862. ((and allowed (integerp value))
  13863. (or (car (nth (1- value) allowed))
  13864. (car (org-last allowed))))
  13865. ((and allowed increment)
  13866. (or (cl-caadr (member (list cur) allowed))
  13867. (user-error "Allowed effort values are not set")))
  13868. (allowed
  13869. (message "Select 1-9,0, [RET%s]: %s"
  13870. (if cur (concat "=" cur) "")
  13871. (mapconcat 'car allowed " "))
  13872. (setq rpl (read-char-exclusive))
  13873. (if (equal rpl ?\r)
  13874. cur
  13875. (setq rpl (- rpl ?0))
  13876. (when (equal rpl 0) (setq rpl 10))
  13877. (if (and (> rpl 0) (<= rpl (length allowed)))
  13878. (car (nth (1- rpl) allowed))
  13879. (org-completing-read "Effort: " allowed nil))))
  13880. (t
  13881. (org-completing-read
  13882. (concat "Effort" (and cur (string-match "\\S-" cur)
  13883. (concat " [" cur "]"))
  13884. ": ")
  13885. existing nil nil "" nil cur)))))
  13886. (unless (equal (org-entry-get nil prop) val)
  13887. (org-entry-put nil prop val))
  13888. (org-refresh-property
  13889. '((effort . identity)
  13890. (effort-minutes . org-duration-to-minutes))
  13891. val)
  13892. (when (equal heading (bound-and-true-p org-clock-current-task))
  13893. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  13894. (org-clock-update-mode-line))
  13895. (message "%s is now %s" prop val)))
  13896. (defun org-entry-properties (&optional pom which)
  13897. "Get all properties of the current entry.
  13898. When POM is a buffer position, get all properties from the entry
  13899. there instead.
  13900. This includes the TODO keyword, the tags, time strings for
  13901. deadline, scheduled, and clocking, and any additional properties
  13902. defined in the entry.
  13903. If WHICH is nil or `all', get all properties. If WHICH is
  13904. `special' or `standard', only get that subclass. If WHICH is
  13905. a string, only get that property.
  13906. Return value is an alist. Keys are properties, as upcased
  13907. strings."
  13908. (org-with-point-at pom
  13909. (when (and (derived-mode-p 'org-mode)
  13910. (ignore-errors (org-back-to-heading t)))
  13911. (catch 'exit
  13912. (let* ((beg (point))
  13913. (specific (and (stringp which) (upcase which)))
  13914. (which (cond ((not specific) which)
  13915. ((member specific org-special-properties) 'special)
  13916. (t 'standard)))
  13917. props)
  13918. ;; Get the special properties, like TODO and TAGS.
  13919. (when (memq which '(nil all special))
  13920. (when (or (not specific) (string= specific "CLOCKSUM"))
  13921. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13922. (when clocksum
  13923. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13924. props)))
  13925. (when specific (throw 'exit props)))
  13926. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13927. (let ((clocksumt (get-text-property (point)
  13928. :org-clock-minutes-today)))
  13929. (when clocksumt
  13930. (push (cons "CLOCKSUM_T"
  13931. (org-duration-from-minutes clocksumt))
  13932. props)))
  13933. (when specific (throw 'exit props)))
  13934. (when (or (not specific) (string= specific "ITEM"))
  13935. (let ((case-fold-search nil))
  13936. (when (looking-at org-complex-heading-regexp)
  13937. (push (cons "ITEM"
  13938. (let ((title (match-string-no-properties 4)))
  13939. (if (org-string-nw-p title)
  13940. (org-remove-tabs title)
  13941. "")))
  13942. props)))
  13943. (when specific (throw 'exit props)))
  13944. (when (or (not specific) (string= specific "TODO"))
  13945. (let ((case-fold-search nil))
  13946. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13947. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13948. (when specific (throw 'exit props)))
  13949. (when (or (not specific) (string= specific "PRIORITY"))
  13950. (push (cons "PRIORITY"
  13951. (if (looking-at org-priority-regexp)
  13952. (match-string-no-properties 2)
  13953. (char-to-string org-default-priority)))
  13954. props)
  13955. (when specific (throw 'exit props)))
  13956. (when (or (not specific) (string= specific "FILE"))
  13957. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13958. props)
  13959. (when specific (throw 'exit props)))
  13960. (when (or (not specific) (string= specific "TAGS"))
  13961. (let ((value (org-string-nw-p (org-get-tags-string))))
  13962. (when value (push (cons "TAGS" value) props)))
  13963. (when specific (throw 'exit props)))
  13964. (when (or (not specific) (string= specific "ALLTAGS"))
  13965. (let ((value (org-get-tags-at)))
  13966. (when value
  13967. (push (cons "ALLTAGS"
  13968. (format ":%s:" (mapconcat #'identity value ":")))
  13969. props)))
  13970. (when specific (throw 'exit props)))
  13971. (when (or (not specific) (string= specific "BLOCKED"))
  13972. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13973. (when specific (throw 'exit props)))
  13974. (when (or (not specific)
  13975. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13976. (forward-line)
  13977. (when (looking-at-p org-planning-line-re)
  13978. (end-of-line)
  13979. (let ((bol (line-beginning-position))
  13980. ;; Backward compatibility: time keywords used to
  13981. ;; be configurable (before 8.3). Make sure we
  13982. ;; get the correct keyword.
  13983. (key-assoc `(("CLOSED" . ,org-closed-string)
  13984. ("DEADLINE" . ,org-deadline-string)
  13985. ("SCHEDULED" . ,org-scheduled-string))))
  13986. (dolist (pair (if specific (list (assoc specific key-assoc))
  13987. key-assoc))
  13988. (save-excursion
  13989. (when (search-backward (cdr pair) bol t)
  13990. (goto-char (match-end 0))
  13991. (skip-chars-forward " \t")
  13992. (and (looking-at org-ts-regexp-both)
  13993. (push (cons (car pair)
  13994. (match-string-no-properties 0))
  13995. props)))))))
  13996. (when specific (throw 'exit props)))
  13997. (when (or (not specific)
  13998. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13999. (let ((find-ts
  14000. (lambda (end ts)
  14001. ;; Fix next time-stamp before END. TS is the
  14002. ;; list of time-stamps found so far.
  14003. (let ((ts ts)
  14004. (regexp (cond
  14005. ((string= specific "TIMESTAMP")
  14006. org-ts-regexp)
  14007. ((string= specific "TIMESTAMP_IA")
  14008. org-ts-regexp-inactive)
  14009. ((assoc "TIMESTAMP_IA" ts)
  14010. org-ts-regexp)
  14011. ((assoc "TIMESTAMP" ts)
  14012. org-ts-regexp-inactive)
  14013. (t org-ts-regexp-both))))
  14014. (catch 'next
  14015. (while (re-search-forward regexp end t)
  14016. (backward-char)
  14017. (let ((object (org-element-context)))
  14018. ;; Accept to match timestamps in node
  14019. ;; properties, too.
  14020. (when (memq (org-element-type object)
  14021. '(node-property timestamp))
  14022. (let ((type
  14023. (org-element-property :type object)))
  14024. (cond
  14025. ((and (memq type '(active active-range))
  14026. (not (equal specific "TIMESTAMP_IA")))
  14027. (unless (assoc "TIMESTAMP" ts)
  14028. (push (cons "TIMESTAMP"
  14029. (org-element-property
  14030. :raw-value object))
  14031. ts)
  14032. (when specific (throw 'exit ts))))
  14033. ((and (memq type '(inactive inactive-range))
  14034. (not (string= specific "TIMESTAMP")))
  14035. (unless (assoc "TIMESTAMP_IA" ts)
  14036. (push (cons "TIMESTAMP_IA"
  14037. (org-element-property
  14038. :raw-value object))
  14039. ts)
  14040. (when specific (throw 'exit ts))))))
  14041. ;; Both timestamp types are found,
  14042. ;; move to next part.
  14043. (when (= (length ts) 2) (throw 'next ts)))))
  14044. ts)))))
  14045. (goto-char beg)
  14046. ;; First look for timestamps within headline.
  14047. (let ((ts (funcall find-ts (line-end-position) nil)))
  14048. (if (= (length ts) 2) (setq props (nconc ts props))
  14049. ;; Then find timestamps in the section, skipping
  14050. ;; planning line.
  14051. (let ((end (save-excursion (outline-next-heading))))
  14052. (forward-line)
  14053. (when (looking-at-p org-planning-line-re) (forward-line))
  14054. (setq props (nconc (funcall find-ts end ts) props))))))))
  14055. ;; Get the standard properties, like :PROP:.
  14056. (when (memq which '(nil all standard))
  14057. ;; If we are looking after a specific property, delegate
  14058. ;; to `org-entry-get', which is faster. However, make an
  14059. ;; exception for "CATEGORY", since it can be also set
  14060. ;; through keywords (i.e. #+CATEGORY).
  14061. (if (and specific (not (equal specific "CATEGORY")))
  14062. (let ((value (org-entry-get beg specific nil t)))
  14063. (throw 'exit (and value (list (cons specific value)))))
  14064. (let ((range (org-get-property-block beg)))
  14065. (when range
  14066. (let ((end (cdr range)) seen-base)
  14067. (goto-char (car range))
  14068. ;; Unlike to `org--update-property-plist', we
  14069. ;; handle the case where base values is found
  14070. ;; after its extension. We also forbid standard
  14071. ;; properties to be named as special properties.
  14072. (while (re-search-forward org-property-re end t)
  14073. (let* ((key (upcase (match-string-no-properties 2)))
  14074. (extendp (string-match-p "\\+\\'" key))
  14075. (key-base (if extendp (substring key 0 -1) key))
  14076. (value (match-string-no-properties 3)))
  14077. (cond
  14078. ((member-ignore-case key-base org-special-properties))
  14079. (extendp
  14080. (setq props
  14081. (org--update-property-plist key value props)))
  14082. ((member key seen-base))
  14083. (t (push key seen-base)
  14084. (let ((p (assoc-string key props t)))
  14085. (if p (setcdr p (concat value " " (cdr p)))
  14086. (push (cons key value) props))))))))))))
  14087. (unless (assoc "CATEGORY" props)
  14088. (push (cons "CATEGORY" (org-get-category beg)) props)
  14089. (when (string= specific "CATEGORY") (throw 'exit props)))
  14090. ;; Return value.
  14091. props)))))
  14092. (defun org--property-local-values (property literal-nil)
  14093. "Return value for PROPERTY in current entry.
  14094. Value is a list whose car is the base value for PROPERTY and cdr
  14095. a list of accumulated values. Return nil if neither is found in
  14096. the entry. Also return nil when PROPERTY is set to \"nil\",
  14097. unless LITERAL-NIL is non-nil."
  14098. (let ((range (org-get-property-block)))
  14099. (when range
  14100. (goto-char (car range))
  14101. (let* ((case-fold-search t)
  14102. (end (cdr range))
  14103. (value
  14104. ;; Base value.
  14105. (save-excursion
  14106. (let ((v (and (re-search-forward
  14107. (org-re-property property nil t) end t)
  14108. (match-string-no-properties 3))))
  14109. (list (if literal-nil v (org-not-nil v)))))))
  14110. ;; Find additional values.
  14111. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14112. (while (re-search-forward property+ end t)
  14113. (push (match-string-no-properties 3) value)))
  14114. ;; Return final values.
  14115. (and (not (equal value '(nil))) (nreverse value))))))
  14116. (defun org--property-global-value (property literal-nil)
  14117. "Return value for PROPERTY in current buffer.
  14118. Return value is a string. Return nil if property is not set
  14119. globally. Also return nil when PROPERTY is set to \"nil\",
  14120. unless LITERAL-NIL is non-nil."
  14121. (let ((global
  14122. (cdr (or (assoc-string property org-file-properties t)
  14123. (assoc-string property org-global-properties t)
  14124. (assoc-string property org-global-properties-fixed t)))))
  14125. (if literal-nil global (org-not-nil global))))
  14126. (defun org-entry-get (pom property &optional inherit literal-nil)
  14127. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14128. If INHERIT is non-nil and the entry does not have the property,
  14129. then also check higher levels of the hierarchy. If INHERIT is
  14130. the symbol `selective', use inheritance only if the setting in
  14131. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14132. If the property is present but empty, the return value is the
  14133. empty string. If the property is not present at all, nil is
  14134. returned. In any other case, return the value as a string.
  14135. Search is case-insensitive.
  14136. If LITERAL-NIL is set, return the string value \"nil\" as
  14137. a string, do not interpret it as the list atom nil. This is used
  14138. for inheritance when a \"nil\" value can supersede a non-nil
  14139. value higher up the hierarchy."
  14140. (org-with-point-at pom
  14141. (cond
  14142. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14143. ;; We need a special property. Use `org-entry-properties' to
  14144. ;; retrieve it, but specify the wanted property.
  14145. (cdr (assoc-string property (org-entry-properties nil property))))
  14146. ((and inherit
  14147. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14148. (org-entry-get-with-inheritance property literal-nil))
  14149. (t
  14150. (let* ((local (org--property-local-values property literal-nil))
  14151. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14152. (if literal-nil value (org-not-nil value)))))))
  14153. (defun org-property-or-variable-value (var &optional inherit)
  14154. "Check if there is a property fixing the value of VAR.
  14155. If yes, return this value. If not, return the current value of the variable."
  14156. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14157. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14158. (read prop)
  14159. (symbol-value var))))
  14160. (defun org-entry-delete (pom property)
  14161. "Delete PROPERTY from entry at point-or-marker POM.
  14162. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14163. non-nil when a property was removed."
  14164. (org-with-point-at pom
  14165. (pcase (org-get-property-block)
  14166. (`(,begin . ,origin)
  14167. (let* ((end (copy-marker origin))
  14168. (re (org-re-property
  14169. (concat (regexp-quote property) "\\+?") t t)))
  14170. (goto-char begin)
  14171. (while (re-search-forward re end t)
  14172. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14173. ;; If drawer is empty, remove it altogether.
  14174. (when (= begin end)
  14175. (delete-region (line-beginning-position 0)
  14176. (line-beginning-position 2)))
  14177. ;; Return non-nil if some property was removed.
  14178. (prog1 (/= end origin) (set-marker end nil))))
  14179. (_ nil))))
  14180. ;; Multi-values properties are properties that contain multiple values
  14181. ;; These values are assumed to be single words, separated by whitespace.
  14182. (defun org-entry-add-to-multivalued-property (pom property value)
  14183. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14184. (let* ((old (org-entry-get pom property))
  14185. (values (and old (split-string old))))
  14186. (setq value (org-entry-protect-space value))
  14187. (unless (member value values)
  14188. (setq values (append values (list value)))
  14189. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14190. (defun org-entry-remove-from-multivalued-property (pom property value)
  14191. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14192. (let* ((old (org-entry-get pom property))
  14193. (values (and old (split-string old))))
  14194. (setq value (org-entry-protect-space value))
  14195. (when (member value values)
  14196. (setq values (delete value values))
  14197. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14198. (defun org-entry-member-in-multivalued-property (pom property value)
  14199. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14200. (let* ((old (org-entry-get pom property))
  14201. (values (and old (split-string old))))
  14202. (setq value (org-entry-protect-space value))
  14203. (member value values)))
  14204. (defun org-entry-get-multivalued-property (pom property)
  14205. "Return a list of values in a multivalued property."
  14206. (let* ((value (org-entry-get pom property))
  14207. (values (and value (split-string value))))
  14208. (mapcar #'org-entry-restore-space values)))
  14209. (defun org-entry-put-multivalued-property (pom property &rest values)
  14210. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14211. VALUES should be a list of strings. Spaces will be protected."
  14212. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  14213. (let* ((value (org-entry-get pom property))
  14214. (values (and value (split-string value))))
  14215. (mapcar #'org-entry-restore-space values)))
  14216. (defun org-entry-protect-space (s)
  14217. "Protect spaces and newline in string S."
  14218. (while (string-match " " s)
  14219. (setq s (replace-match "%20" t t s)))
  14220. (while (string-match "\n" s)
  14221. (setq s (replace-match "%0A" t t s)))
  14222. s)
  14223. (defun org-entry-restore-space (s)
  14224. "Restore spaces and newline in string S."
  14225. (while (string-match "%20" s)
  14226. (setq s (replace-match " " t t s)))
  14227. (while (string-match "%0A" s)
  14228. (setq s (replace-match "\n" t t s)))
  14229. s)
  14230. (defvar org-entry-property-inherited-from (make-marker)
  14231. "Marker pointing to the entry from where a property was inherited.
  14232. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14233. location of the entry where the inheritance search matched. If there was
  14234. no match, the marker will point nowhere.
  14235. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14236. is set.")
  14237. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14238. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14239. The search will stop at the first ancestor which has the property defined.
  14240. If the value found is \"nil\", return nil to show that the property
  14241. should be considered as undefined (this is the meaning of nil here).
  14242. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14243. (move-marker org-entry-property-inherited-from nil)
  14244. (org-with-wide-buffer
  14245. (let (value)
  14246. (catch 'exit
  14247. (while t
  14248. (let ((v (org--property-local-values property literal-nil)))
  14249. (when v
  14250. (setq value
  14251. (concat (mapconcat #'identity (delq nil v) " ")
  14252. (and value " ")
  14253. value)))
  14254. (cond
  14255. ((car v)
  14256. (org-back-to-heading t)
  14257. (move-marker org-entry-property-inherited-from (point))
  14258. (throw 'exit nil))
  14259. ((org-up-heading-safe))
  14260. (t
  14261. (let ((global (org--property-global-value property literal-nil)))
  14262. (cond ((not global))
  14263. (value (setq value (concat global " " value)))
  14264. (t (setq value global))))
  14265. (throw 'exit nil))))))
  14266. (if literal-nil value (org-not-nil value)))))
  14267. (defvar org-property-changed-functions nil
  14268. "Hook called when the value of a property has changed.
  14269. Each hook function should accept two arguments, the name of the property
  14270. and the new value.")
  14271. (defun org-entry-put (pom property value)
  14272. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14273. If the value is nil, it is converted to the empty string. If it
  14274. is not a string, an error is raised. Also raise an error on
  14275. invalid property names.
  14276. PROPERTY can be any regular property (see
  14277. `org-special-properties'). It can also be \"TODO\",
  14278. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14279. For the last two properties, VALUE may have any of the special
  14280. values \"earlier\" and \"later\". The function then increases or
  14281. decreases scheduled or deadline date by one day."
  14282. (cond ((null value) (setq value ""))
  14283. ((not (stringp value)) (error "Properties values should be strings"))
  14284. ((not (org--valid-property-p property))
  14285. (user-error "Invalid property name: \"%s\"" property)))
  14286. (org-with-point-at pom
  14287. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14288. (org-back-to-heading t)
  14289. (org-with-limited-levels (org-back-to-heading t)))
  14290. (let ((beg (point)))
  14291. (cond
  14292. ((equal property "TODO")
  14293. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14294. ((not (member value org-todo-keywords-1))
  14295. (user-error "\"%s\" is not a valid TODO state" value)))
  14296. (org-todo value)
  14297. (org-set-tags nil 'align))
  14298. ((equal property "PRIORITY")
  14299. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14300. (org-set-tags nil 'align))
  14301. ((equal property "SCHEDULED")
  14302. (forward-line)
  14303. (if (and (looking-at-p org-planning-line-re)
  14304. (re-search-forward
  14305. org-scheduled-time-regexp (line-end-position) t))
  14306. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14307. ((string= value "later") (org-timestamp-change 1 'day))
  14308. ((string= value "") (org-schedule '(4)))
  14309. (t (org-schedule nil value)))
  14310. (if (member value '("earlier" "later" ""))
  14311. (call-interactively #'org-schedule)
  14312. (org-schedule nil value))))
  14313. ((equal property "DEADLINE")
  14314. (forward-line)
  14315. (if (and (looking-at-p org-planning-line-re)
  14316. (re-search-forward
  14317. org-deadline-time-regexp (line-end-position) t))
  14318. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14319. ((string= value "later") (org-timestamp-change 1 'day))
  14320. ((string= value "") (org-deadline '(4)))
  14321. (t (org-deadline nil value)))
  14322. (if (member value '("earlier" "later" ""))
  14323. (call-interactively #'org-deadline)
  14324. (org-deadline nil value))))
  14325. ((member property org-special-properties)
  14326. (error "The %s property cannot be set with `org-entry-put'" property))
  14327. (t
  14328. (let* ((range (org-get-property-block beg 'force))
  14329. (end (cdr range))
  14330. (case-fold-search t))
  14331. (goto-char (car range))
  14332. (if (re-search-forward (org-re-property property nil t) end t)
  14333. (progn (delete-region (match-beginning 0) (match-end 0))
  14334. (goto-char (match-beginning 0)))
  14335. (goto-char end)
  14336. (insert "\n")
  14337. (backward-char))
  14338. (insert ":" property ":")
  14339. (when value (insert " " value))
  14340. (org-indent-line)))))
  14341. (run-hook-with-args 'org-property-changed-functions property value)))
  14342. (defun org-buffer-property-keys (&optional specials defaults columns)
  14343. "Get all property keys in the current buffer.
  14344. When SPECIALS is non-nil, also list the special properties that
  14345. reflect things like tags and TODO state.
  14346. When DEFAULTS is non-nil, also include properties that has
  14347. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14348. DESCRIPTION, LOCATION, and LOGGING and others.
  14349. When COLUMNS in non-nil, also include property names given in
  14350. COLUMN formats in the current buffer."
  14351. (let ((case-fold-search t)
  14352. (props (append
  14353. (and specials org-special-properties)
  14354. (and defaults (cons org-effort-property org-default-properties))
  14355. nil)))
  14356. (org-with-wide-buffer
  14357. (goto-char (point-min))
  14358. (while (re-search-forward org-property-start-re nil t)
  14359. (catch :skip
  14360. (let ((range (org-get-property-block)))
  14361. (unless range (throw :skip nil))
  14362. (goto-char (car range))
  14363. (let ((begin (car range))
  14364. (end (cdr range)))
  14365. ;; Make sure that found property block is not located
  14366. ;; before current point, as it would generate an infloop.
  14367. ;; It can happen, for example, in the following
  14368. ;; situation:
  14369. ;;
  14370. ;; * Headline
  14371. ;; :PROPERTIES:
  14372. ;; ...
  14373. ;; :END:
  14374. ;; *************** Inlinetask
  14375. ;; #+BEGIN_EXAMPLE
  14376. ;; :PROPERTIES:
  14377. ;; #+END_EXAMPLE
  14378. ;;
  14379. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14380. (while (< (point) end)
  14381. (let ((p (progn (looking-at org-property-re)
  14382. (match-string-no-properties 2))))
  14383. ;; Only add true property name, not extension symbol.
  14384. (push (if (not (string-match-p "\\+\\'" p)) p
  14385. (substring p 0 -1))
  14386. props))
  14387. (forward-line))))
  14388. (outline-next-heading)))
  14389. (when columns
  14390. (goto-char (point-min))
  14391. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14392. (let ((element (org-element-at-point)))
  14393. (when (memq (org-element-type element) '(keyword node-property))
  14394. (let ((value (org-element-property :value element))
  14395. (start 0))
  14396. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14397. \\(?:{[^}]+}\\)?"
  14398. value start)
  14399. (setq start (match-end 0))
  14400. (let ((p (match-string-no-properties 1 value)))
  14401. (unless (member-ignore-case p org-special-properties)
  14402. (push p props))))))))))
  14403. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14404. (defun org-property-values (key)
  14405. "List all non-nil values of property KEY in current buffer."
  14406. (org-with-wide-buffer
  14407. (goto-char (point-min))
  14408. (let ((case-fold-search t)
  14409. (re (org-re-property key))
  14410. values)
  14411. (while (re-search-forward re nil t)
  14412. (push (org-entry-get (point) key) values))
  14413. (delete-dups values))))
  14414. (defun org-insert-property-drawer ()
  14415. "Insert a property drawer into the current entry."
  14416. (org-with-wide-buffer
  14417. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14418. (org-back-to-heading t)
  14419. (org-with-limited-levels (org-back-to-heading t)))
  14420. (forward-line)
  14421. (when (looking-at-p org-planning-line-re) (forward-line))
  14422. (unless (looking-at-p org-property-drawer-re)
  14423. ;; Make sure we start editing a line from current entry, not from
  14424. ;; next one. It prevents extending text properties or overlays
  14425. ;; belonging to the latter.
  14426. (when (bolp) (backward-char))
  14427. (let ((begin (1+ (point)))
  14428. (inhibit-read-only t))
  14429. (insert "\n:PROPERTIES:\n:END:")
  14430. (when (eobp) (insert "\n"))
  14431. (org-indent-region begin (point))))))
  14432. (defun org-insert-drawer (&optional arg drawer)
  14433. "Insert a drawer at point.
  14434. When optional argument ARG is non-nil, insert a property drawer.
  14435. Optional argument DRAWER, when non-nil, is a string representing
  14436. drawer's name. Otherwise, the user is prompted for a name.
  14437. If a region is active, insert the drawer around that region
  14438. instead.
  14439. Point is left between drawer's boundaries."
  14440. (interactive "P")
  14441. (let* ((drawer (if arg "PROPERTIES"
  14442. (or drawer (read-from-minibuffer "Drawer: ")))))
  14443. (cond
  14444. ;; With C-u, fall back on `org-insert-property-drawer'
  14445. (arg (org-insert-property-drawer))
  14446. ;; Check validity of suggested drawer's name.
  14447. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14448. (user-error "Invalid drawer name"))
  14449. ;; With an active region, insert a drawer at point.
  14450. ((not (org-region-active-p))
  14451. (progn
  14452. (unless (bolp) (insert "\n"))
  14453. (insert (format ":%s:\n\n:END:\n" drawer))
  14454. (forward-line -2)))
  14455. ;; Otherwise, insert the drawer at point
  14456. (t
  14457. (let ((rbeg (region-beginning))
  14458. (rend (copy-marker (region-end))))
  14459. (unwind-protect
  14460. (progn
  14461. (goto-char rbeg)
  14462. (beginning-of-line)
  14463. (when (save-excursion
  14464. (re-search-forward org-outline-regexp-bol rend t))
  14465. (user-error "Drawers cannot contain headlines"))
  14466. ;; Position point at the beginning of the first
  14467. ;; non-blank line in region. Insert drawer's opening
  14468. ;; there, then indent it.
  14469. (org-skip-whitespace)
  14470. (beginning-of-line)
  14471. (insert ":" drawer ":\n")
  14472. (forward-line -1)
  14473. (indent-for-tab-command)
  14474. ;; Move point to the beginning of the first blank line
  14475. ;; after the last non-blank line in region. Insert
  14476. ;; drawer's closing, then indent it.
  14477. (goto-char rend)
  14478. (skip-chars-backward " \r\t\n")
  14479. (insert "\n:END:")
  14480. (deactivate-mark t)
  14481. (indent-for-tab-command)
  14482. (unless (eolp) (insert "\n")))
  14483. ;; Clear marker, whatever the outcome of insertion is.
  14484. (set-marker rend nil)))))))
  14485. (defvar org-property-set-functions-alist nil
  14486. "Property set function alist.
  14487. Each entry should have the following format:
  14488. (PROPERTY . READ-FUNCTION)
  14489. The read function will be called with the same argument as
  14490. `org-completing-read'.")
  14491. (defun org-set-property-function (property)
  14492. "Get the function that should be used to set PROPERTY.
  14493. This is computed according to `org-property-set-functions-alist'."
  14494. (or (cdr (assoc property org-property-set-functions-alist))
  14495. 'org-completing-read))
  14496. (defun org-read-property-value (property)
  14497. "Read PROPERTY value from user."
  14498. (let* ((completion-ignore-case t)
  14499. (allowed (org-property-get-allowed-values nil property 'table))
  14500. (cur (org-entry-get nil property))
  14501. (prompt (concat property " value"
  14502. (if (and cur (string-match "\\S-" cur))
  14503. (concat " [" cur "]") "") ": "))
  14504. (set-function (org-set-property-function property))
  14505. (val (if allowed
  14506. (funcall set-function prompt allowed nil
  14507. (not (get-text-property 0 'org-unrestricted
  14508. (caar allowed))))
  14509. (funcall set-function prompt
  14510. (mapcar 'list (org-property-values property))
  14511. nil nil "" nil cur))))
  14512. (org-trim val)))
  14513. (defvar org-last-set-property nil)
  14514. (defvar org-last-set-property-value nil)
  14515. (defun org-read-property-name ()
  14516. "Read a property name."
  14517. (let ((completion-ignore-case t)
  14518. (default-prop (or (and (org-at-property-p)
  14519. (match-string-no-properties 2))
  14520. org-last-set-property)))
  14521. (org-completing-read
  14522. (concat "Property"
  14523. (if default-prop (concat " [" default-prop "]") "")
  14524. ": ")
  14525. (mapcar #'list (org-buffer-property-keys nil t t))
  14526. nil nil nil nil default-prop)))
  14527. (defun org-set-property-and-value (use-last)
  14528. "Allow to set [PROPERTY]: [value] direction from prompt.
  14529. When use-default, don't even ask, just use the last
  14530. \"[PROPERTY]: [value]\" string from the history."
  14531. (interactive "P")
  14532. (let* ((completion-ignore-case t)
  14533. (pv (or (and use-last org-last-set-property-value)
  14534. (org-completing-read
  14535. "Enter a \"[Property]: [value]\" pair: "
  14536. nil nil nil nil nil
  14537. org-last-set-property-value)))
  14538. prop val)
  14539. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14540. (setq prop (match-string 1 pv)
  14541. val (match-string 2 pv))
  14542. (org-set-property prop val))))
  14543. (defun org-set-property (property value)
  14544. "In the current entry, set PROPERTY to VALUE.
  14545. When called interactively, this will prompt for a property name, offering
  14546. completion on existing and default properties. And then it will prompt
  14547. for a value, offering completion either on allowed values (via an inherited
  14548. xxx_ALL property) or on existing values in other instances of this property
  14549. in the current file.
  14550. Throw an error when trying to set a property with an invalid name."
  14551. (interactive (list nil nil))
  14552. (let ((property (or property (org-read-property-name))))
  14553. ;; `org-entry-put' also makes the following check, but this one
  14554. ;; avoids polluting `org-last-set-property' and
  14555. ;; `org-last-set-property-value' needlessly.
  14556. (unless (org--valid-property-p property)
  14557. (user-error "Invalid property name: \"%s\"" property))
  14558. (let ((value (or value (org-read-property-value property)))
  14559. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14560. (setq org-last-set-property property)
  14561. (setq org-last-set-property-value (concat property ": " value))
  14562. ;; Possibly postprocess the inserted value:
  14563. (when fn (setq value (funcall fn value)))
  14564. (unless (equal (org-entry-get nil property) value)
  14565. (org-entry-put nil property value)))))
  14566. (defun org-find-property (property &optional value)
  14567. "Find first entry in buffer that sets PROPERTY.
  14568. When optional argument VALUE is non-nil, only consider an entry
  14569. if it contains PROPERTY set to this value. If PROPERTY should be
  14570. explicitly set to nil, use string \"nil\" for VALUE.
  14571. Return position where the entry begins, or nil if there is no
  14572. such entry. If narrowing is in effect, only search the visible
  14573. part of the buffer."
  14574. (save-excursion
  14575. (goto-char (point-min))
  14576. (let ((case-fold-search t)
  14577. (re (org-re-property property nil (not value) value)))
  14578. (catch 'exit
  14579. (while (re-search-forward re nil t)
  14580. (when (if value (org-at-property-p)
  14581. (org-entry-get (point) property nil t))
  14582. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14583. (defun org-delete-property (property)
  14584. "In the current entry, delete PROPERTY."
  14585. (interactive
  14586. (let* ((completion-ignore-case t)
  14587. (cat (org-entry-get (point) "CATEGORY"))
  14588. (props0 (org-entry-properties nil 'standard))
  14589. (props (if cat props0
  14590. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14591. (prop (if (< 1 (length props))
  14592. (completing-read "Property: " props nil t)
  14593. (caar props))))
  14594. (list prop)))
  14595. (if (not property)
  14596. (message "No property to delete in this entry")
  14597. (org-entry-delete nil property)
  14598. (message "Property \"%s\" deleted" property)))
  14599. (defun org-delete-property-globally (property)
  14600. "Remove PROPERTY globally, from all entries.
  14601. This function ignores narrowing, if any."
  14602. (interactive
  14603. (let* ((completion-ignore-case t)
  14604. (prop (completing-read
  14605. "Globally remove property: "
  14606. (mapcar #'list (org-buffer-property-keys)))))
  14607. (list prop)))
  14608. (org-with-wide-buffer
  14609. (goto-char (point-min))
  14610. (let ((count 0)
  14611. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14612. (while (re-search-forward re nil t)
  14613. (when (org-entry-delete (point) property) (cl-incf count)))
  14614. (message "Property \"%s\" removed from %d entries" property count))))
  14615. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14616. (defun org-compute-property-at-point ()
  14617. "Compute the property at point.
  14618. This looks for an enclosing column format, extracts the operator and
  14619. then applies it to the property in the column format's scope."
  14620. (interactive)
  14621. (unless (org-at-property-p)
  14622. (user-error "Not at a property"))
  14623. (let ((prop (match-string-no-properties 2)))
  14624. (org-columns-get-format-and-top-level)
  14625. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14626. (user-error "No operator defined for property %s" prop))
  14627. (org-columns-compute prop)))
  14628. (defvar org-property-allowed-value-functions nil
  14629. "Hook for functions supplying allowed values for a specific property.
  14630. The functions must take a single argument, the name of the property, and
  14631. return a flat list of allowed values. If \":ETC\" is one of
  14632. the values, this means that these values are intended as defaults for
  14633. completion, but that other values should be allowed too.
  14634. The functions must return nil if they are not responsible for this
  14635. property.")
  14636. (defun org-property-get-allowed-values (pom property &optional table)
  14637. "Get allowed values for the property PROPERTY.
  14638. When TABLE is non-nil, return an alist that can directly be used for
  14639. completion."
  14640. (let (vals)
  14641. (cond
  14642. ((equal property "TODO")
  14643. (setq vals (org-with-point-at pom
  14644. (append org-todo-keywords-1 '("")))))
  14645. ((equal property "PRIORITY")
  14646. (let ((n org-lowest-priority))
  14647. (while (>= n org-highest-priority)
  14648. (push (char-to-string n) vals)
  14649. (setq n (1- n)))))
  14650. ((equal property "CATEGORY"))
  14651. ((member property org-special-properties))
  14652. ((setq vals (run-hook-with-args-until-success
  14653. 'org-property-allowed-value-functions property)))
  14654. (t
  14655. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14656. (when (and vals (string-match "\\S-" vals))
  14657. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14658. (setq vals (mapcar (lambda (x)
  14659. (cond ((stringp x) x)
  14660. ((numberp x) (number-to-string x))
  14661. ((symbolp x) (symbol-name x))
  14662. (t "???")))
  14663. vals)))))
  14664. (when (member ":ETC" vals)
  14665. (setq vals (remove ":ETC" vals))
  14666. (org-add-props (car vals) '(org-unrestricted t)))
  14667. (if table (mapcar 'list vals) vals)))
  14668. (defun org-property-previous-allowed-value (&optional _previous)
  14669. "Switch to the next allowed value for this property."
  14670. (interactive)
  14671. (org-property-next-allowed-value t))
  14672. (defun org-property-next-allowed-value (&optional previous)
  14673. "Switch to the next allowed value for this property."
  14674. (interactive)
  14675. (unless (org-at-property-p)
  14676. (user-error "Not at a property"))
  14677. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14678. (key (match-string 2))
  14679. (value (match-string 3))
  14680. (allowed (or (org-property-get-allowed-values (point) key)
  14681. (and (member value '("[ ]" "[-]" "[X]"))
  14682. '("[ ]" "[X]"))))
  14683. (heading (save-match-data (nth 4 (org-heading-components))))
  14684. nval)
  14685. (unless allowed
  14686. (user-error "Allowed values for this property have not been defined"))
  14687. (when previous (setq allowed (reverse allowed)))
  14688. (when (member value allowed)
  14689. (setq nval (car (cdr (member value allowed)))))
  14690. (setq nval (or nval (car allowed)))
  14691. (when (equal nval value)
  14692. (user-error "Only one allowed value for this property"))
  14693. (org-at-property-p)
  14694. (replace-match (concat " :" key ": " nval) t t)
  14695. (org-indent-line)
  14696. (beginning-of-line 1)
  14697. (skip-chars-forward " \t")
  14698. (when (equal prop org-effort-property)
  14699. (org-refresh-property
  14700. '((effort . identity)
  14701. (effort-minutes . org-duration-to-minutes))
  14702. nval)
  14703. (when (string= org-clock-current-task heading)
  14704. (setq org-clock-effort nval)
  14705. (org-clock-update-mode-line)))
  14706. (run-hook-with-args 'org-property-changed-functions key nval)))
  14707. (defun org-find-olp (path &optional this-buffer)
  14708. "Return a marker pointing to the entry at outline path OLP.
  14709. If anything goes wrong, throw an error.
  14710. You can wrap this call to catch the error like this:
  14711. (condition-case msg
  14712. (org-mobile-locate-entry (match-string 4))
  14713. (error (nth 1 msg)))
  14714. The return value will then be either a string with the error message,
  14715. or a marker if everything is OK.
  14716. If THIS-BUFFER is set, the outline path does not contain a file,
  14717. only headings."
  14718. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14719. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14720. (level 1)
  14721. (lmin 1)
  14722. (lmax 1)
  14723. end found flevel)
  14724. (unless buffer (error "File not found :%s" file))
  14725. (with-current-buffer buffer
  14726. (unless (derived-mode-p 'org-mode)
  14727. (error "Buffer %s needs to be in Org mode" buffer))
  14728. (org-with-wide-buffer
  14729. (goto-char (point-min))
  14730. (dolist (heading path)
  14731. (let ((re (format org-complex-heading-regexp-format
  14732. (regexp-quote heading)))
  14733. (cnt 0))
  14734. (while (re-search-forward re end t)
  14735. (setq level (- (match-end 1) (match-beginning 1)))
  14736. (when (and (>= level lmin) (<= level lmax))
  14737. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14738. (when (= cnt 0)
  14739. (error "Heading not found on level %d: %s" lmax heading))
  14740. (when (> cnt 1)
  14741. (error "Heading not unique on level %d: %s" lmax heading))
  14742. (goto-char found)
  14743. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14744. (setq end (save-excursion (org-end-of-subtree t t)))))
  14745. (when (org-at-heading-p)
  14746. (point-marker))))))
  14747. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14748. "Find node HEADING in BUFFER.
  14749. Return a marker to the heading if it was found, or nil if not.
  14750. If POS-ONLY is set, return just the position instead of a marker.
  14751. The heading text must match exact, but it may have a TODO keyword,
  14752. a priority cookie and tags in the standard locations."
  14753. (with-current-buffer (or buffer (current-buffer))
  14754. (org-with-wide-buffer
  14755. (goto-char (point-min))
  14756. (let (case-fold-search)
  14757. (when (re-search-forward
  14758. (format org-complex-heading-regexp-format
  14759. (regexp-quote heading)) nil t)
  14760. (if pos-only
  14761. (match-beginning 0)
  14762. (move-marker (make-marker) (match-beginning 0))))))))
  14763. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14764. "Find Org node headline HEADING in all .org files in directory DIR.
  14765. When the target headline is found, return a marker to this location."
  14766. (let ((files (directory-files (or dir default-directory)
  14767. t "\\`[^.#].*\\.org\\'"))
  14768. visiting m buffer)
  14769. (catch 'found
  14770. (dolist (file files)
  14771. (message "trying %s" file)
  14772. (setq visiting (org-find-base-buffer-visiting file))
  14773. (setq buffer (or visiting (find-file-noselect file)))
  14774. (setq m (org-find-exact-headline-in-buffer
  14775. heading buffer))
  14776. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14777. (and m (throw 'found m))))))
  14778. (defun org-find-entry-with-id (ident)
  14779. "Locate the entry that contains the ID property with exact value IDENT.
  14780. IDENT can be a string, a symbol or a number, this function will search for
  14781. the string representation of it.
  14782. Return the position where this entry starts, or nil if there is no such entry."
  14783. (interactive "sID: ")
  14784. (let ((id (cond
  14785. ((stringp ident) ident)
  14786. ((symbolp ident) (symbol-name ident))
  14787. ((numberp ident) (number-to-string ident))
  14788. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14789. (org-with-wide-buffer (org-find-property "ID" id))))
  14790. ;;;; Timestamps
  14791. (defvar org-last-changed-timestamp nil)
  14792. (defvar org-last-inserted-timestamp nil
  14793. "The last time stamp inserted with `org-insert-time-stamp'.")
  14794. (defun org-time-stamp (arg &optional inactive)
  14795. "Prompt for a date/time and insert a time stamp.
  14796. If the user specifies a time like HH:MM or if this command is
  14797. called with at least one prefix argument, the time stamp contains
  14798. the date and the time. Otherwise, only the date is included.
  14799. All parts of a date not specified by the user are filled in from
  14800. the timestamp at point, if any, or the current date/time
  14801. otherwise.
  14802. If there is already a timestamp at the cursor, it is replaced.
  14803. With two universal prefix arguments, insert an active timestamp
  14804. with the current time without prompting the user.
  14805. When called from lisp, the timestamp is inactive if INACTIVE is
  14806. non-nil."
  14807. (interactive "P")
  14808. (let* ((ts (cond
  14809. ((org-at-date-range-p t)
  14810. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14811. ((org-at-timestamp-p 'lax) (match-string 0))))
  14812. ;; Default time is either the timestamp at point or today.
  14813. ;; When entering a range, only the range start is considered.
  14814. (default-time (if (not ts) (current-time)
  14815. (apply #'encode-time (org-parse-time-string ts))))
  14816. (default-input (and ts (org-get-compact-tod ts)))
  14817. (repeater (and ts
  14818. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14819. (match-string 0 ts)))
  14820. org-time-was-given
  14821. org-end-time-was-given
  14822. (time
  14823. (and (if (equal arg '(16)) (current-time)
  14824. ;; Preserve `this-command' and `last-command'.
  14825. (let ((this-command this-command)
  14826. (last-command last-command))
  14827. (org-read-date
  14828. arg 'totime nil nil default-time default-input
  14829. inactive))))))
  14830. (cond
  14831. ((and ts
  14832. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14833. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14834. (insert "--")
  14835. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14836. (ts
  14837. ;; Make sure we're on a timestamp. When in the middle of a date
  14838. ;; range, move arbitrarily to range end.
  14839. (unless (org-at-timestamp-p 'lax)
  14840. (skip-chars-forward "-")
  14841. (org-at-timestamp-p 'lax))
  14842. (replace-match "")
  14843. (setq org-last-changed-timestamp
  14844. (org-insert-time-stamp
  14845. time (or org-time-was-given arg)
  14846. inactive nil nil (list org-end-time-was-given)))
  14847. (when repeater
  14848. (backward-char)
  14849. (insert " " repeater)
  14850. (setq org-last-changed-timestamp
  14851. (concat (substring org-last-inserted-timestamp 0 -1)
  14852. " " repeater ">")))
  14853. (message "Timestamp updated"))
  14854. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14855. (t (org-insert-time-stamp
  14856. time (or org-time-was-given arg) inactive nil nil
  14857. (list org-end-time-was-given))))))
  14858. ;; FIXME: can we use this for something else, like computing time differences?
  14859. (defun org-get-compact-tod (s)
  14860. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14861. (let* ((t1 (match-string 1 s))
  14862. (h1 (string-to-number (match-string 2 s)))
  14863. (m1 (string-to-number (match-string 3 s)))
  14864. (t2 (and (match-end 4) (match-string 5 s)))
  14865. (h2 (and t2 (string-to-number (match-string 6 s))))
  14866. (m2 (and t2 (string-to-number (match-string 7 s))))
  14867. dh dm)
  14868. (if (not t2)
  14869. t1
  14870. (setq dh (- h2 h1) dm (- m2 m1))
  14871. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14872. (concat t1 "+" (number-to-string dh)
  14873. (and (/= 0 dm) (format ":%02d" dm)))))))
  14874. (defun org-time-stamp-inactive (&optional arg)
  14875. "Insert an inactive time stamp.
  14876. An inactive time stamp is enclosed in square brackets instead of angle
  14877. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14878. does not link to the calendar and cannot be changed with the S-cursor keys.
  14879. So these are more for recording a certain time/date."
  14880. (interactive "P")
  14881. (org-time-stamp arg 'inactive))
  14882. (defvar org-date-ovl (make-overlay 1 1))
  14883. (overlay-put org-date-ovl 'face 'org-date-selected)
  14884. (delete-overlay org-date-ovl)
  14885. (defvar org-ans1) ; dynamically scoped parameter
  14886. (defvar org-ans2) ; dynamically scoped parameter
  14887. (defvar org-plain-time-of-day-regexp) ; defined below
  14888. (defvar org-overriding-default-time nil) ; dynamically scoped
  14889. (defvar org-read-date-overlay nil)
  14890. (defvar org-dcst nil) ; dynamically scoped
  14891. (defvar org-read-date-history nil)
  14892. (defvar org-read-date-final-answer nil)
  14893. (defvar org-read-date-analyze-futurep nil)
  14894. (defvar org-read-date-analyze-forced-year nil)
  14895. (defvar org-read-date-inactive)
  14896. (defvar org-read-date-minibuffer-local-map
  14897. (let* ((map (make-sparse-keymap)))
  14898. (set-keymap-parent map minibuffer-local-map)
  14899. (org-defkey map (kbd ".")
  14900. (lambda () (interactive)
  14901. ;; Are we at the beginning of the prompt?
  14902. (if (looking-back "^[^:]+: "
  14903. (let ((inhibit-field-text-motion t))
  14904. (line-beginning-position)))
  14905. (org-eval-in-calendar '(calendar-goto-today))
  14906. (insert "."))))
  14907. (org-defkey map (kbd "C-.")
  14908. (lambda () (interactive)
  14909. (org-eval-in-calendar '(calendar-goto-today))))
  14910. (org-defkey map [(meta shift left)]
  14911. (lambda () (interactive)
  14912. (org-eval-in-calendar '(calendar-backward-month 1))))
  14913. (org-defkey map [(meta shift right)]
  14914. (lambda () (interactive)
  14915. (org-eval-in-calendar '(calendar-forward-month 1))))
  14916. (org-defkey map [(meta shift up)]
  14917. (lambda () (interactive)
  14918. (org-eval-in-calendar '(calendar-backward-year 1))))
  14919. (org-defkey map [(meta shift down)]
  14920. (lambda () (interactive)
  14921. (org-eval-in-calendar '(calendar-forward-year 1))))
  14922. (org-defkey map [?\e (shift left)]
  14923. (lambda () (interactive)
  14924. (org-eval-in-calendar '(calendar-backward-month 1))))
  14925. (org-defkey map [?\e (shift right)]
  14926. (lambda () (interactive)
  14927. (org-eval-in-calendar '(calendar-forward-month 1))))
  14928. (org-defkey map [?\e (shift up)]
  14929. (lambda () (interactive)
  14930. (org-eval-in-calendar '(calendar-backward-year 1))))
  14931. (org-defkey map [?\e (shift down)]
  14932. (lambda () (interactive)
  14933. (org-eval-in-calendar '(calendar-forward-year 1))))
  14934. (org-defkey map [(shift up)]
  14935. (lambda () (interactive)
  14936. (org-eval-in-calendar '(calendar-backward-week 1))))
  14937. (org-defkey map [(shift down)]
  14938. (lambda () (interactive)
  14939. (org-eval-in-calendar '(calendar-forward-week 1))))
  14940. (org-defkey map [(shift left)]
  14941. (lambda () (interactive)
  14942. (org-eval-in-calendar '(calendar-backward-day 1))))
  14943. (org-defkey map [(shift right)]
  14944. (lambda () (interactive)
  14945. (org-eval-in-calendar '(calendar-forward-day 1))))
  14946. (org-defkey map "!"
  14947. (lambda () (interactive)
  14948. (org-eval-in-calendar '(diary-view-entries))
  14949. (message "")))
  14950. (org-defkey map ">"
  14951. (lambda () (interactive)
  14952. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14953. (org-defkey map "<"
  14954. (lambda () (interactive)
  14955. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14956. (org-defkey map "\C-v"
  14957. (lambda () (interactive)
  14958. (org-eval-in-calendar
  14959. '(calendar-scroll-left-three-months 1))))
  14960. (org-defkey map "\M-v"
  14961. (lambda () (interactive)
  14962. (org-eval-in-calendar
  14963. '(calendar-scroll-right-three-months 1))))
  14964. map)
  14965. "Keymap for minibuffer commands when using `org-read-date'.")
  14966. (defvar org-def)
  14967. (defvar org-defdecode)
  14968. (defvar org-with-time)
  14969. (defvar calendar-setup) ; Dynamically scoped.
  14970. (defun org-read-date (&optional with-time to-time from-string prompt
  14971. default-time default-input inactive)
  14972. "Read a date, possibly a time, and make things smooth for the user.
  14973. The prompt will suggest to enter an ISO date, but you can also enter anything
  14974. which will at least partially be understood by `parse-time-string'.
  14975. Unrecognized parts of the date will default to the current day, month, year,
  14976. hour and minute. If this command is called to replace a timestamp at point,
  14977. or to enter the second timestamp of a range, the default time is taken
  14978. from the existing stamp. Furthermore, the command prefers the future,
  14979. so if you are giving a date where the year is not given, and the day-month
  14980. combination is already past in the current year, it will assume you
  14981. mean next year. For details, see the manual. A few examples:
  14982. 3-2-5 --> 2003-02-05
  14983. feb 15 --> currentyear-02-15
  14984. 2/15 --> currentyear-02-15
  14985. sep 12 9 --> 2009-09-12
  14986. 12:45 --> today 12:45
  14987. 22 sept 0:34 --> currentyear-09-22 0:34
  14988. 12 --> currentyear-currentmonth-12
  14989. Fri --> nearest Friday after today
  14990. -Tue --> last Tuesday
  14991. etc.
  14992. Furthermore you can specify a relative date by giving, as the *first* thing
  14993. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14994. change in days weeks, months, years.
  14995. With a single plus or minus, the date is relative to today. With a double
  14996. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14997. +4d --> four days from today
  14998. +4 --> same as above
  14999. +2w --> two weeks from today
  15000. ++5 --> five days from default date
  15001. The function understands only English month and weekday abbreviations.
  15002. While prompting, a calendar is popped up - you can also select the
  15003. date with the mouse (button 1). The calendar shows a period of three
  15004. months. To scroll it to other months, use the keys `>' and `<'.
  15005. If you don't like the calendar, turn it off with
  15006. (setq org-read-date-popup-calendar nil)
  15007. With optional argument TO-TIME, the date will immediately be converted
  15008. to an internal time.
  15009. With an optional argument WITH-TIME, the prompt will suggest to
  15010. also insert a time. Note that when WITH-TIME is not set, you can
  15011. still enter a time, and this function will inform the calling routine
  15012. about this change. The calling routine may then choose to change the
  15013. format used to insert the time stamp into the buffer to include the time.
  15014. With optional argument FROM-STRING, read from this string instead from
  15015. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15016. the time/date that is used for everything that is not specified by the
  15017. user."
  15018. (require 'parse-time)
  15019. (let* ((org-with-time with-time)
  15020. (org-time-stamp-rounding-minutes
  15021. (if (equal org-with-time '(16))
  15022. '(0 0)
  15023. org-time-stamp-rounding-minutes))
  15024. (org-dcst org-display-custom-times)
  15025. (ct (org-current-time))
  15026. (org-def (or org-overriding-default-time default-time ct))
  15027. (org-defdecode (decode-time org-def))
  15028. (cur-frame (selected-frame))
  15029. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15030. (calendar-setup
  15031. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15032. (calendar-move-hook nil)
  15033. (calendar-view-diary-initially-flag nil)
  15034. (calendar-view-holidays-initially-flag nil)
  15035. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15036. ;; Rationalize `org-def' and `org-defdecode', if required.
  15037. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15038. (setf (nth 2 org-defdecode) -1)
  15039. (setf (nth 1 org-defdecode) 59)
  15040. (setq org-def (apply #'encode-time org-defdecode))
  15041. (setq org-defdecode (decode-time org-def)))
  15042. (let* ((timestr (format-time-string
  15043. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15044. org-def))
  15045. (prompt (concat (if prompt (concat prompt " ") "")
  15046. (format "Date+time [%s]: " timestr))))
  15047. (cond
  15048. (from-string (setq ans from-string))
  15049. (org-read-date-popup-calendar
  15050. (save-excursion
  15051. (save-window-excursion
  15052. (calendar)
  15053. (when (eq calendar-setup 'calendar-only)
  15054. (setq cal-frame
  15055. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15056. (select-frame cal-frame))
  15057. (org-eval-in-calendar '(setq cursor-type nil) t)
  15058. (unwind-protect
  15059. (progn
  15060. (calendar-forward-day (- (time-to-days org-def)
  15061. (calendar-absolute-from-gregorian
  15062. (calendar-current-date))))
  15063. (org-eval-in-calendar nil t)
  15064. (let* ((old-map (current-local-map))
  15065. (map (copy-keymap calendar-mode-map))
  15066. (minibuffer-local-map
  15067. (copy-keymap org-read-date-minibuffer-local-map)))
  15068. (org-defkey map (kbd "RET") 'org-calendar-select)
  15069. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15070. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15071. (unwind-protect
  15072. (progn
  15073. (use-local-map map)
  15074. (setq org-read-date-inactive inactive)
  15075. (add-hook 'post-command-hook 'org-read-date-display)
  15076. (setq org-ans0
  15077. (read-string prompt
  15078. default-input
  15079. 'org-read-date-history
  15080. nil))
  15081. ;; org-ans0: from prompt
  15082. ;; org-ans1: from mouse click
  15083. ;; org-ans2: from calendar motion
  15084. (setq ans
  15085. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15086. (remove-hook 'post-command-hook 'org-read-date-display)
  15087. (use-local-map old-map)
  15088. (when org-read-date-overlay
  15089. (delete-overlay org-read-date-overlay)
  15090. (setq org-read-date-overlay nil)))))
  15091. (bury-buffer "*Calendar*")
  15092. (when cal-frame
  15093. (delete-frame cal-frame)
  15094. (select-frame-set-input-focus cur-frame))))))
  15095. (t ; Naked prompt only
  15096. (unwind-protect
  15097. (setq ans (read-string prompt default-input
  15098. 'org-read-date-history timestr))
  15099. (when org-read-date-overlay
  15100. (delete-overlay org-read-date-overlay)
  15101. (setq org-read-date-overlay nil))))))
  15102. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15103. (when org-read-date-analyze-forced-year
  15104. (message "Year was forced into %s"
  15105. (if org-read-date-force-compatible-dates
  15106. "compatible range (1970-2037)"
  15107. "range representable on this machine"))
  15108. (ding))
  15109. ;; One round trip to get rid of 34th of August and stuff like that....
  15110. (setq final (decode-time (apply 'encode-time final)))
  15111. (setq org-read-date-final-answer ans)
  15112. (if to-time
  15113. (apply 'encode-time final)
  15114. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15115. (format "%04d-%02d-%02d %02d:%02d"
  15116. (nth 5 final) (nth 4 final) (nth 3 final)
  15117. (nth 2 final) (nth 1 final))
  15118. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15119. (defun org-read-date-display ()
  15120. "Display the current date prompt interpretation in the minibuffer."
  15121. (when org-read-date-display-live
  15122. (when org-read-date-overlay
  15123. (delete-overlay org-read-date-overlay))
  15124. (when (minibufferp (current-buffer))
  15125. (save-excursion
  15126. (end-of-line 1)
  15127. (while (not (equal (buffer-substring
  15128. (max (point-min) (- (point) 4)) (point))
  15129. " "))
  15130. (insert " ")))
  15131. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15132. " " (or org-ans1 org-ans2)))
  15133. (org-end-time-was-given nil)
  15134. (f (org-read-date-analyze ans org-def org-defdecode))
  15135. (fmts (if org-dcst
  15136. org-time-stamp-custom-formats
  15137. org-time-stamp-formats))
  15138. (fmt (if (or org-with-time
  15139. (and (boundp 'org-time-was-given) org-time-was-given))
  15140. (cdr fmts)
  15141. (car fmts)))
  15142. (txt (format-time-string fmt (apply 'encode-time f)))
  15143. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15144. (txt (concat "=> " txt)))
  15145. (when (and org-end-time-was-given
  15146. (string-match org-plain-time-of-day-regexp txt))
  15147. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15148. org-end-time-was-given
  15149. (substring txt (match-end 0)))))
  15150. (when org-read-date-analyze-futurep
  15151. (setq txt (concat txt " (=>F)")))
  15152. (setq org-read-date-overlay
  15153. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15154. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15155. (defun org-read-date-analyze (ans def defdecode)
  15156. "Analyze the combined answer of the date prompt."
  15157. ;; FIXME: cleanup and comment
  15158. ;; Pass `current-time' result to `decode-time' (instead of calling
  15159. ;; without arguments) so that only `current-time' has to be
  15160. ;; overridden in tests.
  15161. (let ((org-def def)
  15162. (org-defdecode defdecode)
  15163. (nowdecode (decode-time (current-time)))
  15164. delta deltan deltaw deltadef year month day
  15165. hour minute second wday pm h2 m2 tl wday1
  15166. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15167. (setq org-read-date-analyze-futurep nil
  15168. org-read-date-analyze-forced-year nil)
  15169. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15170. (setq ans "+0"))
  15171. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15172. (setq ans (replace-match "" t t ans)
  15173. deltan (car delta)
  15174. deltaw (nth 1 delta)
  15175. deltadef (nth 2 delta)))
  15176. ;; Check if there is an iso week date in there. If yes, store the
  15177. ;; info and postpone interpreting it until the rest of the parsing
  15178. ;; is done.
  15179. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15180. (setq iso-year (when (match-end 1)
  15181. (org-small-year-to-year
  15182. (string-to-number (match-string 1 ans))))
  15183. iso-weekday (when (match-end 3)
  15184. (string-to-number (match-string 3 ans)))
  15185. iso-week (string-to-number (match-string 2 ans)))
  15186. (setq ans (replace-match "" t t ans)))
  15187. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15188. (when (string-match
  15189. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15190. (setq year (if (match-end 2)
  15191. (string-to-number (match-string 2 ans))
  15192. (progn (setq kill-year t)
  15193. (string-to-number (format-time-string "%Y"))))
  15194. month (string-to-number (match-string 3 ans))
  15195. day (string-to-number (match-string 4 ans)))
  15196. (setq year (org-small-year-to-year year))
  15197. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15198. t nil ans)))
  15199. ;; Help matching dotted european dates
  15200. (when (string-match
  15201. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15202. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15203. (setq kill-year t)
  15204. (string-to-number (format-time-string "%Y")))
  15205. day (string-to-number (match-string 1 ans))
  15206. month (string-to-number (match-string 2 ans))
  15207. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15208. t nil ans)))
  15209. ;; Help matching american dates, like 5/30 or 5/30/7
  15210. (when (string-match
  15211. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15212. (setq year (if (match-end 4)
  15213. (string-to-number (match-string 4 ans))
  15214. (progn (setq kill-year t)
  15215. (string-to-number (format-time-string "%Y"))))
  15216. month (string-to-number (match-string 1 ans))
  15217. day (string-to-number (match-string 2 ans)))
  15218. (setq year (org-small-year-to-year year))
  15219. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15220. t nil ans)))
  15221. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15222. ;; If there is a time with am/pm, and *no* time without it, we convert
  15223. ;; so that matching will be successful.
  15224. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15225. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15226. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15227. (setq hour (string-to-number (match-string 1 ans))
  15228. minute (if (match-end 3)
  15229. (string-to-number (match-string 3 ans))
  15230. 0)
  15231. pm (equal ?p
  15232. (string-to-char (downcase (match-string 4 ans)))))
  15233. (if (and (= hour 12) (not pm))
  15234. (setq hour 0)
  15235. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15236. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15237. t t ans))))
  15238. ;; Check if a time range is given as a duration
  15239. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15240. (setq hour (string-to-number (match-string 1 ans))
  15241. h2 (+ hour (string-to-number (match-string 3 ans)))
  15242. minute (string-to-number (match-string 2 ans))
  15243. m2 (+ minute (if (match-end 5) (string-to-number
  15244. (match-string 5 ans))0)))
  15245. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15246. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15247. t t ans)))
  15248. ;; Check if there is a time range
  15249. (when (boundp 'org-end-time-was-given)
  15250. (setq org-time-was-given nil)
  15251. (when (and (string-match org-plain-time-of-day-regexp ans)
  15252. (match-end 8))
  15253. (setq org-end-time-was-given (match-string 8 ans))
  15254. (setq ans (concat (substring ans 0 (match-beginning 7))
  15255. (substring ans (match-end 7))))))
  15256. (setq tl (parse-time-string ans)
  15257. day (or (nth 3 tl) (nth 3 org-defdecode))
  15258. month
  15259. (cond ((nth 4 tl))
  15260. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15261. ;; Day was specified. Make sure DAY+MONTH
  15262. ;; combination happens in the future.
  15263. ((nth 3 tl)
  15264. (setq futurep t)
  15265. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15266. (nth 4 nowdecode)))
  15267. (t (nth 4 org-defdecode)))
  15268. year
  15269. (cond ((and (not kill-year) (nth 5 tl)))
  15270. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15271. ;; Month was guessed in the future and is at least
  15272. ;; equal to NOWDECODE's. Fix year accordingly.
  15273. (futurep
  15274. (if (or (> month (nth 4 nowdecode))
  15275. (>= day (nth 3 nowdecode)))
  15276. (nth 5 nowdecode)
  15277. (1+ (nth 5 nowdecode))))
  15278. ;; Month was specified. Make sure MONTH+YEAR
  15279. ;; combination happens in the future.
  15280. ((nth 4 tl)
  15281. (setq futurep t)
  15282. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15283. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15284. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15285. (t (nth 5 nowdecode))))
  15286. (t (nth 5 org-defdecode)))
  15287. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15288. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15289. second (or (nth 0 tl) 0)
  15290. wday (nth 6 tl))
  15291. (when (and (eq org-read-date-prefer-future 'time)
  15292. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15293. (equal day (nth 3 nowdecode))
  15294. (equal month (nth 4 nowdecode))
  15295. (equal year (nth 5 nowdecode))
  15296. (nth 2 tl)
  15297. (or (< (nth 2 tl) (nth 2 nowdecode))
  15298. (and (= (nth 2 tl) (nth 2 nowdecode))
  15299. (nth 1 tl)
  15300. (< (nth 1 tl) (nth 1 nowdecode)))))
  15301. (setq day (1+ day)
  15302. futurep t))
  15303. ;; Special date definitions below
  15304. (cond
  15305. (iso-week
  15306. ;; There was an iso week
  15307. (require 'cal-iso)
  15308. (setq futurep nil)
  15309. (setq year (or iso-year year)
  15310. day (or iso-weekday wday 1)
  15311. wday nil ; to make sure that the trigger below does not match
  15312. iso-date (calendar-gregorian-from-absolute
  15313. (calendar-iso-to-absolute
  15314. (list iso-week day year))))
  15315. ; FIXME: Should we also push ISO weeks into the future?
  15316. ; (when (and org-read-date-prefer-future
  15317. ; (not iso-year)
  15318. ; (< (calendar-absolute-from-gregorian iso-date)
  15319. ; (time-to-days (current-time))))
  15320. ; (setq year (1+ year)
  15321. ; iso-date (calendar-gregorian-from-absolute
  15322. ; (calendar-iso-to-absolute
  15323. ; (list iso-week day year)))))
  15324. (setq month (car iso-date)
  15325. year (nth 2 iso-date)
  15326. day (nth 1 iso-date)))
  15327. (deltan
  15328. (setq futurep nil)
  15329. (unless deltadef
  15330. ;; Pass `current-time' result to `decode-time' (instead of
  15331. ;; calling without arguments) so that only `current-time' has
  15332. ;; to be overridden in tests.
  15333. (let ((now (decode-time (current-time))))
  15334. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15335. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15336. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15337. ((equal deltaw "m") (setq month (+ month deltan)))
  15338. ((equal deltaw "y") (setq year (+ year deltan)))))
  15339. ((and wday (not (nth 3 tl)))
  15340. ;; Weekday was given, but no day, so pick that day in the week
  15341. ;; on or after the derived date.
  15342. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15343. (unless (equal wday wday1)
  15344. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15345. (when (and (boundp 'org-time-was-given)
  15346. (nth 2 tl))
  15347. (setq org-time-was-given t))
  15348. (when (< year 100) (setq year (+ 2000 year)))
  15349. ;; Check of the date is representable
  15350. (if org-read-date-force-compatible-dates
  15351. (progn
  15352. (when (< year 1970)
  15353. (setq year 1970 org-read-date-analyze-forced-year t))
  15354. (when (> year 2037)
  15355. (setq year 2037 org-read-date-analyze-forced-year t)))
  15356. (condition-case nil
  15357. (ignore (encode-time second minute hour day month year))
  15358. (error
  15359. (setq year (nth 5 org-defdecode))
  15360. (setq org-read-date-analyze-forced-year t))))
  15361. (setq org-read-date-analyze-futurep futurep)
  15362. (list second minute hour day month year)))
  15363. (defvar parse-time-weekdays)
  15364. (defun org-read-date-get-relative (s today default)
  15365. "Check string S for special relative date string.
  15366. TODAY and DEFAULT are internal times, for today and for a default.
  15367. Return shift list (N what def-flag)
  15368. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15369. N is the number of WHATs to shift.
  15370. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15371. the DEFAULT date rather than TODAY."
  15372. (require 'parse-time)
  15373. (when (and
  15374. (string-match
  15375. (concat
  15376. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15377. "\\([0-9]+\\)?"
  15378. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15379. "\\([ \t]\\|$\\)") s)
  15380. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15381. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15382. (string-to-char (substring (match-string 1 s) -1))
  15383. ?+))
  15384. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15385. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15386. (what (if (match-end 3) (match-string 3 s) "d"))
  15387. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15388. (date (if rel default today))
  15389. (wday (nth 6 (decode-time date)))
  15390. delta)
  15391. (if wday1
  15392. (progn
  15393. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15394. (when (= delta 0) (setq delta 7))
  15395. (when (= dir ?-)
  15396. (setq delta (- delta 7))
  15397. (when (= delta 0) (setq delta -7)))
  15398. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15399. (list delta "d" rel))
  15400. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15401. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15402. "Turn a user-specified date into the internal representation.
  15403. The internal representation needed by the calendar is (month day year).
  15404. This is a wrapper to handle the brain-dead convention in calendar that
  15405. user function argument order change dependent on argument order."
  15406. (pcase calendar-date-style
  15407. (`american (list arg1 arg2 arg3))
  15408. (`european (list arg2 arg1 arg3))
  15409. (`iso (list arg2 arg3 arg1))))
  15410. (defun org-eval-in-calendar (form &optional keepdate)
  15411. "Eval FORM in the calendar window and return to current window.
  15412. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15413. (let ((sf (selected-frame))
  15414. (sw (selected-window)))
  15415. (select-window (get-buffer-window "*Calendar*" t))
  15416. (eval form)
  15417. (when (and (not keepdate) (calendar-cursor-to-date))
  15418. (let* ((date (calendar-cursor-to-date))
  15419. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15420. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15421. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15422. (select-window sw)
  15423. (select-frame-set-input-focus sf)))
  15424. (defun org-calendar-select ()
  15425. "Return to `org-read-date' with the date currently selected.
  15426. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15427. (interactive)
  15428. (when (calendar-cursor-to-date)
  15429. (let* ((date (calendar-cursor-to-date))
  15430. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15431. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15432. (when (active-minibuffer-window) (exit-minibuffer))))
  15433. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15434. "Insert a date stamp for the date given by the internal TIME.
  15435. See `format-time-string' for the format of TIME.
  15436. WITH-HM means use the stamp format that includes the time of the day.
  15437. INACTIVE means use square brackets instead of angular ones, so that the
  15438. stamp will not contribute to the agenda.
  15439. PRE and POST are optional strings to be inserted before and after the
  15440. stamp.
  15441. The command returns the inserted time stamp."
  15442. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15443. stamp)
  15444. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15445. (insert-before-markers (or pre ""))
  15446. (when (listp extra)
  15447. (setq extra (car extra))
  15448. (if (and (stringp extra)
  15449. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15450. (setq extra (format "-%02d:%02d"
  15451. (string-to-number (match-string 1 extra))
  15452. (string-to-number (match-string 2 extra))))
  15453. (setq extra nil)))
  15454. (when extra
  15455. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15456. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15457. (insert-before-markers (or post ""))
  15458. (setq org-last-inserted-timestamp stamp)))
  15459. (defun org-toggle-time-stamp-overlays ()
  15460. "Toggle the use of custom time stamp formats."
  15461. (interactive)
  15462. (setq org-display-custom-times (not org-display-custom-times))
  15463. (unless org-display-custom-times
  15464. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15465. (while (setq p (next-single-property-change p 'display))
  15466. (when (and (get-text-property p 'display)
  15467. (eq (get-text-property p 'face) 'org-date))
  15468. (remove-text-properties
  15469. p (setq p (next-single-property-change p 'display))
  15470. '(display t))))
  15471. (set-buffer-modified-p bmp)))
  15472. (org-restart-font-lock)
  15473. (setq org-table-may-need-update t)
  15474. (if org-display-custom-times
  15475. (message "Time stamps are overlaid with custom format")
  15476. (message "Time stamp overlays removed")))
  15477. (defun org-display-custom-time (beg end)
  15478. "Overlay modified time stamp format over timestamp between BEG and END."
  15479. (let* ((ts (buffer-substring beg end))
  15480. t1 with-hm tf time str (off 0))
  15481. (save-match-data
  15482. (setq t1 (org-parse-time-string ts t))
  15483. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15484. (setq off (- (match-end 0) (match-beginning 0)))))
  15485. (setq end (- end off))
  15486. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15487. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15488. time (org-fix-decoded-time t1)
  15489. str (org-add-props
  15490. (format-time-string
  15491. (substring tf 1 -1) (apply 'encode-time time))
  15492. nil 'mouse-face 'highlight))
  15493. (put-text-property beg end 'display str)))
  15494. (defun org-fix-decoded-time (time)
  15495. "Set 0 instead of nil for the first 6 elements of time.
  15496. Don't touch the rest."
  15497. (let ((n 0))
  15498. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15499. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15500. "Difference between TIMESTAMP-STRING and now in days.
  15501. If SECONDS is non-nil, return the difference in seconds."
  15502. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15503. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15504. (funcall fdiff (current-time)))))
  15505. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15506. "Is the time in TIMESTAMP-STRING close to the current date?"
  15507. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15508. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15509. (not (org-entry-is-done-p))))
  15510. (defun org-get-wdays (ts &optional delay zero-delay)
  15511. "Get the deadline lead time appropriate for timestring TS.
  15512. When DELAY is non-nil, get the delay time for scheduled items
  15513. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15514. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15515. don't try to find the delay cookie in the scheduled timestamp."
  15516. (let ((tv (if delay org-scheduled-delay-days
  15517. org-deadline-warning-days)))
  15518. (cond
  15519. ((or (and delay (< tv 0))
  15520. (and delay zero-delay (<= tv 0))
  15521. (and (not delay) (<= tv 0)))
  15522. ;; Enforce this value no matter what
  15523. (- tv))
  15524. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15525. ;; lead time is specified.
  15526. (floor (* (string-to-number (match-string 1 ts))
  15527. (cdr (assoc (match-string 2 ts)
  15528. '(("d" . 1) ("w" . 7)
  15529. ("m" . 30.4) ("y" . 365.25)
  15530. ("h" . 0.041667)))))))
  15531. ;; go for the default.
  15532. (t tv))))
  15533. (defun org-calendar-select-mouse (ev)
  15534. "Return to `org-read-date' with the date currently selected.
  15535. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15536. (interactive "e")
  15537. (mouse-set-point ev)
  15538. (when (calendar-cursor-to-date)
  15539. (let* ((date (calendar-cursor-to-date))
  15540. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15541. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15542. (when (active-minibuffer-window) (exit-minibuffer))))
  15543. (defun org-check-deadlines (ndays)
  15544. "Check if there are any deadlines due or past due.
  15545. A deadline is considered due if it happens within `org-deadline-warning-days'
  15546. days from today's date. If the deadline appears in an entry marked DONE,
  15547. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15548. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15549. are shown."
  15550. (interactive "P")
  15551. (let* ((org-warn-days
  15552. (cond
  15553. ((equal ndays '(4)) 100000)
  15554. (ndays (prefix-numeric-value ndays))
  15555. (t (abs org-deadline-warning-days))))
  15556. (case-fold-search nil)
  15557. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15558. (callback
  15559. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15560. (message "%d deadlines past-due or due within %d days"
  15561. (org-occur regexp nil callback)
  15562. org-warn-days)))
  15563. (defsubst org-re-timestamp (type)
  15564. "Return a regexp for timestamp TYPE.
  15565. Allowed values for TYPE are:
  15566. all: all timestamps
  15567. active: only active timestamps (<...>)
  15568. inactive: only inactive timestamps ([...])
  15569. scheduled: only scheduled timestamps
  15570. deadline: only deadline timestamps
  15571. closed: only closed time-stamps
  15572. When TYPE is nil, fall back on returning a regexp that matches
  15573. both scheduled and deadline timestamps."
  15574. (cl-case type
  15575. (all org-ts-regexp-both)
  15576. (active org-ts-regexp)
  15577. (inactive org-ts-regexp-inactive)
  15578. (scheduled org-scheduled-time-regexp)
  15579. (deadline org-deadline-time-regexp)
  15580. (closed org-closed-time-regexp)
  15581. (otherwise
  15582. (concat "\\<"
  15583. (regexp-opt (list org-deadline-string org-scheduled-string))
  15584. " *<\\([^>]+\\)>"))))
  15585. (defun org-check-before-date (d)
  15586. "Check if there are deadlines or scheduled entries before date D."
  15587. (interactive (list (org-read-date)))
  15588. (let* ((case-fold-search nil)
  15589. (regexp (org-re-timestamp org-ts-type))
  15590. (ts-type org-ts-type)
  15591. (callback
  15592. (lambda ()
  15593. (let ((match (match-string 1)))
  15594. (and (if (memq ts-type '(active inactive all))
  15595. (eq (org-element-type (save-excursion
  15596. (backward-char)
  15597. (org-element-context)))
  15598. 'timestamp)
  15599. (org-at-planning-p))
  15600. (time-less-p
  15601. (org-time-string-to-time match)
  15602. (org-time-string-to-time d)))))))
  15603. (message "%d entries before %s"
  15604. (org-occur regexp nil callback)
  15605. d)))
  15606. (defun org-check-after-date (d)
  15607. "Check if there are deadlines or scheduled entries after date D."
  15608. (interactive (list (org-read-date)))
  15609. (let* ((case-fold-search nil)
  15610. (regexp (org-re-timestamp org-ts-type))
  15611. (ts-type org-ts-type)
  15612. (callback
  15613. (lambda ()
  15614. (let ((match (match-string 1)))
  15615. (and (if (memq ts-type '(active inactive all))
  15616. (eq (org-element-type (save-excursion
  15617. (backward-char)
  15618. (org-element-context)))
  15619. 'timestamp)
  15620. (org-at-planning-p))
  15621. (not (time-less-p
  15622. (org-time-string-to-time match)
  15623. (org-time-string-to-time d))))))))
  15624. (message "%d entries after %s"
  15625. (org-occur regexp nil callback)
  15626. d)))
  15627. (defun org-check-dates-range (start-date end-date)
  15628. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15629. (interactive (list (org-read-date nil nil nil "Range starts")
  15630. (org-read-date nil nil nil "Range end")))
  15631. (let ((case-fold-search nil)
  15632. (regexp (org-re-timestamp org-ts-type))
  15633. (callback
  15634. (let ((type org-ts-type))
  15635. (lambda ()
  15636. (let ((match (match-string 1)))
  15637. (and
  15638. (if (memq type '(active inactive all))
  15639. (eq (org-element-type (save-excursion
  15640. (backward-char)
  15641. (org-element-context)))
  15642. 'timestamp)
  15643. (org-at-planning-p))
  15644. (not (time-less-p
  15645. (org-time-string-to-time match)
  15646. (org-time-string-to-time start-date)))
  15647. (time-less-p
  15648. (org-time-string-to-time match)
  15649. (org-time-string-to-time end-date))))))))
  15650. (message "%d entries between %s and %s"
  15651. (org-occur regexp nil callback) start-date end-date)))
  15652. (defun org-evaluate-time-range (&optional to-buffer)
  15653. "Evaluate a time range by computing the difference between start and end.
  15654. Normally the result is just printed in the echo area, but with prefix arg
  15655. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15656. If the time range is actually in a table, the result is inserted into the
  15657. next column.
  15658. For time difference computation, a year is assumed to be exactly 365
  15659. days in order to avoid rounding problems."
  15660. (interactive "P")
  15661. (or
  15662. (org-clock-update-time-maybe)
  15663. (save-excursion
  15664. (unless (org-at-date-range-p t)
  15665. (goto-char (point-at-bol))
  15666. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15667. (unless (org-at-date-range-p t)
  15668. (user-error "Not at a time-stamp range, and none found in current line")))
  15669. (let* ((ts1 (match-string 1))
  15670. (ts2 (match-string 2))
  15671. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15672. (match-end (match-end 0))
  15673. (time1 (org-time-string-to-time ts1))
  15674. (time2 (org-time-string-to-time ts2))
  15675. (t1 (float-time time1))
  15676. (t2 (float-time time2))
  15677. (diff (abs (- t2 t1)))
  15678. (negative (< (- t2 t1) 0))
  15679. ;; (ys (floor (* 365 24 60 60)))
  15680. (ds (* 24 60 60))
  15681. (hs (* 60 60))
  15682. (fy "%dy %dd %02d:%02d")
  15683. (fy1 "%dy %dd")
  15684. (fd "%dd %02d:%02d")
  15685. (fd1 "%dd")
  15686. (fh "%02d:%02d")
  15687. y d h m align)
  15688. (if havetime
  15689. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15690. y 0
  15691. d (floor (/ diff ds)) diff (mod diff ds)
  15692. h (floor (/ diff hs)) diff (mod diff hs)
  15693. m (floor (/ diff 60)))
  15694. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15695. y 0
  15696. d (floor (+ (/ diff ds) 0.5))
  15697. h 0 m 0))
  15698. (if (not to-buffer)
  15699. (message "%s" (org-make-tdiff-string y d h m))
  15700. (if (org-at-table-p)
  15701. (progn
  15702. (goto-char match-end)
  15703. (setq align t)
  15704. (and (looking-at " *|") (goto-char (match-end 0))))
  15705. (goto-char match-end))
  15706. (when (looking-at
  15707. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15708. (replace-match ""))
  15709. (when negative (insert " -"))
  15710. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15711. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15712. (insert " " (format fh h m))))
  15713. (when align (org-table-align))
  15714. (message "Time difference inserted")))))
  15715. (defun org-make-tdiff-string (y d h m)
  15716. (let ((fmt "")
  15717. (l nil))
  15718. (when (> y 0)
  15719. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15720. (push y l))
  15721. (when (> d 0)
  15722. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15723. (push d l))
  15724. (when (> h 0)
  15725. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15726. (push h l))
  15727. (when (> m 0)
  15728. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15729. (push m l))
  15730. (apply 'format fmt (nreverse l))))
  15731. (defun org-time-string-to-time (s)
  15732. "Convert timestamp string S into internal time."
  15733. (apply #'encode-time (org-parse-time-string s)))
  15734. (defun org-time-string-to-seconds (s)
  15735. "Convert a timestamp string S into a number of seconds."
  15736. (float-time (org-time-string-to-time s)))
  15737. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15738. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15739. "Convert time stamp S to an absolute day number.
  15740. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15741. stamp, get the closest date to DAYNR. If PREFER is
  15742. `past' (respectively `future') return a date past (respectively
  15743. after) or equal to DAYNR.
  15744. POS is the location of time stamp S, as a buffer position in
  15745. BUFFER.
  15746. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15747. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15748. signaled."
  15749. (cond
  15750. ((string-match "\\`%%\\((.*)\\)" s)
  15751. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15752. ;; only able to match individual dates. If it fails, raise an
  15753. ;; error.
  15754. (if (and daynr
  15755. (org-diary-sexp-entry
  15756. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15757. daynr
  15758. (signal 'org-diary-sexp-no-match (list s))))
  15759. (daynr (org-closest-date s daynr prefer))
  15760. (t (time-to-days
  15761. (condition-case errdata
  15762. (apply #'encode-time (org-parse-time-string s))
  15763. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15764. s
  15765. (if (not (and buffer pos)) ""
  15766. (format-message " at %d in buffer `%s'" pos buffer))
  15767. (cdr errdata))))))))
  15768. (defun org-days-to-iso-week (days)
  15769. "Return the iso week number."
  15770. (require 'cal-iso)
  15771. (car (calendar-iso-from-absolute days)))
  15772. (defun org-small-year-to-year (year)
  15773. "Convert 2-digit years into 4-digit years.
  15774. YEAR is expanded into one of the 30 next years, if possible, or
  15775. into a past one. Any year larger than 99 is returned unchanged."
  15776. (if (>= year 100) year
  15777. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15778. (century (/ current 100))
  15779. (offset (- year (% current 100))))
  15780. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15781. ((> offset -70) (+ (* century 100) year))
  15782. (t (+ (* (1+ century) 100) year))))))
  15783. (defun org-time-from-absolute (d)
  15784. "Return the time corresponding to date D.
  15785. D may be an absolute day number, or a calendar-type list (month day year)."
  15786. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15787. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15788. (defvar org-agenda-current-date)
  15789. (defun org-calendar-holiday ()
  15790. "List of holidays, for Diary display in Org mode."
  15791. (require 'holidays)
  15792. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15793. (and hl (mapconcat #'identity hl "; "))))
  15794. (defun org-diary-sexp-entry (sexp entry d)
  15795. "Process a SEXP diary ENTRY for date D."
  15796. (require 'diary-lib)
  15797. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15798. ;; dynamically.
  15799. (let* ((sexp `(let ((entry ,entry)
  15800. (date ',d))
  15801. ,(car (read-from-string sexp))))
  15802. (result (if calendar-debug-sexp (eval sexp)
  15803. (condition-case nil
  15804. (eval sexp)
  15805. (error
  15806. (beep)
  15807. (message "Bad sexp at line %d in %s: %s"
  15808. (org-current-line)
  15809. (buffer-file-name) sexp)
  15810. (sleep-for 2))))))
  15811. (cond ((stringp result) (split-string result "; "))
  15812. ((and (consp result)
  15813. (not (consp (cdr result)))
  15814. (stringp (cdr result))) (cdr result))
  15815. ((and (consp result)
  15816. (stringp (car result))) result)
  15817. (result entry))))
  15818. (defun org-diary-to-ical-string (frombuf)
  15819. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15820. This uses the icalendar.el library."
  15821. (let* ((tmpdir temporary-file-directory)
  15822. (tmpfile (make-temp-name
  15823. (expand-file-name "orgics" tmpdir)))
  15824. buf rtn b e)
  15825. (with-current-buffer frombuf
  15826. (icalendar-export-region (point-min) (point-max) tmpfile)
  15827. (setq buf (find-buffer-visiting tmpfile))
  15828. (set-buffer buf)
  15829. (goto-char (point-min))
  15830. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15831. (setq b (match-beginning 0)))
  15832. (goto-char (point-max))
  15833. (when (re-search-backward "^END:VEVENT" nil t)
  15834. (setq e (match-end 0)))
  15835. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15836. (kill-buffer buf)
  15837. (delete-file tmpfile)
  15838. rtn))
  15839. (defun org-closest-date (start current prefer)
  15840. "Return closest date to CURRENT starting from START.
  15841. CURRENT and START are both time stamps.
  15842. When PREFER is `past', return a date that is either CURRENT or
  15843. past. When PREFER is `future', return a date that is either
  15844. CURRENT or future.
  15845. Only time stamps with a repeater are modified. Any other time
  15846. stamp stay unchanged. In any case, return value is an absolute
  15847. day number."
  15848. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15849. ;; No repeater. Do not shift time stamp.
  15850. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15851. (let ((value (string-to-number (match-string 1 start)))
  15852. (type (match-string 2 start)))
  15853. (if (= 0 value)
  15854. ;; Repeater with a 0-value is considered as void.
  15855. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15856. (let* ((base (org-date-to-gregorian start))
  15857. (target (org-date-to-gregorian current))
  15858. (sday (calendar-absolute-from-gregorian base))
  15859. (cday (calendar-absolute-from-gregorian target))
  15860. n1 n2)
  15861. ;; If START is already past CURRENT, just return START.
  15862. (if (<= cday sday) sday
  15863. ;; Compute closest date before (N1) and closest date past
  15864. ;; (N2) CURRENT.
  15865. (pcase type
  15866. ("h"
  15867. (let ((missing-hours
  15868. (mod (+ (- (* 24 (- cday sday))
  15869. (nth 2 (org-parse-time-string start)))
  15870. org-extend-today-until)
  15871. value)))
  15872. (setf n1 (if (= missing-hours 0) cday
  15873. (- cday (1+ (/ missing-hours 24)))))
  15874. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15875. ((or "d" "w")
  15876. (let ((value (if (equal type "w") (* 7 value) value)))
  15877. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15878. (setf n2 (+ n1 value))))
  15879. ("m"
  15880. (let* ((add-months
  15881. (lambda (d n)
  15882. ;; Add N months to gregorian date D, i.e.,
  15883. ;; a list (MONTH DAY YEAR). Return a valid
  15884. ;; gregorian date.
  15885. (let ((m (+ (nth 0 d) n)))
  15886. (list (mod m 12)
  15887. (nth 1 d)
  15888. (+ (/ m 12) (nth 2 d))))))
  15889. (months ; Complete months to TARGET.
  15890. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15891. (- (nth 0 target) (nth 0 base))
  15892. ;; If START's day is greater than
  15893. ;; TARGET's, remove incomplete month.
  15894. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15895. value)
  15896. value))
  15897. (before (funcall add-months base months)))
  15898. (setf n1 (calendar-absolute-from-gregorian before))
  15899. (setf n2
  15900. (calendar-absolute-from-gregorian
  15901. (funcall add-months before value)))))
  15902. (_
  15903. (let* ((d (nth 1 base))
  15904. (m (nth 0 base))
  15905. (y (nth 2 base))
  15906. (years ; Complete years to TARGET.
  15907. (* (/ (- (nth 2 target)
  15908. y
  15909. ;; If START's month and day are
  15910. ;; greater than TARGET's, remove
  15911. ;; incomplete year.
  15912. (if (or (> (nth 0 target) m)
  15913. (and (= (nth 0 target) m)
  15914. (> (nth 1 target) d)))
  15915. 0
  15916. 1))
  15917. value)
  15918. value))
  15919. (before (list m d (+ y years))))
  15920. (setf n1 (calendar-absolute-from-gregorian before))
  15921. (setf n2 (calendar-absolute-from-gregorian
  15922. (list m d (+ (nth 2 before) value)))))))
  15923. ;; Handle PREFER parameter, if any.
  15924. (cond
  15925. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15926. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15927. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15928. (defun org-date-to-gregorian (d)
  15929. "Turn any specification of date D into a Gregorian date for the calendar."
  15930. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15931. ((and (listp d) (= (length d) 3)) d)
  15932. ((stringp d)
  15933. (let ((d (org-parse-time-string d)))
  15934. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15935. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15936. (defun org-parse-time-string (s &optional nodefault)
  15937. "Parse the standard Org time string.
  15938. This should be a lot faster than the normal `parse-time-string'.
  15939. If time is not given, defaults to 0:00. However, with optional
  15940. NODEFAULT, hour and minute fields will be nil if not given."
  15941. (cond ((string-match org-ts-regexp0 s)
  15942. (list 0
  15943. (when (or (match-beginning 8) (not nodefault))
  15944. (string-to-number (or (match-string 8 s) "0")))
  15945. (when (or (match-beginning 7) (not nodefault))
  15946. (string-to-number (or (match-string 7 s) "0")))
  15947. (string-to-number (match-string 4 s))
  15948. (string-to-number (match-string 3 s))
  15949. (string-to-number (match-string 2 s))
  15950. nil nil nil))
  15951. ((string-match "^<[^>]+>$" s)
  15952. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15953. ;; second argument. However, this requires at least Emacs
  15954. ;; 25.1. We can do it when we switch to this version as our
  15955. ;; minimal requirement.
  15956. (decode-time (seconds-to-time (org-matcher-time s))))
  15957. (t (error "Not a standard Org time string: %s" s))))
  15958. (defun org-timestamp-up (&optional arg)
  15959. "Increase the date item at the cursor by one.
  15960. If the cursor is on the year, change the year. If it is on the month,
  15961. the day or the time, change that.
  15962. With prefix ARG, change by that many units."
  15963. (interactive "p")
  15964. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15965. (defun org-timestamp-down (&optional arg)
  15966. "Decrease the date item at the cursor by one.
  15967. If the cursor is on the year, change the year. If it is on the month,
  15968. the day or the time, change that.
  15969. With prefix ARG, change by that many units."
  15970. (interactive "p")
  15971. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15972. (defun org-timestamp-up-day (&optional arg)
  15973. "Increase the date in the time stamp by one day.
  15974. With prefix ARG, change that many days."
  15975. (interactive "p")
  15976. (if (and (not (org-at-timestamp-p 'lax))
  15977. (org-at-heading-p))
  15978. (org-todo 'up)
  15979. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15980. (defun org-timestamp-down-day (&optional arg)
  15981. "Decrease the date in the time stamp by one day.
  15982. With prefix ARG, change that many days."
  15983. (interactive "p")
  15984. (if (and (not (org-at-timestamp-p 'lax))
  15985. (org-at-heading-p))
  15986. (org-todo 'down)
  15987. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15988. (defun org-at-timestamp-p (&optional extended)
  15989. "Non-nil if point is inside a timestamp.
  15990. By default, the function only consider syntactically valid active
  15991. timestamps. However, the caller may have a broader definition
  15992. for timestamps. As a consequence, optional argument EXTENDED can
  15993. be set to the following values
  15994. `inactive'
  15995. Include also syntactically valid inactive timestamps.
  15996. `agenda'
  15997. Include timestamps allowed in Agenda, i.e., those in
  15998. properties drawers, planning lines and clock lines.
  15999. `lax'
  16000. Ignore context. The function matches any part of the
  16001. document looking like a timestamp. This includes comments,
  16002. example blocks...
  16003. For backward-compatibility with Org 9.0, every other non-nil
  16004. value is equivalent to `inactive'.
  16005. When at a timestamp, return the position of the point as a symbol
  16006. among `bracket', `after', `year', `month', `hour', `minute',
  16007. `day' or a number of character from the last know part of the
  16008. time stamp.
  16009. When matching, the match groups are the following:
  16010. group 1: year
  16011. group 2: month
  16012. group 3: day number
  16013. group 4: day name
  16014. group 5: hours, if any
  16015. group 6: minutes, if any"
  16016. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16017. (pos (point))
  16018. (match?
  16019. (let ((boundaries (org-in-regexp regexp)))
  16020. (save-match-data
  16021. (cond ((null boundaries) nil)
  16022. ((eq extended 'lax) t)
  16023. (t
  16024. (or (and (eq extended 'agenda)
  16025. (or (org-at-planning-p)
  16026. (org-at-property-p)
  16027. (and (bound-and-true-p
  16028. org-agenda-include-inactive-timestamps)
  16029. (org-at-clock-log-p))))
  16030. (eq 'timestamp
  16031. (save-excursion
  16032. (when (= pos (cdr boundaries)) (forward-char -1))
  16033. (org-element-type (org-element-context)))))))))))
  16034. (cond
  16035. ((not match?) nil)
  16036. ((= pos (match-beginning 0)) 'bracket)
  16037. ;; Distinguish location right before the closing bracket from
  16038. ;; right after it.
  16039. ((= pos (1- (match-end 0))) 'bracket)
  16040. ((= pos (match-end 0)) 'after)
  16041. ((org-pos-in-match-range pos 2) 'year)
  16042. ((org-pos-in-match-range pos 3) 'month)
  16043. ((org-pos-in-match-range pos 7) 'hour)
  16044. ((org-pos-in-match-range pos 8) 'minute)
  16045. ((or (org-pos-in-match-range pos 4)
  16046. (org-pos-in-match-range pos 5)) 'day)
  16047. ((and (> pos (or (match-end 8) (match-end 5)))
  16048. (< pos (match-end 0)))
  16049. (- pos (or (match-end 8) (match-end 5))))
  16050. (t 'day))))
  16051. (defun org-toggle-timestamp-type ()
  16052. "Toggle the type (<active> or [inactive]) of a time stamp."
  16053. (interactive)
  16054. (when (org-at-timestamp-p 'lax)
  16055. (let ((beg (match-beginning 0)) (end (match-end 0))
  16056. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16057. (save-excursion
  16058. (goto-char beg)
  16059. (while (re-search-forward "[][<>]" end t)
  16060. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16061. t t)))
  16062. (message "Timestamp is now %sactive"
  16063. (if (equal (char-after beg) ?<) "" "in")))))
  16064. (defun org-at-clock-log-p ()
  16065. "Non-nil if point is on a clock log line."
  16066. (and (org-match-line org-clock-line-re)
  16067. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16068. (defvar org-clock-history) ; defined in org-clock.el
  16069. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16070. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16071. "Change the date in the time stamp at point.
  16072. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16073. `year', `minute', `second'. If WHAT is not given, the cursor position
  16074. in the timestamp determines what will be changed.
  16075. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16076. (let ((origin (point))
  16077. (timestamp? (org-at-timestamp-p 'lax))
  16078. origin-cat
  16079. with-hm inactive
  16080. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16081. extra rem
  16082. ts time time0 fixnext clrgx)
  16083. (unless timestamp? (user-error "Not at a timestamp"))
  16084. (if (and (not what) (eq timestamp? 'bracket))
  16085. (org-toggle-timestamp-type)
  16086. ;; Point isn't on brackets. Remember the part of the time-stamp
  16087. ;; the point was in. Indeed, size of time-stamps may change,
  16088. ;; but point must be kept in the same category nonetheless.
  16089. (setq origin-cat timestamp?)
  16090. (when (and (not what) (not (eq timestamp? 'day))
  16091. org-display-custom-times
  16092. (get-text-property (point) 'display)
  16093. (not (get-text-property (1- (point)) 'display)))
  16094. (setq timestamp? 'day))
  16095. (setq timestamp? (or what timestamp?)
  16096. inactive (= (char-after (match-beginning 0)) ?\[)
  16097. ts (match-string 0))
  16098. (replace-match "")
  16099. (when (string-match
  16100. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16101. ts)
  16102. (setq extra (match-string 1 ts))
  16103. (when suppress-tmp-delay
  16104. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16105. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16106. (setq with-hm t))
  16107. (setq time0 (org-parse-time-string ts))
  16108. (when (and updown
  16109. (eq timestamp? 'minute)
  16110. (not current-prefix-arg))
  16111. ;; This looks like s-up and s-down. Change by one rounding step.
  16112. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16113. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16114. (setcar (cdr time0) (+ (nth 1 time0)
  16115. (if (> n 0) (- rem) (- dm rem))))))
  16116. (setq time
  16117. (apply #'encode-time
  16118. (or (car time0) 0)
  16119. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16120. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16121. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16122. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16123. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16124. (nthcdr 6 time0)))
  16125. (when (and (memq timestamp? '(hour minute))
  16126. extra
  16127. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16128. (setq extra (org-modify-ts-extra
  16129. extra
  16130. (if (eq timestamp? 'hour) 2 5)
  16131. n dm)))
  16132. (when (integerp timestamp?)
  16133. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16134. (when (eq what 'calendar)
  16135. (let ((cal-date (org-get-date-from-calendar)))
  16136. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16137. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16138. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16139. (setcar time0 (or (car time0) 0))
  16140. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16141. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16142. (setq time (apply 'encode-time time0))))
  16143. ;; Insert the new time-stamp, and ensure point stays in the same
  16144. ;; category as before (i.e. not after the last position in that
  16145. ;; category).
  16146. (let ((pos (point)))
  16147. ;; Stay before inserted string. `save-excursion' is of no use.
  16148. (setq org-last-changed-timestamp
  16149. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16150. (goto-char pos))
  16151. (save-match-data
  16152. (looking-at org-ts-regexp3)
  16153. (goto-char
  16154. (pcase origin-cat
  16155. ;; `day' category ends before `hour' if any, or at the end
  16156. ;; of the day name.
  16157. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16158. (`hour (min (match-end 7) origin))
  16159. (`minute (min (1- (match-end 8)) origin))
  16160. ((pred integerp) (min (1- (match-end 0)) origin))
  16161. ;; Point was right after the time-stamp. However, the
  16162. ;; time-stamp length might have changed, so refer to
  16163. ;; (match-end 0) instead.
  16164. (`after (match-end 0))
  16165. ;; `year' and `month' have both fixed size: point couldn't
  16166. ;; have moved into another part.
  16167. (_ origin))))
  16168. ;; Update clock if on a CLOCK line.
  16169. (org-clock-update-time-maybe)
  16170. ;; Maybe adjust the closest clock in `org-clock-history'
  16171. (when org-clock-adjust-closest
  16172. (if (not (and (org-at-clock-log-p)
  16173. (< 1 (length (delq nil (mapcar 'marker-position
  16174. org-clock-history))))))
  16175. (message "No clock to adjust")
  16176. (cond ((save-excursion ; fix previous clock?
  16177. (re-search-backward org-ts-regexp0 nil t)
  16178. (looking-back (concat org-clock-string " \\[")
  16179. (line-beginning-position)))
  16180. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16181. ((save-excursion ; fix next clock?
  16182. (re-search-backward org-ts-regexp0 nil t)
  16183. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16184. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16185. (save-window-excursion
  16186. ;; Find closest clock to point, adjust the previous/next one in history
  16187. (let* ((p (save-excursion (org-back-to-heading t)))
  16188. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16189. (clfixnth
  16190. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16191. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16192. (if (not clfixpos)
  16193. (message "No clock to adjust")
  16194. (save-excursion
  16195. (org-goto-marker-or-bmk clfixpos)
  16196. (org-show-subtree)
  16197. (when (re-search-forward clrgx nil t)
  16198. (goto-char (match-beginning 1))
  16199. (let (org-clock-adjust-closest)
  16200. (org-timestamp-change n timestamp? updown))
  16201. (message "Clock adjusted in %s for heading: %s"
  16202. (file-name-nondirectory (buffer-file-name))
  16203. (org-get-heading t t)))))))))
  16204. ;; Try to recenter the calendar window, if any.
  16205. (when (and org-calendar-follow-timestamp-change
  16206. (get-buffer-window "*Calendar*" t)
  16207. (memq timestamp? '(day month year)))
  16208. (org-recenter-calendar (time-to-days time))))))
  16209. (defun org-modify-ts-extra (s pos n dm)
  16210. "Change the different parts of the lead-time and repeat fields in timestamp."
  16211. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16212. ng h m new rem)
  16213. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16214. (cond
  16215. ((or (org-pos-in-match-range pos 2)
  16216. (org-pos-in-match-range pos 3))
  16217. (setq m (string-to-number (match-string 3 s))
  16218. h (string-to-number (match-string 2 s)))
  16219. (if (org-pos-in-match-range pos 2)
  16220. (setq h (+ h n))
  16221. (setq n (* dm (with-no-warnings (signum n))))
  16222. (unless (= 0 (setq rem (% m dm)))
  16223. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16224. (setq m (+ m n)))
  16225. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16226. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16227. (setq h (mod h 24))
  16228. (setq ng 1 new (format "-%02d:%02d" h m)))
  16229. ((org-pos-in-match-range pos 6)
  16230. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16231. ((org-pos-in-match-range pos 5)
  16232. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16233. ((org-pos-in-match-range pos 9)
  16234. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16235. ((org-pos-in-match-range pos 8)
  16236. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16237. (when ng
  16238. (setq s (concat
  16239. (substring s 0 (match-beginning ng))
  16240. new
  16241. (substring s (match-end ng))))))
  16242. s))
  16243. (defun org-recenter-calendar (d)
  16244. "If the calendar is visible, recenter it to date D."
  16245. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16246. (when cwin
  16247. (let ((calendar-move-hook nil))
  16248. (with-selected-window cwin
  16249. (calendar-goto-date
  16250. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16251. (defun org-goto-calendar (&optional arg)
  16252. "Go to the Emacs calendar at the current date.
  16253. If there is a time stamp in the current line, go to that date.
  16254. A prefix ARG can be used to force the current date."
  16255. (interactive "P")
  16256. (let ((calendar-move-hook nil)
  16257. (calendar-view-holidays-initially-flag nil)
  16258. (calendar-view-diary-initially-flag nil)
  16259. diff)
  16260. (when (or (org-at-timestamp-p 'lax)
  16261. (org-match-line (concat ".*" org-ts-regexp)))
  16262. (let ((d1 (time-to-days (current-time)))
  16263. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16264. (setq diff (- d2 d1))))
  16265. (calendar)
  16266. (calendar-goto-today)
  16267. (when (and diff (not arg)) (calendar-forward-day diff))))
  16268. (defun org-get-date-from-calendar ()
  16269. "Return a list (month day year) of date at point in calendar."
  16270. (with-current-buffer "*Calendar*"
  16271. (save-match-data
  16272. (calendar-cursor-to-date))))
  16273. (defun org-date-from-calendar ()
  16274. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16275. If there is already a time stamp at the cursor position, update it."
  16276. (interactive)
  16277. (if (org-at-timestamp-p 'lax)
  16278. (org-timestamp-change 0 'calendar)
  16279. (let ((cal-date (org-get-date-from-calendar)))
  16280. (org-insert-time-stamp
  16281. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16282. (defcustom org-effort-durations
  16283. `(("min" . 1)
  16284. ("h" . 60)
  16285. ("d" . ,(* 60 8))
  16286. ("w" . ,(* 60 8 5))
  16287. ("m" . ,(* 60 8 5 4))
  16288. ("y" . ,(* 60 8 5 40)))
  16289. "Conversion factor to minutes for an effort modifier.
  16290. Each entry has the form (MODIFIER . MINUTES).
  16291. In an effort string, a number followed by MODIFIER is multiplied
  16292. by the specified number of MINUTES to obtain an effort in
  16293. minutes.
  16294. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16295. effort string \"2hours\" is equivalent to 120 minutes."
  16296. :group 'org-agenda
  16297. :version "26.1"
  16298. :package-version '(Org . "8.3")
  16299. :type '(alist :key-type (string :tag "Modifier")
  16300. :value-type (number :tag "Minutes")))
  16301. (defcustom org-image-actual-width t
  16302. "Should we use the actual width of images when inlining them?
  16303. When set to t, always use the image width.
  16304. When set to a number, use imagemagick (when available) to set
  16305. the image's width to this value.
  16306. When set to a number in a list, try to get the width from any
  16307. #+ATTR.* keyword if it matches a width specification like
  16308. #+ATTR_HTML: :width 300px
  16309. and fall back on that number if none is found.
  16310. When set to nil, try to get the width from an #+ATTR.* keyword
  16311. and fall back on the original width if none is found.
  16312. This requires Emacs >= 24.1, build with imagemagick support."
  16313. :group 'org-appearance
  16314. :version "24.4"
  16315. :package-version '(Org . "8.0")
  16316. :type '(choice
  16317. (const :tag "Use the image width" t)
  16318. (integer :tag "Use a number of pixels")
  16319. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16320. (const :tag "Use #+ATTR* or don't resize" nil)))
  16321. (defcustom org-agenda-inhibit-startup nil
  16322. "Inhibit startup when preparing agenda buffers.
  16323. When this variable is t, the initialization of the Org agenda
  16324. buffers is inhibited: e.g. the visibility state is not set, the
  16325. tables are not re-aligned, etc."
  16326. :type 'boolean
  16327. :version "24.3"
  16328. :group 'org-agenda)
  16329. (defcustom org-agenda-ignore-properties nil
  16330. "Avoid updating text properties when building the agenda.
  16331. Properties are used to prepare buffers for effort estimates,
  16332. appointments, statistics and subtree-local categories.
  16333. If you don't use these in the agenda, you can add them to this
  16334. list and agenda building will be a bit faster.
  16335. The value is a list, with zero or more of the symbols `effort', `appt',
  16336. `stats' or `category'."
  16337. :type '(set :greedy t
  16338. (const effort)
  16339. (const appt)
  16340. (const stats)
  16341. (const category))
  16342. :version "26.1"
  16343. :package-version '(Org . "8.3")
  16344. :group 'org-agenda)
  16345. ;;;; Files
  16346. (defun org-save-all-org-buffers ()
  16347. "Save all Org buffers without user confirmation."
  16348. (interactive)
  16349. (message "Saving all Org buffers...")
  16350. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16351. (when (featurep 'org-id) (org-id-locations-save))
  16352. (message "Saving all Org buffers... done"))
  16353. (defun org-revert-all-org-buffers ()
  16354. "Revert all Org buffers.
  16355. Prompt for confirmation when there are unsaved changes.
  16356. Be sure you know what you are doing before letting this function
  16357. overwrite your changes.
  16358. This function is useful in a setup where one tracks org files
  16359. with a version control system, to revert on one machine after pulling
  16360. changes from another. I believe the procedure must be like this:
  16361. 1. M-x org-save-all-org-buffers
  16362. 2. Pull changes from the other machine, resolve conflicts
  16363. 3. M-x org-revert-all-org-buffers"
  16364. (interactive)
  16365. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16366. (user-error "Abort"))
  16367. (save-excursion
  16368. (save-window-excursion
  16369. (dolist (b (buffer-list))
  16370. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16371. (with-current-buffer b buffer-file-name))
  16372. (pop-to-buffer-same-window b)
  16373. (revert-buffer t 'no-confirm)))
  16374. (when (and (featurep 'org-id) org-id-track-globally)
  16375. (org-id-locations-load)))))
  16376. ;;;; Agenda files
  16377. ;;;###autoload
  16378. (defun org-switchb (&optional arg)
  16379. "Switch between Org buffers.
  16380. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16381. With `\\[universal-argument] \\[universal-argument]' \
  16382. prefix, restrict available buffers to agenda files."
  16383. (interactive "P")
  16384. (let ((blist (org-buffer-list
  16385. (cond ((equal arg '(4)) 'files)
  16386. ((equal arg '(16)) 'agenda)))))
  16387. (pop-to-buffer-same-window
  16388. (completing-read "Org buffer: "
  16389. (mapcar #'list (mapcar #'buffer-name blist))
  16390. nil t))))
  16391. (defun org-buffer-list (&optional predicate exclude-tmp)
  16392. "Return a list of Org buffers.
  16393. PREDICATE can be `export', `files' or `agenda'.
  16394. export restrict the list to Export buffers.
  16395. files restrict the list to buffers visiting Org files.
  16396. agenda restrict the list to buffers visiting agenda files.
  16397. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16398. (let* ((bfn nil)
  16399. (agenda-files (and (eq predicate 'agenda)
  16400. (mapcar 'file-truename (org-agenda-files t))))
  16401. (filter
  16402. (cond
  16403. ((eq predicate 'files)
  16404. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16405. ((eq predicate 'export)
  16406. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16407. ((eq predicate 'agenda)
  16408. (lambda (b)
  16409. (with-current-buffer b
  16410. (and (derived-mode-p 'org-mode)
  16411. (setq bfn (buffer-file-name b))
  16412. (member (file-truename bfn) agenda-files)))))
  16413. (t (lambda (b) (with-current-buffer b
  16414. (or (derived-mode-p 'org-mode)
  16415. (string-match "\\*Org .*Export"
  16416. (buffer-name b)))))))))
  16417. (delq nil
  16418. (mapcar
  16419. (lambda(b)
  16420. (if (and (funcall filter b)
  16421. (or (not exclude-tmp)
  16422. (not (string-match "tmp" (buffer-name b)))))
  16423. b
  16424. nil))
  16425. (buffer-list)))))
  16426. (defun org-agenda-files (&optional unrestricted archives)
  16427. "Get the list of agenda files.
  16428. Optional UNRESTRICTED means return the full list even if a restriction
  16429. is currently in place.
  16430. When ARCHIVES is t, include all archive files that are really being
  16431. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16432. `org-agenda-archives-mode' is t."
  16433. (let ((files
  16434. (cond
  16435. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16436. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16437. ((listp org-agenda-files) org-agenda-files)
  16438. (t (error "Invalid value of `org-agenda-files'")))))
  16439. (setq files (apply 'append
  16440. (mapcar (lambda (f)
  16441. (if (file-directory-p f)
  16442. (directory-files
  16443. f t org-agenda-file-regexp)
  16444. (list f)))
  16445. files)))
  16446. (when org-agenda-skip-unavailable-files
  16447. (setq files (delq nil
  16448. (mapcar (function
  16449. (lambda (file)
  16450. (and (file-readable-p file) file)))
  16451. files))))
  16452. (when (or (eq archives t)
  16453. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16454. (setq files (org-add-archive-files files)))
  16455. files))
  16456. (defun org-agenda-file-p (&optional file)
  16457. "Return non-nil, if FILE is an agenda file.
  16458. If FILE is omitted, use the file associated with the current
  16459. buffer."
  16460. (let ((fname (or file (buffer-file-name))))
  16461. (and fname
  16462. (member (file-truename fname)
  16463. (mapcar #'file-truename (org-agenda-files t))))))
  16464. (defun org-edit-agenda-file-list ()
  16465. "Edit the list of agenda files.
  16466. Depending on setup, this either uses customize to edit the variable
  16467. `org-agenda-files', or it visits the file that is holding the list. In the
  16468. latter case, the buffer is set up in a way that saving it automatically kills
  16469. the buffer and restores the previous window configuration."
  16470. (interactive)
  16471. (if (stringp org-agenda-files)
  16472. (let ((cw (current-window-configuration)))
  16473. (find-file org-agenda-files)
  16474. (setq-local org-window-configuration cw)
  16475. (add-hook 'after-save-hook
  16476. (lambda ()
  16477. (set-window-configuration
  16478. (prog1 org-window-configuration
  16479. (kill-buffer (current-buffer))))
  16480. (org-install-agenda-files-menu)
  16481. (message "New agenda file list installed"))
  16482. nil 'local)
  16483. (message "%s" (substitute-command-keys
  16484. "Edit list and finish with \\[save-buffer]")))
  16485. (customize-variable 'org-agenda-files)))
  16486. (defun org-store-new-agenda-file-list (list)
  16487. "Set new value for the agenda file list and save it correctly."
  16488. (if (stringp org-agenda-files)
  16489. (let ((fe (org-read-agenda-file-list t)) b u)
  16490. (while (setq b (find-buffer-visiting org-agenda-files))
  16491. (kill-buffer b))
  16492. (with-temp-file org-agenda-files
  16493. (insert
  16494. (mapconcat
  16495. (lambda (f) ;; Keep un-expanded entries.
  16496. (if (setq u (assoc f fe))
  16497. (cdr u)
  16498. f))
  16499. list "\n")
  16500. "\n")))
  16501. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16502. (org-insert-mode-line-in-empty-file nil))
  16503. (setq org-agenda-files list)
  16504. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16505. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16506. "Read the list of agenda files from a file.
  16507. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16508. filenames, used by `org-store-new-agenda-file-list' to write back
  16509. un-expanded file names."
  16510. (when (file-directory-p org-agenda-files)
  16511. (error "`org-agenda-files' cannot be a single directory"))
  16512. (when (stringp org-agenda-files)
  16513. (with-temp-buffer
  16514. (insert-file-contents org-agenda-files)
  16515. (mapcar
  16516. (lambda (f)
  16517. (let ((e (expand-file-name (substitute-in-file-name f)
  16518. org-directory)))
  16519. (if pair-with-expansion
  16520. (cons e f)
  16521. e)))
  16522. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16523. ;;;###autoload
  16524. (defun org-cycle-agenda-files ()
  16525. "Cycle through the files in `org-agenda-files'.
  16526. If the current buffer visits an agenda file, find the next one in the list.
  16527. If the current buffer does not, find the first agenda file."
  16528. (interactive)
  16529. (let* ((fs (or (org-agenda-files t)
  16530. (user-error "No agenda files")))
  16531. (files (copy-sequence fs))
  16532. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16533. file)
  16534. (when tcf
  16535. (while (and (setq file (pop files))
  16536. (not (equal (file-truename file) tcf)))))
  16537. (find-file (car (or files fs)))
  16538. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16539. (defun org-agenda-file-to-front (&optional to-end)
  16540. "Move/add the current file to the top of the agenda file list.
  16541. If the file is not present in the list, it is added to the front. If it is
  16542. present, it is moved there. With optional argument TO-END, add/move to the
  16543. end of the list."
  16544. (interactive "P")
  16545. (let ((org-agenda-skip-unavailable-files nil)
  16546. (file-alist (mapcar (lambda (x)
  16547. (cons (file-truename x) x))
  16548. (org-agenda-files t)))
  16549. (ctf (file-truename
  16550. (or buffer-file-name
  16551. (user-error "Please save the current buffer to a file"))))
  16552. x had)
  16553. (setq x (assoc ctf file-alist) had x)
  16554. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16555. (if to-end
  16556. (setq file-alist (append (delq x file-alist) (list x)))
  16557. (setq file-alist (cons x (delq x file-alist))))
  16558. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16559. (org-install-agenda-files-menu)
  16560. (message "File %s to %s of agenda file list"
  16561. (if had "moved" "added") (if to-end "end" "front"))))
  16562. (defun org-remove-file (&optional file)
  16563. "Remove current file from the list of files in variable `org-agenda-files'.
  16564. These are the files which are being checked for agenda entries.
  16565. Optional argument FILE means use this file instead of the current."
  16566. (interactive)
  16567. (let* ((org-agenda-skip-unavailable-files nil)
  16568. (file (or file buffer-file-name
  16569. (user-error "Current buffer does not visit a file")))
  16570. (true-file (file-truename file))
  16571. (afile (abbreviate-file-name file))
  16572. (files (delq nil (mapcar
  16573. (lambda (x)
  16574. (unless (equal true-file
  16575. (file-truename x))
  16576. x))
  16577. (org-agenda-files t)))))
  16578. (if (not (= (length files) (length (org-agenda-files t))))
  16579. (progn
  16580. (org-store-new-agenda-file-list files)
  16581. (org-install-agenda-files-menu)
  16582. (message "Removed from Org Agenda list: %s" afile))
  16583. (message "File was not in list: %s (not removed)" afile))))
  16584. (defun org-file-menu-entry (file)
  16585. (vector file (list 'find-file file) t))
  16586. (defun org-check-agenda-file (file)
  16587. "Make sure FILE exists. If not, ask user what to do."
  16588. (unless (file-exists-p file)
  16589. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16590. (abbreviate-file-name file))
  16591. (let ((r (downcase (read-char-exclusive))))
  16592. (cond
  16593. ((equal r ?r)
  16594. (org-remove-file file)
  16595. (throw 'nextfile t))
  16596. (t (user-error "Abort"))))))
  16597. (defun org-get-agenda-file-buffer (file)
  16598. "Get an agenda buffer visiting FILE.
  16599. If the buffer needs to be created, add it to the list of buffers
  16600. which might be released later."
  16601. (let ((buf (org-find-base-buffer-visiting file)))
  16602. (if buf
  16603. buf ; just return it
  16604. ;; Make a new buffer and remember it
  16605. (setq buf (find-file-noselect file))
  16606. (when buf (push buf org-agenda-new-buffers))
  16607. buf)))
  16608. (defun org-release-buffers (blist)
  16609. "Release all buffers in list, asking the user for confirmation when needed.
  16610. When a buffer is unmodified, it is just killed. When modified, it is saved
  16611. \(if the user agrees) and then killed."
  16612. (let (file)
  16613. (dolist (buf blist)
  16614. (setq file (buffer-file-name buf))
  16615. (when (and (buffer-modified-p buf)
  16616. file
  16617. (y-or-n-p (format "Save file %s? " file)))
  16618. (with-current-buffer buf (save-buffer)))
  16619. (kill-buffer buf))))
  16620. (defun org-agenda-prepare-buffers (files)
  16621. "Create buffers for all agenda files, protect archived trees and comments."
  16622. (interactive)
  16623. (let ((pa '(:org-archived t))
  16624. (pc '(:org-comment t))
  16625. (pall '(:org-archived t :org-comment t))
  16626. (inhibit-read-only t)
  16627. (org-inhibit-startup org-agenda-inhibit-startup)
  16628. (rea (concat ":" org-archive-tag ":"))
  16629. re pos)
  16630. (setq org-tag-alist-for-agenda nil
  16631. org-tag-groups-alist-for-agenda nil)
  16632. (save-excursion
  16633. (save-restriction
  16634. (dolist (file files)
  16635. (catch 'nextfile
  16636. (if (bufferp file)
  16637. (set-buffer file)
  16638. (org-check-agenda-file file)
  16639. (set-buffer (org-get-agenda-file-buffer file)))
  16640. (widen)
  16641. (org-set-regexps-and-options 'tags-only)
  16642. (setq pos (point))
  16643. (or (memq 'category org-agenda-ignore-properties)
  16644. (org-refresh-category-properties))
  16645. (or (memq 'stats org-agenda-ignore-properties)
  16646. (org-refresh-stats-properties))
  16647. (or (memq 'effort org-agenda-ignore-properties)
  16648. (org-refresh-effort-properties))
  16649. (or (memq 'appt org-agenda-ignore-properties)
  16650. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16651. (setq org-todo-keywords-for-agenda
  16652. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16653. (setq org-done-keywords-for-agenda
  16654. (append org-done-keywords-for-agenda org-done-keywords))
  16655. (setq org-todo-keyword-alist-for-agenda
  16656. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16657. (setq org-tag-alist-for-agenda
  16658. (org-uniquify
  16659. (append org-tag-alist-for-agenda
  16660. org-current-tag-alist)))
  16661. ;; Merge current file's tag groups into global
  16662. ;; `org-tag-groups-alist-for-agenda'.
  16663. (when org-group-tags
  16664. (dolist (alist org-tag-groups-alist)
  16665. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16666. (if old
  16667. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16668. (push alist org-tag-groups-alist-for-agenda)))))
  16669. (org-with-silent-modifications
  16670. (save-excursion
  16671. (remove-text-properties (point-min) (point-max) pall)
  16672. (when org-agenda-skip-archived-trees
  16673. (goto-char (point-min))
  16674. (while (re-search-forward rea nil t)
  16675. (when (org-at-heading-p t)
  16676. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16677. (goto-char (point-min))
  16678. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16679. (while (re-search-forward re nil t)
  16680. (when (save-match-data (org-in-commented-heading-p t))
  16681. (add-text-properties
  16682. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16683. (goto-char pos)))))
  16684. (setq org-todo-keywords-for-agenda
  16685. (org-uniquify org-todo-keywords-for-agenda))
  16686. (setq org-todo-keyword-alist-for-agenda
  16687. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16688. ;;;; CDLaTeX minor mode
  16689. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16690. "Keymap for the minor `org-cdlatex-mode'.")
  16691. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16692. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16693. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16694. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16695. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16696. (defvar org-cdlatex-texmathp-advice-is-done nil
  16697. "Flag remembering if we have applied the advice to texmathp already.")
  16698. (define-minor-mode org-cdlatex-mode
  16699. "Toggle the minor `org-cdlatex-mode'.
  16700. This mode supports entering LaTeX environment and math in LaTeX fragments
  16701. in Org mode.
  16702. \\{org-cdlatex-mode-map}"
  16703. nil " OCDL" nil
  16704. (when org-cdlatex-mode
  16705. (require 'cdlatex)
  16706. (run-hooks 'cdlatex-mode-hook)
  16707. (cdlatex-compute-tables))
  16708. (unless org-cdlatex-texmathp-advice-is-done
  16709. (setq org-cdlatex-texmathp-advice-is-done t)
  16710. (defadvice texmathp (around org-math-always-on activate)
  16711. "Always return t in Org buffers.
  16712. This is because we want to insert math symbols without dollars even outside
  16713. the LaTeX math segments. If Org mode thinks that point is actually inside
  16714. an embedded LaTeX fragment, let `texmathp' do its job.
  16715. `\\[org-cdlatex-mode-map]'"
  16716. (interactive)
  16717. (let (p)
  16718. (cond
  16719. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16720. ((eq this-command 'cdlatex-math-symbol)
  16721. (setq ad-return-value t
  16722. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16723. (t
  16724. (let ((p (org-inside-LaTeX-fragment-p)))
  16725. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16726. (setq ad-return-value t
  16727. texmathp-why '("Org mode embedded math" . 0))
  16728. (when p ad-do-it)))))))))
  16729. (defun turn-on-org-cdlatex ()
  16730. "Unconditionally turn on `org-cdlatex-mode'."
  16731. (org-cdlatex-mode 1))
  16732. (defun org-try-cdlatex-tab ()
  16733. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16734. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16735. - inside a LaTeX fragment, or
  16736. - after the first word in a line, where an abbreviation expansion could
  16737. insert a LaTeX environment."
  16738. (when org-cdlatex-mode
  16739. (cond
  16740. ;; Before any word on the line: No expansion possible.
  16741. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16742. ;; Just after first word on the line: Expand it. Make sure it
  16743. ;; cannot happen on headlines, though.
  16744. ((save-excursion
  16745. (skip-chars-backward "a-zA-Z0-9*")
  16746. (skip-chars-backward " \t")
  16747. (and (bolp) (not (org-at-heading-p))))
  16748. (cdlatex-tab) t)
  16749. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16750. (defun org-cdlatex-underscore-caret (&optional _arg)
  16751. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16752. Revert to the normal definition outside of these fragments."
  16753. (interactive "P")
  16754. (if (org-inside-LaTeX-fragment-p)
  16755. (call-interactively 'cdlatex-sub-superscript)
  16756. (let (org-cdlatex-mode)
  16757. (call-interactively (key-binding (vector last-input-event))))))
  16758. (defun org-cdlatex-math-modify (&optional _arg)
  16759. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16760. Revert to the normal definition outside of these fragments."
  16761. (interactive "P")
  16762. (if (org-inside-LaTeX-fragment-p)
  16763. (call-interactively 'cdlatex-math-modify)
  16764. (let (org-cdlatex-mode)
  16765. (call-interactively (key-binding (vector last-input-event))))))
  16766. (defun org-cdlatex-environment-indent (&optional environment item)
  16767. "Execute `cdlatex-environment' and indent the inserted environment.
  16768. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16769. The inserted environment is indented to current indentation
  16770. unless point is at the beginning of the line, in which the
  16771. environment remains unintended."
  16772. (interactive)
  16773. ;; cdlatex-environment always return nil. Therefore, capture output
  16774. ;; first and determine if an environment was selected.
  16775. (let* ((beg (point-marker))
  16776. (end (copy-marker (point) t))
  16777. (inserted (progn
  16778. (ignore-errors (cdlatex-environment environment item))
  16779. (< beg end)))
  16780. ;; Figure out how many lines to move forward after the
  16781. ;; environment has been inserted.
  16782. (lines (when inserted
  16783. (save-excursion
  16784. (- (cl-loop while (< beg (point))
  16785. with x = 0
  16786. do (forward-line -1)
  16787. (cl-incf x)
  16788. finally return x)
  16789. (if (progn (goto-char beg)
  16790. (and (progn (skip-chars-forward " \t") (eolp))
  16791. (progn (skip-chars-backward " \t") (bolp))))
  16792. 1 0)))))
  16793. (env (org-trim (delete-and-extract-region beg end))))
  16794. (when inserted
  16795. ;; Get indentation of next line unless at column 0.
  16796. (let ((ind (if (bolp) 0
  16797. (save-excursion
  16798. (org-return-indent)
  16799. (prog1 (org-get-indentation)
  16800. (when (progn (skip-chars-forward " \t") (eolp))
  16801. (delete-region beg (point)))))))
  16802. (bol (progn (skip-chars-backward " \t") (bolp))))
  16803. ;; Insert a newline before environment unless at column zero
  16804. ;; to "escape" the current line. Insert a newline if
  16805. ;; something is one the same line as \end{ENVIRONMENT}.
  16806. (insert
  16807. (concat (unless bol "\n") env
  16808. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16809. (unless (zerop ind)
  16810. (save-excursion
  16811. (goto-char beg)
  16812. (while (< (point) end)
  16813. (unless (eolp) (indent-line-to ind))
  16814. (forward-line))))
  16815. (goto-char beg)
  16816. (forward-line lines)
  16817. (indent-line-to ind)))
  16818. (set-marker beg nil)
  16819. (set-marker end nil)))
  16820. ;;;; LaTeX fragments
  16821. (defun org-inside-LaTeX-fragment-p ()
  16822. "Test if point is inside a LaTeX fragment.
  16823. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16824. sequence appearing also before point.
  16825. Even though the matchers for math are configurable, this function assumes
  16826. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16827. delimiters are skipped when they have been removed by customization.
  16828. The return value is nil, or a cons cell with the delimiter and the
  16829. position of this delimiter.
  16830. This function does a reasonably good job, but can locally be fooled by
  16831. for example currency specifications. For example it will assume being in
  16832. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16833. fragments that are properly closed, but during editing, we have to live
  16834. with the uncertainty caused by missing closing delimiters. This function
  16835. looks only before point, not after."
  16836. (catch 'exit
  16837. (let ((pos (point))
  16838. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16839. (lim (save-excursion (org-backward-paragraph) (point)))
  16840. dd-on str (start 0) m re)
  16841. (goto-char pos)
  16842. (when dodollar
  16843. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16844. re (nth 1 (assoc "$" org-latex-regexps)))
  16845. (while (string-match re str start)
  16846. (cond
  16847. ((= (match-end 0) (length str))
  16848. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16849. ((= (match-end 0) (- (length str) 5))
  16850. (throw 'exit nil))
  16851. (t (setq start (match-end 0))))))
  16852. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16853. (goto-char pos)
  16854. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16855. (and (match-beginning 2) (throw 'exit nil))
  16856. ;; count $$
  16857. (while (re-search-backward "\\$\\$" lim t)
  16858. (setq dd-on (not dd-on)))
  16859. (goto-char pos)
  16860. (when dd-on (cons "$$" m))))))
  16861. (defun org-inside-latex-macro-p ()
  16862. "Is point inside a LaTeX macro or its arguments?"
  16863. (save-match-data
  16864. (org-in-regexp
  16865. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16866. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16867. "Build an overlay between BEG and END using IMAGE file.
  16868. Argument IMAGETYPE is the extension of the displayed image,
  16869. as a string. It defaults to \"png\"."
  16870. (let ((ov (make-overlay beg end))
  16871. (imagetype (or (intern imagetype) 'png)))
  16872. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16873. (overlay-put ov 'evaporate t)
  16874. (overlay-put ov
  16875. 'modification-hooks
  16876. (list (lambda (o _flag _beg _end &optional _l)
  16877. (delete-overlay o))))
  16878. (overlay-put ov
  16879. 'display
  16880. (list 'image :type imagetype :file image :ascent 'center))))
  16881. (defun org--list-latex-overlays (&optional beg end)
  16882. "List all Org LaTeX overlays in current buffer.
  16883. Limit to overlays between BEG and END when those are provided."
  16884. (cl-remove-if-not
  16885. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16886. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16887. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16888. "Remove all overlays with LaTeX fragment images in current buffer.
  16889. When optional arguments BEG and END are non-nil, remove all
  16890. overlays between them instead. Return a non-nil value when some
  16891. overlays were removed, nil otherwise."
  16892. (let ((overlays (org--list-latex-overlays beg end)))
  16893. (mapc #'delete-overlay overlays)
  16894. overlays))
  16895. (defun org-toggle-latex-fragment (&optional arg)
  16896. "Preview the LaTeX fragment at point, or all locally or globally.
  16897. If the cursor is on a LaTeX fragment, create the image and overlay
  16898. it over the source code, if there is none. Remove it otherwise.
  16899. If there is no fragment at point, display all fragments in the
  16900. current section.
  16901. With prefix ARG, preview or clear image for all fragments in the
  16902. current subtree or in the whole buffer when used before the first
  16903. headline. With a prefix ARG `\\[universal-argument] \
  16904. \\[universal-argument]' preview or clear images
  16905. for all fragments in the buffer."
  16906. (interactive "P")
  16907. (when (display-graphic-p)
  16908. (catch 'exit
  16909. (save-excursion
  16910. (let (beg end msg)
  16911. (cond
  16912. ((or (equal arg '(16))
  16913. (and (equal arg '(4))
  16914. (org-with-limited-levels (org-before-first-heading-p))))
  16915. (if (org-remove-latex-fragment-image-overlays)
  16916. (progn (message "LaTeX fragments images removed from buffer")
  16917. (throw 'exit nil))
  16918. (setq msg "Creating images for buffer...")))
  16919. ((equal arg '(4))
  16920. (org-with-limited-levels (org-back-to-heading t))
  16921. (setq beg (point))
  16922. (setq end (progn (org-end-of-subtree t) (point)))
  16923. (if (org-remove-latex-fragment-image-overlays beg end)
  16924. (progn
  16925. (message "LaTeX fragment images removed from subtree")
  16926. (throw 'exit nil))
  16927. (setq msg "Creating images for subtree...")))
  16928. ((let ((datum (org-element-context)))
  16929. (when (memq (org-element-type datum)
  16930. '(latex-environment latex-fragment))
  16931. (setq beg (org-element-property :begin datum))
  16932. (setq end (org-element-property :end datum))
  16933. (if (org-remove-latex-fragment-image-overlays beg end)
  16934. (progn (message "LaTeX fragment image removed")
  16935. (throw 'exit nil))
  16936. (setq msg "Creating image...")))))
  16937. (t
  16938. (org-with-limited-levels
  16939. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16940. (outline-previous-heading)
  16941. (point)))
  16942. (setq end (progn (outline-next-heading) (point)))
  16943. (if (org-remove-latex-fragment-image-overlays beg end)
  16944. (progn
  16945. (message "LaTeX fragment images removed from section")
  16946. (throw 'exit nil))
  16947. (setq msg "Creating images for section...")))))
  16948. (let ((file (buffer-file-name (buffer-base-buffer))))
  16949. (org-format-latex
  16950. (concat org-preview-latex-image-directory "org-ltximg")
  16951. beg end
  16952. ;; Emacs cannot overlay images from remote hosts. Create
  16953. ;; it in `temporary-file-directory' instead.
  16954. (if (or (not file) (file-remote-p file))
  16955. temporary-file-directory
  16956. default-directory)
  16957. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16958. (message (concat msg "done")))))))
  16959. (defun org-format-latex
  16960. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16961. "Replace LaTeX fragments with links to an image.
  16962. The function takes care of creating the replacement image.
  16963. Only consider fragments between BEG and END when those are
  16964. provided.
  16965. When optional argument OVERLAYS is non-nil, display the image on
  16966. top of the fragment instead of replacing it.
  16967. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16968. Some of the options can be changed using the variable
  16969. `org-format-latex-options', which see."
  16970. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16971. (unless (eq processing-type 'verbatim)
  16972. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16973. (cnt 0)
  16974. checkdir-flag)
  16975. (goto-char (or beg (point-min)))
  16976. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16977. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16978. (overlay-recenter (or end (point-max))))
  16979. (while (re-search-forward math-regexp end t)
  16980. (unless (and overlays
  16981. (eq (get-char-property (point) 'org-overlay-type)
  16982. 'org-latex-overlay))
  16983. (let* ((context (org-element-context))
  16984. (type (org-element-type context)))
  16985. (when (memq type '(latex-environment latex-fragment))
  16986. (let ((block-type (eq type 'latex-environment))
  16987. (value (org-element-property :value context))
  16988. (beg (org-element-property :begin context))
  16989. (end (save-excursion
  16990. (goto-char (org-element-property :end context))
  16991. (skip-chars-backward " \r\t\n")
  16992. (point))))
  16993. (cond
  16994. ((eq processing-type 'mathjax)
  16995. ;; Prepare for MathJax processing.
  16996. (if (not (string-match "\\`\\$\\$?" value))
  16997. (goto-char end)
  16998. (delete-region beg end)
  16999. (if (string= (match-string 0 value) "$$")
  17000. (insert "\\[" (substring value 2 -2) "\\]")
  17001. (insert "\\(" (substring value 1 -1) "\\)"))))
  17002. ((assq processing-type org-preview-latex-process-alist)
  17003. ;; Process to an image.
  17004. (cl-incf cnt)
  17005. (goto-char beg)
  17006. (let* ((processing-info
  17007. (cdr (assq processing-type org-preview-latex-process-alist)))
  17008. (face (face-at-point))
  17009. ;; Get the colors from the face at point.
  17010. (fg
  17011. (let ((color (plist-get org-format-latex-options
  17012. :foreground)))
  17013. (if (and forbuffer (eq color 'auto))
  17014. (face-attribute face :foreground nil 'default)
  17015. color)))
  17016. (bg
  17017. (let ((color (plist-get org-format-latex-options
  17018. :background)))
  17019. (if (and forbuffer (eq color 'auto))
  17020. (face-attribute face :background nil 'default)
  17021. color)))
  17022. (hash (sha1 (prin1-to-string
  17023. (list org-format-latex-header
  17024. org-latex-default-packages-alist
  17025. org-latex-packages-alist
  17026. org-format-latex-options
  17027. forbuffer value fg bg))))
  17028. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17029. (absprefix (expand-file-name prefix dir))
  17030. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17031. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17032. (sep (and block-type "\n\n"))
  17033. (link (concat sep "[[file:" linkfile "]]" sep))
  17034. (options
  17035. (org-combine-plists
  17036. org-format-latex-options
  17037. `(:foreground ,fg :background ,bg))))
  17038. (when msg (message msg cnt))
  17039. (unless checkdir-flag ; Ensure the directory exists.
  17040. (setq checkdir-flag t)
  17041. (let ((todir (file-name-directory absprefix)))
  17042. (unless (file-directory-p todir)
  17043. (make-directory todir t))))
  17044. (unless (file-exists-p movefile)
  17045. (org-create-formula-image
  17046. value movefile options forbuffer processing-type))
  17047. (if overlays
  17048. (progn
  17049. (dolist (o (overlays-in beg end))
  17050. (when (eq (overlay-get o 'org-overlay-type)
  17051. 'org-latex-overlay)
  17052. (delete-overlay o)))
  17053. (org--format-latex-make-overlay beg end movefile imagetype)
  17054. (goto-char end))
  17055. (delete-region beg end)
  17056. (insert
  17057. (org-add-props link
  17058. (list 'org-latex-src
  17059. (replace-regexp-in-string "\"" "" value)
  17060. 'org-latex-src-embed-type
  17061. (if block-type 'paragraph 'character)))))))
  17062. ((eq processing-type 'mathml)
  17063. ;; Process to MathML.
  17064. (unless (org-format-latex-mathml-available-p)
  17065. (user-error "LaTeX to MathML converter not configured"))
  17066. (cl-incf cnt)
  17067. (when msg (message msg cnt))
  17068. (goto-char beg)
  17069. (delete-region beg end)
  17070. (insert (org-format-latex-as-mathml
  17071. value block-type prefix dir)))
  17072. (t
  17073. (error "Unknown conversion process %s for LaTeX fragments"
  17074. processing-type)))))))))))
  17075. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17076. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17077. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17078. sucessful, return the portion between \"<math...> </math>\"
  17079. elements otherwise return nil. When MATHML-FILE is specified,
  17080. write the results in to that file. When invoked as an
  17081. interactive command, prompt for LATEX-FRAG, with initial value
  17082. set to the current active region and echo the results for user
  17083. inspection."
  17084. (interactive (list (let ((frag (when (org-region-active-p)
  17085. (buffer-substring-no-properties
  17086. (region-beginning) (region-end)))))
  17087. (read-string "LaTeX Fragment: " frag nil frag))))
  17088. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17089. (let* ((tmp-in-file
  17090. (let ((file (file-relative-name
  17091. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17092. (write-region latex-frag nil file)
  17093. file))
  17094. (tmp-out-file (file-relative-name
  17095. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17096. (cmd (format-spec
  17097. org-latex-to-mathml-convert-command
  17098. `((?j . ,(and org-latex-to-mathml-jar-file
  17099. (shell-quote-argument
  17100. (expand-file-name
  17101. org-latex-to-mathml-jar-file))))
  17102. (?I . ,(shell-quote-argument tmp-in-file))
  17103. (?i . ,latex-frag)
  17104. (?o . ,(shell-quote-argument tmp-out-file)))))
  17105. mathml shell-command-output)
  17106. (when (called-interactively-p 'any)
  17107. (unless (org-format-latex-mathml-available-p)
  17108. (user-error "LaTeX to MathML converter not configured")))
  17109. (message "Running %s" cmd)
  17110. (setq shell-command-output (shell-command-to-string cmd))
  17111. (setq mathml
  17112. (when (file-readable-p tmp-out-file)
  17113. (with-current-buffer (find-file-noselect tmp-out-file t)
  17114. (goto-char (point-min))
  17115. (when (re-search-forward
  17116. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17117. (regexp-quote
  17118. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17119. nil t)
  17120. (prog1 (match-string 0) (kill-buffer))))))
  17121. (cond
  17122. (mathml
  17123. (setq mathml
  17124. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17125. (when mathml-file
  17126. (write-region mathml nil mathml-file))
  17127. (when (called-interactively-p 'any)
  17128. (message mathml)))
  17129. ((message "LaTeX to MathML conversion failed")
  17130. (message shell-command-output)))
  17131. (delete-file tmp-in-file)
  17132. (when (file-exists-p tmp-out-file)
  17133. (delete-file tmp-out-file))
  17134. mathml))
  17135. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17136. prefix &optional dir)
  17137. "Use `org-create-math-formula' but check local cache first."
  17138. (let* ((absprefix (expand-file-name prefix dir))
  17139. (print-length nil) (print-level nil)
  17140. (formula-id (concat
  17141. "formula-"
  17142. (sha1
  17143. (prin1-to-string
  17144. (list latex-frag
  17145. org-latex-to-mathml-convert-command)))))
  17146. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17147. (formula-cache-dir (file-name-directory formula-cache)))
  17148. (unless (file-directory-p formula-cache-dir)
  17149. (make-directory formula-cache-dir t))
  17150. (unless (file-exists-p formula-cache)
  17151. (org-create-math-formula latex-frag formula-cache))
  17152. (if (file-exists-p formula-cache)
  17153. ;; Successful conversion. Return the link to MathML file.
  17154. (org-add-props
  17155. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17156. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17157. 'org-latex-src-embed-type (if latex-frag-type
  17158. 'paragraph 'character)))
  17159. ;; Failed conversion. Return the LaTeX fragment verbatim
  17160. latex-frag)))
  17161. (defun org--get-display-dpi ()
  17162. "Get the DPI of the display.
  17163. The function assumes that the display has the same pixel width in
  17164. the horizontal and vertical directions."
  17165. (if (display-graphic-p)
  17166. (round (/ (display-pixel-height)
  17167. (/ (display-mm-height) 25.4)))
  17168. (error "Attempt to calculate the dpi of a non-graphic display")))
  17169. (defun org-create-formula-image
  17170. (string tofile options buffer &optional processing-type)
  17171. "Create an image from LaTeX source using external processes.
  17172. The LaTeX STRING is saved to a temporary LaTeX file, then
  17173. converted to an image file by process PROCESSING-TYPE defined in
  17174. `org-preview-latex-process-alist'. A nil value defaults to
  17175. `org-preview-latex-default-process'.
  17176. The generated image file is eventually moved to TOFILE.
  17177. The OPTIONS argument controls the size, foreground color and
  17178. background color of the generated image.
  17179. When BUFFER non-nil, this function is used for LaTeX previewing.
  17180. Otherwise, it is used to deal with LaTeX snippets showed in
  17181. a HTML file."
  17182. (let* ((processing-type (or processing-type
  17183. org-preview-latex-default-process))
  17184. (processing-info
  17185. (cdr (assq processing-type org-preview-latex-process-alist)))
  17186. (programs (plist-get processing-info :programs))
  17187. (error-message (or (plist-get processing-info :message) ""))
  17188. (use-xcolor (plist-get processing-info :use-xcolor))
  17189. (image-input-type (plist-get processing-info :image-input-type))
  17190. (image-output-type (plist-get processing-info :image-output-type))
  17191. (post-clean (or (plist-get processing-info :post-clean)
  17192. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17193. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17194. (latex-header
  17195. (or (plist-get processing-info :latex-header)
  17196. (org-latex-make-preamble
  17197. (org-export-get-environment (org-export-get-backend 'latex))
  17198. org-format-latex-header
  17199. 'snippet)))
  17200. (latex-compiler (plist-get processing-info :latex-compiler))
  17201. (image-converter (plist-get processing-info :image-converter))
  17202. (tmpdir temporary-file-directory)
  17203. (texfilebase (make-temp-name
  17204. (expand-file-name "orgtex" tmpdir)))
  17205. (texfile (concat texfilebase ".tex"))
  17206. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17207. '(1.0 . 1.0)))
  17208. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17209. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17210. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17211. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17212. "Black"))
  17213. (bg (or (plist-get options (if buffer :background :html-background))
  17214. "Transparent"))
  17215. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17216. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17217. (dolist (program programs)
  17218. (org-check-external-command program error-message))
  17219. (if use-xcolor
  17220. (progn (if (eq fg 'default)
  17221. (setq fg (org-latex-color :foreground))
  17222. (setq fg (org-latex-color-format fg)))
  17223. (if (eq bg 'default)
  17224. (setq bg (org-latex-color :background))
  17225. (setq bg (org-latex-color-format
  17226. (if (string= bg "Transparent") "white" bg))))
  17227. (with-temp-file texfile
  17228. (insert latex-header)
  17229. (insert "\n\\begin{document}\n"
  17230. "\\definecolor{fg}{rgb}{" fg "}\n"
  17231. "\\definecolor{bg}{rgb}{" bg "}\n"
  17232. "\n\\pagecolor{bg}\n"
  17233. "\n{\\color{fg}\n"
  17234. string
  17235. "\n}\n"
  17236. "\n\\end{document}\n")))
  17237. (if (eq fg 'default)
  17238. (setq fg (org-dvipng-color :foreground))
  17239. (unless (string= fg "Transparent")
  17240. (setq fg (org-dvipng-color-format fg))))
  17241. (if (eq bg 'default)
  17242. (setq bg (org-dvipng-color :background))
  17243. (unless (string= bg "Transparent")
  17244. (setq bg (org-dvipng-color-format bg))))
  17245. (with-temp-file texfile
  17246. (insert latex-header)
  17247. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17248. (let* ((err-msg (format "Please adjust `%s' part of \
  17249. `org-preview-latex-process-alist'."
  17250. processing-type))
  17251. (image-input-file
  17252. (org-compile-file
  17253. texfile latex-compiler image-input-type err-msg log-buf))
  17254. (image-output-file
  17255. (org-compile-file
  17256. image-input-file image-converter image-output-type err-msg log-buf
  17257. `((?F . ,(shell-quote-argument fg))
  17258. (?B . ,(shell-quote-argument bg))
  17259. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17260. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17261. (copy-file image-output-file tofile 'replace)
  17262. (dolist (e post-clean)
  17263. (when (file-exists-p (concat texfilebase e))
  17264. (delete-file (concat texfilebase e))))
  17265. image-output-file)))
  17266. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17267. "Fill a LaTeX header template TPL.
  17268. In the template, the following place holders will be recognized:
  17269. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17270. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17271. [PACKAGES] \\usepackage statements for PKG
  17272. [NO-PACKAGES] do not include PKG
  17273. [EXTRA] the string EXTRA
  17274. [NO-EXTRA] do not include EXTRA
  17275. For backward compatibility, if both the positive and the negative place
  17276. holder is missing, the positive one (without the \"NO-\") will be
  17277. assumed to be present at the end of the template.
  17278. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17279. EXTRA is a string.
  17280. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17281. (let (rpl (end ""))
  17282. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17283. (setq rpl (if (or (match-end 1) (not def-pkg))
  17284. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17285. tpl (replace-match rpl t t tpl))
  17286. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17287. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17288. (setq rpl (if (or (match-end 1) (not pkg))
  17289. "" (org-latex-packages-to-string pkg snippets-p t))
  17290. tpl (replace-match rpl t t tpl))
  17291. (when pkg (setq end
  17292. (concat end "\n"
  17293. (org-latex-packages-to-string pkg snippets-p)))))
  17294. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17295. (setq rpl (if (or (match-end 1) (not extra))
  17296. "" (concat extra "\n"))
  17297. tpl (replace-match rpl t t tpl))
  17298. (when (and extra (string-match "\\S-" extra))
  17299. (setq end (concat end "\n" extra))))
  17300. (if (string-match "\\S-" end)
  17301. (concat tpl "\n" end)
  17302. tpl)))
  17303. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17304. "Turn an alist of packages into a string with the \\usepackage macros."
  17305. (setq pkg (mapconcat (lambda(p)
  17306. (cond
  17307. ((stringp p) p)
  17308. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17309. (format "%% Package %s omitted" (cadr p)))
  17310. ((equal "" (car p))
  17311. (format "\\usepackage{%s}" (cadr p)))
  17312. (t
  17313. (format "\\usepackage[%s]{%s}"
  17314. (car p) (cadr p)))))
  17315. pkg
  17316. "\n"))
  17317. (if newline (concat pkg "\n") pkg))
  17318. (defun org-dvipng-color (attr)
  17319. "Return a RGB color specification for dvipng."
  17320. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17321. (defun org-dvipng-color-format (color-name)
  17322. "Convert COLOR-NAME to a RGB color value for dvipng."
  17323. (apply #'format "rgb %s %s %s"
  17324. (mapcar 'org-normalize-color
  17325. (color-values color-name))))
  17326. (defun org-latex-color (attr)
  17327. "Return a RGB color for the LaTeX color package."
  17328. (org-latex-color-format (face-attribute 'default attr nil)))
  17329. (defun org-latex-color-format (color-name)
  17330. "Convert COLOR-NAME to a RGB color value."
  17331. (apply #'format "%s,%s,%s"
  17332. (mapcar 'org-normalize-color
  17333. (color-values color-name))))
  17334. (defun org-normalize-color (value)
  17335. "Return string to be used as color value for an RGB component."
  17336. (format "%g" (/ value 65535.0)))
  17337. ;; Image display
  17338. (defvar-local org-inline-image-overlays nil)
  17339. (defun org-toggle-inline-images (&optional include-linked)
  17340. "Toggle the display of inline images.
  17341. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17342. (interactive "P")
  17343. (if org-inline-image-overlays
  17344. (progn
  17345. (org-remove-inline-images)
  17346. (when (called-interactively-p 'interactive)
  17347. (message "Inline image display turned off")))
  17348. (org-display-inline-images include-linked)
  17349. (when (called-interactively-p 'interactive)
  17350. (message (if org-inline-image-overlays
  17351. (format "%d images displayed inline"
  17352. (length org-inline-image-overlays))
  17353. "No images to display inline")))))
  17354. (defun org-redisplay-inline-images ()
  17355. "Refresh the display of inline images."
  17356. (interactive)
  17357. (if (not org-inline-image-overlays)
  17358. (org-toggle-inline-images)
  17359. (org-toggle-inline-images)
  17360. (org-toggle-inline-images)))
  17361. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17362. "Display inline images.
  17363. An inline image is a link which follows either of these
  17364. conventions:
  17365. 1. Its path is a file with an extension matching return value
  17366. from `image-file-name-regexp' and it has no contents.
  17367. 2. Its description consists in a single link of the previous
  17368. type.
  17369. When optional argument INCLUDE-LINKED is non-nil, also links with
  17370. a text description part will be inlined. This can be nice for
  17371. a quick look at those images, but it does not reflect what
  17372. exported files will look like.
  17373. When optional argument REFRESH is non-nil, refresh existing
  17374. images between BEG and END. This will create new image displays
  17375. only if necessary. BEG and END default to the buffer
  17376. boundaries."
  17377. (interactive "P")
  17378. (when (display-graphic-p)
  17379. (unless refresh
  17380. (org-remove-inline-images)
  17381. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17382. (org-with-wide-buffer
  17383. (goto-char (or beg (point-min)))
  17384. (let* ((case-fold-search t)
  17385. (file-extension-re (image-file-name-regexp))
  17386. (link-abbrevs (mapcar #'car
  17387. (append org-link-abbrev-alist-local
  17388. org-link-abbrev-alist)))
  17389. ;; Check absolute, relative file names and explicit
  17390. ;; "file:" links. Also check link abbreviations since
  17391. ;; some might expand to "file" links.
  17392. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17393. (if (not link-abbrevs) ""
  17394. (format "\\|\\(?:%s:\\)"
  17395. (regexp-opt link-abbrevs))))))
  17396. (while (re-search-forward file-types-re end t)
  17397. (let ((link (save-match-data (org-element-context))))
  17398. ;; Check if we're at an inline image, i.e., an image file
  17399. ;; link without a description (unless INCLUDE-LINKED is
  17400. ;; non-nil).
  17401. (when (and (equal "file" (org-element-property :type link))
  17402. (or include-linked
  17403. (null (org-element-contents link)))
  17404. (string-match-p file-extension-re
  17405. (org-element-property :path link)))
  17406. (let ((file (expand-file-name
  17407. (org-link-unescape
  17408. (org-element-property :path link)))))
  17409. (when (file-exists-p file)
  17410. (let ((width
  17411. ;; Apply `org-image-actual-width' specifications.
  17412. (cond
  17413. ((not (image-type-available-p 'imagemagick)) nil)
  17414. ((eq org-image-actual-width t) nil)
  17415. ((listp org-image-actual-width)
  17416. (or
  17417. ;; First try to find a width among
  17418. ;; attributes associated to the paragraph
  17419. ;; containing link.
  17420. (let ((paragraph
  17421. (let ((e link))
  17422. (while (and (setq e (org-element-property
  17423. :parent e))
  17424. (not (eq (org-element-type e)
  17425. 'paragraph))))
  17426. e)))
  17427. (when paragraph
  17428. (save-excursion
  17429. (goto-char (org-element-property :begin paragraph))
  17430. (when
  17431. (re-search-forward
  17432. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17433. (org-element-property
  17434. :post-affiliated paragraph)
  17435. t)
  17436. (string-to-number (match-string 1))))))
  17437. ;; Otherwise, fall-back to provided number.
  17438. (car org-image-actual-width)))
  17439. ((numberp org-image-actual-width)
  17440. org-image-actual-width)))
  17441. (old (get-char-property-and-overlay
  17442. (org-element-property :begin link)
  17443. 'org-image-overlay)))
  17444. (if (and (car-safe old) refresh)
  17445. (image-refresh (overlay-get (cdr old) 'display))
  17446. (let ((image (create-image file
  17447. (and width 'imagemagick)
  17448. nil
  17449. :width width)))
  17450. (when image
  17451. (let ((ov (make-overlay
  17452. (org-element-property :begin link)
  17453. (progn
  17454. (goto-char
  17455. (org-element-property :end link))
  17456. (skip-chars-backward " \t")
  17457. (point)))))
  17458. (overlay-put ov 'display image)
  17459. (overlay-put ov 'face 'default)
  17460. (overlay-put ov 'org-image-overlay t)
  17461. (overlay-put
  17462. ov 'modification-hooks
  17463. (list 'org-display-inline-remove-overlay))
  17464. (push ov org-inline-image-overlays)))))))))))))))
  17465. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17466. "Remove inline-display overlay if a corresponding region is modified."
  17467. (let ((inhibit-modification-hooks t))
  17468. (when (and ov after)
  17469. (delete ov org-inline-image-overlays)
  17470. (delete-overlay ov))))
  17471. (defun org-remove-inline-images ()
  17472. "Remove inline display of images."
  17473. (interactive)
  17474. (mapc #'delete-overlay org-inline-image-overlays)
  17475. (setq org-inline-image-overlays nil))
  17476. ;;;; Key bindings
  17477. (defun org-remap (map &rest commands)
  17478. "In MAP, remap the functions given in COMMANDS.
  17479. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17480. (let (new old)
  17481. (while commands
  17482. (setq old (pop commands) new (pop commands))
  17483. (org-defkey map (vector 'remap old) new))))
  17484. ;; Outline functions from `outline-mode-prefix-map'
  17485. ;; that can be remapped in Org:
  17486. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17487. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17488. (define-key org-mode-map [remap outline-forward-same-level]
  17489. 'org-forward-heading-same-level)
  17490. (define-key org-mode-map [remap outline-backward-same-level]
  17491. 'org-backward-heading-same-level)
  17492. (define-key org-mode-map [remap outline-show-branches]
  17493. 'org-kill-note-or-show-branches)
  17494. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17495. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17496. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17497. (define-key org-mode-map [remap outline-next-visible-heading]
  17498. 'org-next-visible-heading)
  17499. (define-key org-mode-map [remap outline-previous-visible-heading]
  17500. 'org-previous-visible-heading)
  17501. (define-key org-mode-map [remap show-children] 'org-show-children)
  17502. ;; Outline functions from `outline-mode-prefix-map' that can not
  17503. ;; be remapped in Org:
  17504. ;; - the column "key binding" shows whether the Outline function is still
  17505. ;; available in Org mode on the same key that it has been bound to in
  17506. ;; Outline mode:
  17507. ;; - "overridden": key used for a different functionality in Org mode
  17508. ;; - else: key still bound to the same Outline function in Org mode
  17509. ;; | Outline function | key binding | Org replacement |
  17510. ;; |------------------------------------+-------------+--------------------------|
  17511. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17512. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17513. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17514. ;; | `show-entry' | overridden | no replacement |
  17515. ;; | `show-branches' | `C-c C-k' | still same function |
  17516. ;; | `show-subtree' | overridden | visibility cycling |
  17517. ;; | `show-all' | overridden | no replacement |
  17518. ;; | `hide-subtree' | overridden | visibility cycling |
  17519. ;; | `hide-body' | overridden | no replacement |
  17520. ;; | `hide-entry' | overridden | visibility cycling |
  17521. ;; | `hide-leaves' | overridden | no replacement |
  17522. ;; | `hide-sublevels' | overridden | no replacement |
  17523. ;; | `hide-other' | overridden | no replacement |
  17524. ;; Make `C-c C-x' a prefix key
  17525. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17526. ;; TAB key with modifiers
  17527. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17528. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17529. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17530. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17531. ;; The following line is necessary under Suse GNU/Linux
  17532. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17533. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17534. (define-key org-mode-map [backtab] 'org-shifttab)
  17535. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17536. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17537. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17538. ;; Cursor keys with modifiers
  17539. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17540. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17541. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17542. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17543. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17544. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17545. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17546. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17547. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17548. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17549. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17550. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17551. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17552. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17553. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17554. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17555. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17556. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17557. ;; Babel keys
  17558. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17559. (dolist (pair org-babel-key-bindings)
  17560. (define-key org-babel-map (car pair) (cdr pair)))
  17561. ;;; Extra keys for tty access.
  17562. ;; We only set them when really needed because otherwise the
  17563. ;; menus don't show the simple keys
  17564. (when (or org-use-extra-keys (not window-system))
  17565. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17566. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17567. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17568. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17569. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17570. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17571. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17572. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17573. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17574. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17575. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17576. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17577. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17578. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17579. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17580. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17581. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17582. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17583. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17584. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17585. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17586. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17587. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17588. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17589. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17590. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17591. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17592. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17593. ;; All the other keys
  17594. (org-remap org-mode-map
  17595. 'self-insert-command 'org-self-insert-command
  17596. 'delete-char 'org-delete-char
  17597. 'delete-backward-char 'org-delete-backward-char)
  17598. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17599. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17600. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17601. (if (boundp 'narrow-map)
  17602. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17603. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17604. (if (boundp 'narrow-map)
  17605. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17606. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17607. (if (boundp 'narrow-map)
  17608. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17609. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17610. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17611. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17612. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17613. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17614. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17615. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17616. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17617. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17618. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17619. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17620. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17621. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17622. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17623. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17624. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17625. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17626. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17627. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17628. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17629. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17630. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17631. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17632. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17633. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17634. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17635. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17636. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17637. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17638. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17639. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17640. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17641. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17642. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17643. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17644. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17645. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17646. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17647. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17648. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17649. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17650. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17651. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17652. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17653. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17654. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17655. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17656. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17657. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17658. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17659. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17660. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17661. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17662. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17663. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17664. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17665. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17666. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17667. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17668. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17669. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17670. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17671. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17672. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17673. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17674. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17675. (org-defkey org-mode-map "\C-m" 'org-return)
  17676. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17677. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17678. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17679. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17680. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17681. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17682. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17683. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17684. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17685. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17686. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17687. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17688. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17689. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17690. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17691. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17692. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17693. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17694. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17695. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17696. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17697. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17698. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17699. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17700. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17701. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17702. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17703. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17704. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17705. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17706. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17707. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17708. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17709. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17710. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17711. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17712. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17713. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17714. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17715. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17716. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17717. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17718. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17719. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17720. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17721. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17722. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17723. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17724. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17725. (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
  17726. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17727. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17728. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17729. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17730. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17731. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17732. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17733. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17734. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17735. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17736. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17737. (defconst org-speed-commands-default
  17738. '(
  17739. ("Outline Navigation")
  17740. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17741. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17742. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17743. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17744. ("F" . org-next-block)
  17745. ("B" . org-previous-block)
  17746. ("u" . (org-speed-move-safe 'outline-up-heading))
  17747. ("j" . org-goto)
  17748. ("g" . (org-refile t))
  17749. ("Outline Visibility")
  17750. ("c" . org-cycle)
  17751. ("C" . org-shifttab)
  17752. (" " . org-display-outline-path)
  17753. ("s" . org-narrow-to-subtree)
  17754. ("=" . org-columns)
  17755. ("Outline Structure Editing")
  17756. ("U" . org-metaup)
  17757. ("D" . org-metadown)
  17758. ("r" . org-metaright)
  17759. ("l" . org-metaleft)
  17760. ("R" . org-shiftmetaright)
  17761. ("L" . org-shiftmetaleft)
  17762. ("i" . (progn (forward-char 1) (call-interactively
  17763. 'org-insert-heading-respect-content)))
  17764. ("^" . org-sort)
  17765. ("w" . org-refile)
  17766. ("a" . org-archive-subtree-default-with-confirmation)
  17767. ("@" . org-mark-subtree)
  17768. ("#" . org-toggle-comment)
  17769. ("Clock Commands")
  17770. ("I" . org-clock-in)
  17771. ("O" . org-clock-out)
  17772. ("Meta Data Editing")
  17773. ("t" . org-todo)
  17774. ("," . (org-priority))
  17775. ("0" . (org-priority ?\ ))
  17776. ("1" . (org-priority ?A))
  17777. ("2" . (org-priority ?B))
  17778. ("3" . (org-priority ?C))
  17779. (":" . org-set-tags-command)
  17780. ("e" . org-set-effort)
  17781. ("E" . org-inc-effort)
  17782. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17783. (org-entry-put (point) "APPT_WARNTIME" m)))
  17784. ("Agenda Views etc")
  17785. ("v" . org-agenda)
  17786. ("/" . org-sparse-tree)
  17787. ("Misc")
  17788. ("o" . org-open-at-point)
  17789. ("?" . org-speed-command-help)
  17790. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17791. (">" . (org-agenda-remove-restriction-lock))
  17792. )
  17793. "The default speed commands.")
  17794. (defun org-print-speed-command (e)
  17795. (if (> (length (car e)) 1)
  17796. (progn
  17797. (princ "\n")
  17798. (princ (car e))
  17799. (princ "\n")
  17800. (princ (make-string (length (car e)) ?-))
  17801. (princ "\n"))
  17802. (princ (car e))
  17803. (princ " ")
  17804. (if (symbolp (cdr e))
  17805. (princ (symbol-name (cdr e)))
  17806. (prin1 (cdr e)))
  17807. (princ "\n")))
  17808. (defun org-speed-command-help ()
  17809. "Show the available speed commands."
  17810. (interactive)
  17811. (if (not org-use-speed-commands)
  17812. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17813. (with-output-to-temp-buffer "*Help*"
  17814. (princ "User-defined Speed commands\n===========================\n")
  17815. (mapc #'org-print-speed-command org-speed-commands-user)
  17816. (princ "\n")
  17817. (princ "Built-in Speed commands\n=======================\n")
  17818. (mapc #'org-print-speed-command org-speed-commands-default))
  17819. (with-current-buffer "*Help*"
  17820. (setq truncate-lines t))))
  17821. (defun org-speed-move-safe (cmd)
  17822. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17823. If not, return to the original position and throw an error."
  17824. (interactive)
  17825. (let ((pos (point)))
  17826. (call-interactively cmd)
  17827. (unless (and (bolp) (org-at-heading-p))
  17828. (goto-char pos)
  17829. (error "Boundary reached while executing %s" cmd))))
  17830. (defvar org-self-insert-command-undo-counter 0)
  17831. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17832. (defvar org-speed-command nil)
  17833. (defun org-speed-command-activate (keys)
  17834. "Hook for activating single-letter speed commands.
  17835. `org-speed-commands-default' specifies a minimal command set.
  17836. Use `org-speed-commands-user' for further customization."
  17837. (when (or (and (bolp) (looking-at org-outline-regexp))
  17838. (and (functionp org-use-speed-commands)
  17839. (funcall org-use-speed-commands)))
  17840. (cdr (assoc keys (append org-speed-commands-user
  17841. org-speed-commands-default)))))
  17842. (defun org-babel-speed-command-activate (keys)
  17843. "Hook for activating single-letter code block commands."
  17844. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17845. (cdr (assoc keys org-babel-key-bindings))))
  17846. (defcustom org-speed-command-hook
  17847. '(org-speed-command-activate org-babel-speed-command-activate)
  17848. "Hook for activating speed commands at strategic locations.
  17849. Hook functions are called in sequence until a valid handler is
  17850. found.
  17851. Each hook takes a single argument, a user-pressed command key
  17852. which is also a `self-insert-command' from the global map.
  17853. Within the hook, examine the cursor position and the command key
  17854. and return nil or a valid handler as appropriate. Handler could
  17855. be one of an interactive command, a function, or a form.
  17856. Set `org-use-speed-commands' to non-nil value to enable this
  17857. hook. The default setting is `org-speed-command-activate'."
  17858. :group 'org-structure
  17859. :version "24.1"
  17860. :type 'hook)
  17861. (defun org-self-insert-command (N)
  17862. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17863. If the cursor is in a table looking at whitespace, the whitespace is
  17864. overwritten, and the table is not marked as requiring realignment."
  17865. (interactive "p")
  17866. (org-check-before-invisible-edit 'insert)
  17867. (cond
  17868. ((and org-use-speed-commands
  17869. (let ((kv (this-command-keys-vector)))
  17870. (setq org-speed-command
  17871. (run-hook-with-args-until-success
  17872. 'org-speed-command-hook
  17873. (make-string 1 (aref kv (1- (length kv))))))))
  17874. (cond
  17875. ((commandp org-speed-command)
  17876. (setq this-command org-speed-command)
  17877. (call-interactively org-speed-command))
  17878. ((functionp org-speed-command)
  17879. (funcall org-speed-command))
  17880. ((and org-speed-command (listp org-speed-command))
  17881. (eval org-speed-command))
  17882. (t (let (org-use-speed-commands)
  17883. (call-interactively 'org-self-insert-command)))))
  17884. ((and
  17885. (org-at-table-p)
  17886. (eq N 1)
  17887. (not (org-region-active-p))
  17888. (progn
  17889. ;; Check if we blank the field, and if that triggers align.
  17890. (and (featurep 'org-table) org-table-auto-blank-field
  17891. (memq last-command
  17892. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17893. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17894. ;; Got extra space, this field does not determine
  17895. ;; column width.
  17896. (let (org-table-may-need-update) (org-table-blank-field))
  17897. ;; No extra space, this field may determine column
  17898. ;; width.
  17899. (org-table-blank-field)))
  17900. t)
  17901. (looking-at "[^|\n]* \\( \\)|"))
  17902. ;; There is room for insertion without re-aligning the table.
  17903. (delete-region (match-beginning 1) (match-end 1))
  17904. (self-insert-command N))
  17905. (t
  17906. (setq org-table-may-need-update t)
  17907. (self-insert-command N)
  17908. (org-fix-tags-on-the-fly)
  17909. (when org-self-insert-cluster-for-undo
  17910. (if (not (eq last-command 'org-self-insert-command))
  17911. (setq org-self-insert-command-undo-counter 1)
  17912. (if (>= org-self-insert-command-undo-counter 20)
  17913. (setq org-self-insert-command-undo-counter 1)
  17914. (and (> org-self-insert-command-undo-counter 0)
  17915. buffer-undo-list (listp buffer-undo-list)
  17916. (not (cadr buffer-undo-list)) ; remove nil entry
  17917. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17918. (setq org-self-insert-command-undo-counter
  17919. (1+ org-self-insert-command-undo-counter))))))))
  17920. (defun org-check-before-invisible-edit (kind)
  17921. "Check is editing if kind KIND would be dangerous with invisible text around.
  17922. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17923. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17924. (when (and org-catch-invisible-edits
  17925. (or (not (boundp 'visible-mode)) (not visible-mode))
  17926. (or (get-char-property (point) 'invisible)
  17927. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17928. ;; OK, we need to take a closer look. Do not consider
  17929. ;; invisibility obtained through text properties (e.g., link
  17930. ;; fontification), as it cannot be toggled.
  17931. (let* ((invisible-at-point
  17932. (pcase (get-char-property-and-overlay (point) 'invisible)
  17933. (`(,_ . ,(and (pred overlayp) o)) o)))
  17934. ;; Assume that point cannot land in the middle of an
  17935. ;; overlay, or between two overlays.
  17936. (invisible-before-point
  17937. (and (not invisible-at-point)
  17938. (not (bobp))
  17939. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17940. (`(,_ . ,(and (pred overlayp) o)) o))))
  17941. (border-and-ok-direction
  17942. (or
  17943. ;; Check if we are acting predictably before invisible
  17944. ;; text.
  17945. (and invisible-at-point
  17946. (memq kind '(insert delete-backward)))
  17947. ;; Check if we are acting predictably after invisible text
  17948. ;; This works not well, and I have turned it off. It seems
  17949. ;; better to always show and stop after invisible text.
  17950. ;; (and (not invisible-at-point) invisible-before-point
  17951. ;; (memq kind '(insert delete)))
  17952. )))
  17953. (when (or invisible-at-point invisible-before-point)
  17954. (when (eq org-catch-invisible-edits 'error)
  17955. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17956. (if (and org-custom-properties-overlays
  17957. (y-or-n-p "Display invisible properties in this buffer? "))
  17958. (org-toggle-custom-properties-visibility)
  17959. ;; Make the area visible
  17960. (save-excursion
  17961. (when invisible-before-point
  17962. (goto-char
  17963. (previous-single-char-property-change (point) 'invisible)))
  17964. ;; Remove whatever overlay is currently making yet-to-be
  17965. ;; edited text invisible. Also remove nested invisibility
  17966. ;; related overlays.
  17967. (delete-overlay (or invisible-at-point invisible-before-point))
  17968. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17969. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17970. (`(,_ . ,(and (pred overlayp) o))
  17971. (delete-overlay o)
  17972. t)))))
  17973. (cond
  17974. ((eq org-catch-invisible-edits 'show)
  17975. ;; That's it, we do the edit after showing
  17976. (message
  17977. "Unfolding invisible region around point before editing")
  17978. (sit-for 1))
  17979. ((and (eq org-catch-invisible-edits 'smart)
  17980. border-and-ok-direction)
  17981. (message "Unfolding invisible region around point before editing"))
  17982. (t
  17983. ;; Don't do the edit, make the user repeat it in full visibility
  17984. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17985. (defun org-fix-tags-on-the-fly ()
  17986. "Align tags in headline at point.
  17987. Unlike to `org-set-tags', it ignores region and sorting."
  17988. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17989. (org-at-heading-p))
  17990. (let ((org-ignore-region t)
  17991. (org-tags-sort-function nil))
  17992. (org-set-tags nil t))))
  17993. (defun org-delete-backward-char (N)
  17994. "Like `delete-backward-char', insert whitespace at field end in tables.
  17995. When deleting backwards, in tables this function will insert whitespace in
  17996. front of the next \"|\" separator, to keep the table aligned. The table will
  17997. still be marked for re-alignment if the field did fill the entire column,
  17998. because, in this case the deletion might narrow the column."
  17999. (interactive "p")
  18000. (save-match-data
  18001. (org-check-before-invisible-edit 'delete-backward)
  18002. (if (and (org-at-table-p)
  18003. (eq N 1)
  18004. (not (org-region-active-p))
  18005. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18006. (looking-at ".*?|"))
  18007. (let ((pos (point))
  18008. (noalign (looking-at "[^|\n\r]* |"))
  18009. (c org-table-may-need-update))
  18010. (backward-delete-char N)
  18011. (unless overwrite-mode
  18012. (skip-chars-forward "^|")
  18013. (insert " ")
  18014. (goto-char (1- pos)))
  18015. ;; noalign: if there were two spaces at the end, this field
  18016. ;; does not determine the width of the column.
  18017. (when noalign (setq org-table-may-need-update c)))
  18018. (backward-delete-char N)
  18019. (org-fix-tags-on-the-fly))))
  18020. (defun org-delete-char (N)
  18021. "Like `delete-char', but insert whitespace at field end in tables.
  18022. When deleting characters, in tables this function will insert whitespace in
  18023. front of the next \"|\" separator, to keep the table aligned. The table will
  18024. still be marked for re-alignment if the field did fill the entire column,
  18025. because, in this case the deletion might narrow the column."
  18026. (interactive "p")
  18027. (save-match-data
  18028. (org-check-before-invisible-edit 'delete)
  18029. (if (and (org-at-table-p)
  18030. (not (bolp))
  18031. (not (= (char-after) ?|))
  18032. (eq N 1))
  18033. (if (looking-at ".*?|")
  18034. (let ((pos (point))
  18035. (noalign (looking-at "[^|\n\r]* |"))
  18036. (c org-table-may-need-update))
  18037. (replace-match
  18038. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18039. (goto-char pos)
  18040. ;; noalign: if there were two spaces at the end, this field
  18041. ;; does not determine the width of the column.
  18042. (when noalign (setq org-table-may-need-update c)))
  18043. (delete-char N))
  18044. (delete-char N)
  18045. (org-fix-tags-on-the-fly))))
  18046. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18047. (put 'org-self-insert-command 'delete-selection
  18048. (lambda ()
  18049. (not (run-hook-with-args-until-success
  18050. 'self-insert-uses-region-functions))))
  18051. (put 'orgtbl-self-insert-command 'delete-selection
  18052. (lambda ()
  18053. (not (run-hook-with-args-until-success
  18054. 'self-insert-uses-region-functions))))
  18055. (put 'org-delete-char 'delete-selection 'supersede)
  18056. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18057. (put 'org-yank 'delete-selection 'yank)
  18058. ;; Make `flyspell-mode' delay after some commands
  18059. (put 'org-self-insert-command 'flyspell-delayed t)
  18060. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18061. (put 'org-delete-char 'flyspell-delayed t)
  18062. (put 'org-delete-backward-char 'flyspell-delayed t)
  18063. ;; Make pabbrev-mode expand after Org mode commands
  18064. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18065. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18066. (defun org-transpose-words ()
  18067. "Transpose words for Org.
  18068. This uses the `org-mode-transpose-word-syntax-table' syntax
  18069. table, which interprets characters in `org-emphasis-alist' as
  18070. word constituents."
  18071. (interactive)
  18072. (with-syntax-table org-mode-transpose-word-syntax-table
  18073. (call-interactively 'transpose-words)))
  18074. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18075. (defvar org-ctrl-c-ctrl-c-hook nil
  18076. "Hook for functions attaching themselves to `C-c C-c'.
  18077. This can be used to add additional functionality to the C-c C-c
  18078. key which executes context-dependent commands. This hook is run
  18079. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18080. run after the last test.
  18081. Each function will be called with no arguments. The function
  18082. must check if the context is appropriate for it to act. If yes,
  18083. it should do its thing and then return a non-nil value. If the
  18084. context is wrong, just do nothing and return nil.")
  18085. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18086. "Hook for functions attaching themselves to `C-c C-c'.
  18087. This can be used to add additional functionality to the C-c C-c
  18088. key which executes context-dependent commands. This hook is run
  18089. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18090. before the first test.
  18091. Each function will be called with no arguments. The function
  18092. must check if the context is appropriate for it to act. If yes,
  18093. it should do its thing and then return a non-nil value. If the
  18094. context is wrong, just do nothing and return nil.")
  18095. (defvar org-tab-first-hook nil
  18096. "Hook for functions to attach themselves to TAB.
  18097. See `org-ctrl-c-ctrl-c-hook' for more information.
  18098. This hook runs as the first action when TAB is pressed, even before
  18099. `org-cycle' messes around with the `outline-regexp' to cater for
  18100. inline tasks and plain list item folding.
  18101. If any function in this hook returns t, any other actions that
  18102. would have been caused by TAB (such as table field motion or visibility
  18103. cycling) will not occur.")
  18104. (defvar org-tab-after-check-for-table-hook nil
  18105. "Hook for functions to attach themselves to TAB.
  18106. See `org-ctrl-c-ctrl-c-hook' for more information.
  18107. This hook runs after it has been established that the cursor is not in a
  18108. table, but before checking if the cursor is in a headline or if global cycling
  18109. should be done.
  18110. If any function in this hook returns t, not other actions like visibility
  18111. cycling will be done.")
  18112. (defvar org-tab-after-check-for-cycling-hook nil
  18113. "Hook for functions to attach themselves to TAB.
  18114. See `org-ctrl-c-ctrl-c-hook' for more information.
  18115. This hook runs after it has been established that not table field motion and
  18116. not visibility should be done because of current context. This is probably
  18117. the place where a package like yasnippets can hook in.")
  18118. (defvar org-tab-before-tab-emulation-hook nil
  18119. "Hook for functions to attach themselves to TAB.
  18120. See `org-ctrl-c-ctrl-c-hook' for more information.
  18121. This hook runs after every other options for TAB have been exhausted, but
  18122. before indentation and \t insertion takes place.")
  18123. (defvar org-metaleft-hook nil
  18124. "Hook for functions attaching themselves to `M-left'.
  18125. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18126. (defvar org-metaright-hook nil
  18127. "Hook for functions attaching themselves to `M-right'.
  18128. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18129. (defvar org-metaup-hook nil
  18130. "Hook for functions attaching themselves to `M-up'.
  18131. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18132. (defvar org-metadown-hook nil
  18133. "Hook for functions attaching themselves to `M-down'.
  18134. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18135. (defvar org-shiftmetaleft-hook nil
  18136. "Hook for functions attaching themselves to `M-S-left'.
  18137. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18138. (defvar org-shiftmetaright-hook nil
  18139. "Hook for functions attaching themselves to `M-S-right'.
  18140. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18141. (defvar org-shiftmetaup-hook nil
  18142. "Hook for functions attaching themselves to `M-S-up'.
  18143. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18144. (defvar org-shiftmetadown-hook nil
  18145. "Hook for functions attaching themselves to `M-S-down'.
  18146. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18147. (defvar org-metareturn-hook nil
  18148. "Hook for functions attaching themselves to `M-RET'.
  18149. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18150. (defvar org-shiftup-hook nil
  18151. "Hook for functions attaching themselves to `S-up'.
  18152. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18153. (defvar org-shiftup-final-hook nil
  18154. "Hook for functions attaching themselves to `S-up'.
  18155. This one runs after all other options except shift-select have been excluded.
  18156. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18157. (defvar org-shiftdown-hook nil
  18158. "Hook for functions attaching themselves to `S-down'.
  18159. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18160. (defvar org-shiftdown-final-hook nil
  18161. "Hook for functions attaching themselves to `S-down'.
  18162. This one runs after all other options except shift-select have been excluded.
  18163. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18164. (defvar org-shiftleft-hook nil
  18165. "Hook for functions attaching themselves to `S-left'.
  18166. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18167. (defvar org-shiftleft-final-hook nil
  18168. "Hook for functions attaching themselves to `S-left'.
  18169. This one runs after all other options except shift-select have been excluded.
  18170. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18171. (defvar org-shiftright-hook nil
  18172. "Hook for functions attaching themselves to `S-right'.
  18173. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18174. (defvar org-shiftright-final-hook nil
  18175. "Hook for functions attaching themselves to `S-right'.
  18176. This one runs after all other options except shift-select have been excluded.
  18177. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18178. (defun org-modifier-cursor-error ()
  18179. "Throw an error, a modified cursor command was applied in wrong context."
  18180. (user-error "This command is active in special context like tables, headlines or items"))
  18181. (defun org-shiftselect-error ()
  18182. "Throw an error because Shift-Cursor command was applied in wrong context."
  18183. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18184. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18185. (user-error "This command works only in special context like headlines or timestamps")))
  18186. (defun org-call-for-shift-select (cmd)
  18187. (let ((this-command-keys-shift-translated t))
  18188. (call-interactively cmd)))
  18189. (defun org-shifttab (&optional arg)
  18190. "Global visibility cycling or move to previous table field.
  18191. Call `org-table-previous-field' within a table.
  18192. When ARG is nil, cycle globally through visibility states.
  18193. When ARG is a numeric prefix, show contents of this level."
  18194. (interactive "P")
  18195. (cond
  18196. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18197. ((integerp arg)
  18198. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18199. (message "Content view to level: %d" arg)
  18200. (org-content (prefix-numeric-value arg2))
  18201. (org-cycle-show-empty-lines t)
  18202. (setq org-cycle-global-status 'overview)))
  18203. (t (call-interactively 'org-global-cycle))))
  18204. (defun org-shiftmetaleft ()
  18205. "Promote subtree or delete table column.
  18206. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18207. `org-table-delete-column', depending on context. See the
  18208. individual commands for more information."
  18209. (interactive)
  18210. (cond
  18211. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18212. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18213. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18214. ((if (not (org-region-active-p)) (org-at-item-p)
  18215. (save-excursion (goto-char (region-beginning))
  18216. (org-at-item-p)))
  18217. (call-interactively 'org-outdent-item-tree))
  18218. (t (org-modifier-cursor-error))))
  18219. (defun org-shiftmetaright ()
  18220. "Demote subtree or insert table column.
  18221. Calls `org-demote-subtree', `org-indent-item-tree', or
  18222. `org-table-insert-column', depending on context. See the
  18223. individual commands for more information."
  18224. (interactive)
  18225. (cond
  18226. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18227. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18228. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18229. ((if (not (org-region-active-p)) (org-at-item-p)
  18230. (save-excursion (goto-char (region-beginning))
  18231. (org-at-item-p)))
  18232. (call-interactively 'org-indent-item-tree))
  18233. (t (org-modifier-cursor-error))))
  18234. (defun org-shiftmetaup (&optional _arg)
  18235. "Drag the line at point up.
  18236. In a table, kill the current row.
  18237. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18238. but also adjust the previous clocked item in the clock history.
  18239. Everywhere else, drag the line at point up."
  18240. (interactive "P")
  18241. (cond
  18242. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18243. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18244. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18245. (call-interactively 'org-timestamp-up)))
  18246. (t (call-interactively 'org-drag-line-backward))))
  18247. (defun org-shiftmetadown (&optional _arg)
  18248. "Drag the line at point down.
  18249. In a table, insert an empty row at the current line.
  18250. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18251. but also adjust the previous clocked item in the clock history.
  18252. Everywhere else, drag the line at point down."
  18253. (interactive "P")
  18254. (cond
  18255. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18256. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18257. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18258. (call-interactively 'org-timestamp-down)))
  18259. (t (call-interactively 'org-drag-line-forward))))
  18260. (defsubst org-hidden-tree-error ()
  18261. (user-error
  18262. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18263. (defun org-metaleft (&optional _arg)
  18264. "Promote heading, list item at point or move table column left.
  18265. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18266. depending on context. With no specific context, calls the Emacs
  18267. default `backward-word'. See the individual commands for more
  18268. information.
  18269. This function runs the hook `org-metaleft-hook' as a first step,
  18270. and returns at first non-nil value."
  18271. (interactive "P")
  18272. (cond
  18273. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18274. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18275. ((org-with-limited-levels
  18276. (or (org-at-heading-p)
  18277. (and (org-region-active-p)
  18278. (save-excursion
  18279. (goto-char (region-beginning))
  18280. (org-at-heading-p)))))
  18281. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18282. (call-interactively 'org-do-promote))
  18283. ;; At an inline task.
  18284. ((org-at-heading-p)
  18285. (call-interactively 'org-inlinetask-promote))
  18286. ((or (org-at-item-p)
  18287. (and (org-region-active-p)
  18288. (save-excursion
  18289. (goto-char (region-beginning))
  18290. (org-at-item-p))))
  18291. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18292. (call-interactively 'org-outdent-item))
  18293. (t (call-interactively 'backward-word))))
  18294. (defun org-metaright (&optional _arg)
  18295. "Demote heading, list item at point or move table column right.
  18296. In front of a drawer or a block keyword, indent it correctly.
  18297. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18298. `org-indent-drawer' or `org-indent-block' depending on context.
  18299. With no specific context, calls the Emacs default `forward-word'.
  18300. See the individual commands for more information.
  18301. This function runs the hook `org-metaright-hook' as a first step,
  18302. and returns at first non-nil value."
  18303. (interactive "P")
  18304. (cond
  18305. ((run-hook-with-args-until-success 'org-metaright-hook))
  18306. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18307. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18308. ((org-at-block-p) (call-interactively 'org-indent-block))
  18309. ((org-with-limited-levels
  18310. (or (org-at-heading-p)
  18311. (and (org-region-active-p)
  18312. (save-excursion
  18313. (goto-char (region-beginning))
  18314. (org-at-heading-p)))))
  18315. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18316. (call-interactively 'org-do-demote))
  18317. ;; At an inline task.
  18318. ((org-at-heading-p)
  18319. (call-interactively 'org-inlinetask-demote))
  18320. ((or (org-at-item-p)
  18321. (and (org-region-active-p)
  18322. (save-excursion
  18323. (goto-char (region-beginning))
  18324. (org-at-item-p))))
  18325. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18326. (call-interactively 'org-indent-item))
  18327. (t (call-interactively 'forward-word))))
  18328. (defun org-check-for-hidden (what)
  18329. "Check if there are hidden headlines/items in the current visual line.
  18330. WHAT can be either `headlines' or `items'. If the current line is
  18331. an outline or item heading and it has a folded subtree below it,
  18332. this function returns t, nil otherwise."
  18333. (let ((re (cond
  18334. ((eq what 'headlines) org-outline-regexp-bol)
  18335. ((eq what 'items) (org-item-beginning-re))
  18336. (t (error "This should not happen"))))
  18337. beg end)
  18338. (save-excursion
  18339. (catch 'exit
  18340. (unless (org-region-active-p)
  18341. (setq beg (point-at-bol))
  18342. (beginning-of-line 2)
  18343. (while (and (not (eobp)) ;; this is like `next-line'
  18344. (get-char-property (1- (point)) 'invisible))
  18345. (beginning-of-line 2))
  18346. (setq end (point))
  18347. (goto-char beg)
  18348. (goto-char (point-at-eol))
  18349. (setq end (max end (point)))
  18350. (while (re-search-forward re end t)
  18351. (when (get-char-property (match-beginning 0) 'invisible)
  18352. (throw 'exit t))))
  18353. nil))))
  18354. (defun org-metaup (&optional _arg)
  18355. "Move subtree up or move table row up.
  18356. Calls `org-move-subtree-up' or `org-table-move-row' or
  18357. `org-move-item-up', depending on context. See the individual commands
  18358. for more information."
  18359. (interactive "P")
  18360. (cond
  18361. ((run-hook-with-args-until-success 'org-metaup-hook))
  18362. ((org-region-active-p)
  18363. (let* ((a (min (region-beginning) (region-end)))
  18364. (b (1- (max (region-beginning) (region-end))))
  18365. (c (save-excursion (goto-char a)
  18366. (move-beginning-of-line 0)))
  18367. (d (save-excursion (goto-char a)
  18368. (move-end-of-line 0) (point))))
  18369. (transpose-regions a b c d)
  18370. (goto-char c)))
  18371. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18372. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18373. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18374. (t (org-drag-element-backward))))
  18375. (defun org-metadown (&optional _arg)
  18376. "Move subtree down or move table row down.
  18377. Calls `org-move-subtree-down' or `org-table-move-row' or
  18378. `org-move-item-down', depending on context. See the individual
  18379. commands for more information."
  18380. (interactive "P")
  18381. (cond
  18382. ((run-hook-with-args-until-success 'org-metadown-hook))
  18383. ((org-region-active-p)
  18384. (let* ((a (min (region-beginning) (region-end)))
  18385. (b (max (region-beginning) (region-end)))
  18386. (c (save-excursion (goto-char b)
  18387. (move-beginning-of-line 1)))
  18388. (d (save-excursion (goto-char b)
  18389. (move-end-of-line 1) (1+ (point)))))
  18390. (transpose-regions a b c d)
  18391. (goto-char d)))
  18392. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18393. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18394. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18395. (t (org-drag-element-forward))))
  18396. (defun org-shiftup (&optional arg)
  18397. "Increase item in timestamp or increase priority of current headline.
  18398. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18399. depending on context. See the individual commands for more information."
  18400. (interactive "P")
  18401. (cond
  18402. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18403. ((and org-support-shift-select (org-region-active-p))
  18404. (org-call-for-shift-select 'previous-line))
  18405. ((org-at-timestamp-p 'lax)
  18406. (call-interactively (if org-edit-timestamp-down-means-later
  18407. 'org-timestamp-down 'org-timestamp-up)))
  18408. ((and (not (eq org-support-shift-select 'always))
  18409. org-enable-priority-commands
  18410. (org-at-heading-p))
  18411. (call-interactively 'org-priority-up))
  18412. ((and (not org-support-shift-select) (org-at-item-p))
  18413. (call-interactively 'org-previous-item))
  18414. ((org-clocktable-try-shift 'up arg))
  18415. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18416. (org-support-shift-select
  18417. (org-call-for-shift-select 'previous-line))
  18418. (t (org-shiftselect-error))))
  18419. (defun org-shiftdown (&optional arg)
  18420. "Decrease item in timestamp or decrease priority of current headline.
  18421. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18422. depending on context. See the individual commands for more information."
  18423. (interactive "P")
  18424. (cond
  18425. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18426. ((and org-support-shift-select (org-region-active-p))
  18427. (org-call-for-shift-select 'next-line))
  18428. ((org-at-timestamp-p 'lax)
  18429. (call-interactively (if org-edit-timestamp-down-means-later
  18430. 'org-timestamp-up 'org-timestamp-down)))
  18431. ((and (not (eq org-support-shift-select 'always))
  18432. org-enable-priority-commands
  18433. (org-at-heading-p))
  18434. (call-interactively 'org-priority-down))
  18435. ((and (not org-support-shift-select) (org-at-item-p))
  18436. (call-interactively 'org-next-item))
  18437. ((org-clocktable-try-shift 'down arg))
  18438. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18439. (org-support-shift-select
  18440. (org-call-for-shift-select 'next-line))
  18441. (t (org-shiftselect-error))))
  18442. (defun org-shiftright (&optional arg)
  18443. "Cycle the thing at point or in the current line, depending on context.
  18444. Depending on context, this does one of the following:
  18445. - switch a timestamp at point one day into the future
  18446. - on a headline, switch to the next TODO keyword.
  18447. - on an item, switch entire list to the next bullet type
  18448. - on a property line, switch to the next allowed value
  18449. - on a clocktable definition line, move time block into the future"
  18450. (interactive "P")
  18451. (cond
  18452. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18453. ((and org-support-shift-select (org-region-active-p))
  18454. (org-call-for-shift-select 'forward-char))
  18455. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18456. ((and (not (eq org-support-shift-select 'always))
  18457. (org-at-heading-p))
  18458. (let ((org-inhibit-logging
  18459. (not org-treat-S-cursor-todo-selection-as-state-change))
  18460. (org-inhibit-blocking
  18461. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18462. (org-call-with-arg 'org-todo 'right)))
  18463. ((or (and org-support-shift-select
  18464. (not (eq org-support-shift-select 'always))
  18465. (org-at-item-bullet-p))
  18466. (and (not org-support-shift-select) (org-at-item-p)))
  18467. (org-call-with-arg 'org-cycle-list-bullet nil))
  18468. ((and (not (eq org-support-shift-select 'always))
  18469. (org-at-property-p))
  18470. (call-interactively 'org-property-next-allowed-value))
  18471. ((org-clocktable-try-shift 'right arg))
  18472. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18473. (org-support-shift-select
  18474. (org-call-for-shift-select 'forward-char))
  18475. (t (org-shiftselect-error))))
  18476. (defun org-shiftleft (&optional arg)
  18477. "Cycle the thing at point or in the current line, depending on context.
  18478. Depending on context, this does one of the following:
  18479. - switch a timestamp at point one day into the past
  18480. - on a headline, switch to the previous TODO keyword.
  18481. - on an item, switch entire list to the previous bullet type
  18482. - on a property line, switch to the previous allowed value
  18483. - on a clocktable definition line, move time block into the past"
  18484. (interactive "P")
  18485. (cond
  18486. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18487. ((and org-support-shift-select (org-region-active-p))
  18488. (org-call-for-shift-select 'backward-char))
  18489. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18490. ((and (not (eq org-support-shift-select 'always))
  18491. (org-at-heading-p))
  18492. (let ((org-inhibit-logging
  18493. (not org-treat-S-cursor-todo-selection-as-state-change))
  18494. (org-inhibit-blocking
  18495. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18496. (org-call-with-arg 'org-todo 'left)))
  18497. ((or (and org-support-shift-select
  18498. (not (eq org-support-shift-select 'always))
  18499. (org-at-item-bullet-p))
  18500. (and (not org-support-shift-select) (org-at-item-p)))
  18501. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18502. ((and (not (eq org-support-shift-select 'always))
  18503. (org-at-property-p))
  18504. (call-interactively 'org-property-previous-allowed-value))
  18505. ((org-clocktable-try-shift 'left arg))
  18506. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18507. (org-support-shift-select
  18508. (org-call-for-shift-select 'backward-char))
  18509. (t (org-shiftselect-error))))
  18510. (defun org-shiftcontrolright ()
  18511. "Switch to next TODO set."
  18512. (interactive)
  18513. (cond
  18514. ((and org-support-shift-select (org-region-active-p))
  18515. (org-call-for-shift-select 'forward-word))
  18516. ((and (not (eq org-support-shift-select 'always))
  18517. (org-at-heading-p))
  18518. (org-call-with-arg 'org-todo 'nextset))
  18519. (org-support-shift-select
  18520. (org-call-for-shift-select 'forward-word))
  18521. (t (org-shiftselect-error))))
  18522. (defun org-shiftcontrolleft ()
  18523. "Switch to previous TODO set."
  18524. (interactive)
  18525. (cond
  18526. ((and org-support-shift-select (org-region-active-p))
  18527. (org-call-for-shift-select 'backward-word))
  18528. ((and (not (eq org-support-shift-select 'always))
  18529. (org-at-heading-p))
  18530. (org-call-with-arg 'org-todo 'previousset))
  18531. (org-support-shift-select
  18532. (org-call-for-shift-select 'backward-word))
  18533. (t (org-shiftselect-error))))
  18534. (defun org-shiftcontrolup (&optional n)
  18535. "Change timestamps synchronously up in CLOCK log lines.
  18536. Optional argument N tells to change by that many units."
  18537. (interactive "P")
  18538. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18539. (let (org-support-shift-select)
  18540. (org-clock-timestamps-up n))
  18541. (user-error "Not at a clock log")))
  18542. (defun org-shiftcontroldown (&optional n)
  18543. "Change timestamps synchronously down in CLOCK log lines.
  18544. Optional argument N tells to change by that many units."
  18545. (interactive "P")
  18546. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18547. (let (org-support-shift-select)
  18548. (org-clock-timestamps-down n))
  18549. (user-error "Not at a clock log")))
  18550. (defun org-increase-number-at-point (&optional inc)
  18551. "Increment the number at point.
  18552. With an optional prefix numeric argument INC, increment using
  18553. this numeric value."
  18554. (interactive "p")
  18555. (if (not (number-at-point))
  18556. (user-error "Not on a number")
  18557. (unless inc (setq inc 1))
  18558. (let ((pos (point))
  18559. (beg (skip-chars-backward "-+^/*0-9eE."))
  18560. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18561. (setq nap (buffer-substring-no-properties
  18562. (+ pos beg) (+ pos beg end)))
  18563. (delete-region (+ pos beg) (+ pos beg end))
  18564. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18565. (when (org-at-table-p)
  18566. (org-table-align)
  18567. (org-table-end-of-field 1))))
  18568. (defun org-decrease-number-at-point (&optional inc)
  18569. "Decrement the number at point.
  18570. With an optional prefix numeric argument INC, decrement using
  18571. this numeric value."
  18572. (interactive "p")
  18573. (org-increase-number-at-point (- (or inc 1))))
  18574. (defun org-ctrl-c-ret ()
  18575. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18576. (interactive)
  18577. (cond
  18578. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18579. (t (call-interactively 'org-insert-heading))))
  18580. (defun org-find-visible ()
  18581. (let ((s (point)))
  18582. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18583. (get-char-property s 'invisible)))
  18584. s))
  18585. (defun org-find-invisible ()
  18586. (let ((s (point)))
  18587. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18588. (not (get-char-property s 'invisible))))
  18589. s))
  18590. (defun org-copy-visible (beg end)
  18591. "Copy the visible parts of the region."
  18592. (interactive "r")
  18593. (let ((result ""))
  18594. (while (/= beg end)
  18595. (when (get-char-property beg 'invisible)
  18596. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18597. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18598. (setq result (concat result (buffer-substring beg next)))
  18599. (setq beg next)))
  18600. (kill-new result)))
  18601. (defun org-copy-special ()
  18602. "Copy region in table or copy current subtree.
  18603. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18604. context. See the individual commands for more information."
  18605. (interactive)
  18606. (call-interactively
  18607. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18608. (defun org-cut-special ()
  18609. "Cut region in table or cut current subtree.
  18610. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18611. context. See the individual commands for more information."
  18612. (interactive)
  18613. (call-interactively
  18614. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18615. (defun org-paste-special (arg)
  18616. "Paste rectangular region into table, or past subtree relative to level.
  18617. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18618. See the individual commands for more information."
  18619. (interactive "P")
  18620. (if (org-at-table-p)
  18621. (org-table-paste-rectangle)
  18622. (org-paste-subtree arg)))
  18623. (defun org-edit-special (&optional arg)
  18624. "Call a special editor for the element at point.
  18625. When at a table, call the formula editor with `org-table-edit-formulas'.
  18626. When in a source code block, call `org-edit-src-code'.
  18627. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18628. When in an export block, call `org-edit-export-block'.
  18629. When in a LaTeX environment, call `org-edit-latex-environment'.
  18630. When at an #+INCLUDE keyword, visit the included file.
  18631. When at a footnote reference, call `org-edit-footnote-reference'
  18632. On a link, call `ffap' to visit the link at point.
  18633. Otherwise, return a user error."
  18634. (interactive "P")
  18635. (let ((element (org-element-at-point)))
  18636. (barf-if-buffer-read-only)
  18637. (pcase (org-element-type element)
  18638. (`src-block
  18639. (if (not arg) (org-edit-src-code)
  18640. (let* ((info (org-babel-get-src-block-info))
  18641. (lang (nth 0 info))
  18642. (params (nth 2 info))
  18643. (session (cdr (assq :session params))))
  18644. (if (not session) (org-edit-src-code)
  18645. ;; At a src-block with a session and function called with
  18646. ;; an ARG: switch to the buffer related to the inferior
  18647. ;; process.
  18648. (switch-to-buffer
  18649. (funcall (intern (concat "org-babel-prep-session:" lang))
  18650. session params))))))
  18651. (`keyword
  18652. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18653. (org-open-link-from-string
  18654. (format "[[%s]]"
  18655. (expand-file-name
  18656. (let ((value (org-element-property :value element)))
  18657. (cond ((org-file-url-p value)
  18658. (user-error "The file is specified as a URL, cannot be edited"))
  18659. ((not (org-string-nw-p value))
  18660. (user-error "No file to edit"))
  18661. ((string-match "\\`\"\\(.*?\\)\"" value)
  18662. (match-string 1 value))
  18663. ((string-match "\\`[^ \t\"]\\S-*" value)
  18664. (match-string 0 value))
  18665. (t (user-error "No valid file specified")))))))
  18666. (user-error "No special environment to edit here")))
  18667. (`table
  18668. (if (eq (org-element-property :type element) 'table.el)
  18669. (org-edit-table.el)
  18670. (call-interactively 'org-table-edit-formulas)))
  18671. ;; Only Org tables contain `table-row' type elements.
  18672. (`table-row (call-interactively 'org-table-edit-formulas))
  18673. (`example-block (org-edit-src-code))
  18674. (`export-block (org-edit-export-block))
  18675. (`fixed-width (org-edit-fixed-width-region))
  18676. (`latex-environment (org-edit-latex-environment))
  18677. (_
  18678. ;; No notable element at point. Though, we may be at a link or
  18679. ;; a footnote reference, which are objects. Thus, scan deeper.
  18680. (let ((context (org-element-context element)))
  18681. (pcase (org-element-type context)
  18682. (`footnote-reference (org-edit-footnote-reference))
  18683. (`inline-src-block (org-edit-inline-src-code))
  18684. (`link (call-interactively #'ffap))
  18685. (_ (user-error "No special environment to edit here"))))))))
  18686. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18687. (defun org-ctrl-c-ctrl-c (&optional arg)
  18688. "Set tags in headline, or update according to changed information at point.
  18689. This command does many different things, depending on context:
  18690. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18691. this is what we do.
  18692. - If the cursor is on a statistics cookie, update it.
  18693. - If the cursor is in a headline, prompt for tags and insert them
  18694. into the current line, aligned to `org-tags-column'. When called
  18695. with prefix arg, realign all tags in the current buffer.
  18696. - If the cursor is in one of the special #+KEYWORD lines, this
  18697. triggers scanning the buffer for these lines and updating the
  18698. information.
  18699. - If the cursor is inside a table, realign the table. This command
  18700. works even if the automatic table editor has been turned off.
  18701. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18702. the entire table.
  18703. - If the cursor is at a footnote reference or definition, jump to
  18704. the corresponding definition or references, respectively.
  18705. - If the cursor is a the beginning of a dynamic block, update it.
  18706. - If the current buffer is a capture buffer, close note and file it.
  18707. - If the cursor is on a <<<target>>>, update radio targets and
  18708. corresponding links in this buffer.
  18709. - If the cursor is on a numbered item in a plain list, renumber the
  18710. ordered list.
  18711. - If the cursor is on a checkbox, toggle it.
  18712. - If the cursor is on a code block, evaluate it. The variable
  18713. `org-confirm-babel-evaluate' can be used to control prompting
  18714. before code block evaluation, by default every code block
  18715. evaluation requires confirmation. Code block evaluation can be
  18716. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18717. (interactive "P")
  18718. (cond
  18719. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18720. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18721. (org-remove-occur-highlights)
  18722. (message "Temporary highlights/overlays removed from current buffer"))
  18723. ((and (local-variable-p 'org-finish-function)
  18724. (fboundp org-finish-function))
  18725. (funcall org-finish-function))
  18726. ((org-babel-hash-at-point))
  18727. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18728. (t
  18729. (let* ((context
  18730. (org-element-lineage
  18731. (org-element-context)
  18732. ;; Limit to supported contexts.
  18733. '(babel-call clock dynamic-block footnote-definition
  18734. footnote-reference inline-babel-call inline-src-block
  18735. inlinetask item keyword node-property paragraph
  18736. plain-list planning property-drawer radio-target
  18737. src-block statistics-cookie table table-cell table-row
  18738. timestamp)
  18739. t))
  18740. (type (org-element-type context)))
  18741. ;; For convenience: at the first line of a paragraph on the same
  18742. ;; line as an item, apply function on that item instead.
  18743. (when (eq type 'paragraph)
  18744. (let ((parent (org-element-property :parent context)))
  18745. (when (and (eq (org-element-type parent) 'item)
  18746. (= (line-beginning-position)
  18747. (org-element-property :begin parent)))
  18748. (setq context parent)
  18749. (setq type 'item))))
  18750. ;; Act according to type of element or object at point.
  18751. ;;
  18752. ;; Do nothing on a blank line, except if it is contained in
  18753. ;; a src block. Hence, we first check if point is in such
  18754. ;; a block and then if it is at a blank line.
  18755. (pcase type
  18756. ((or `inline-src-block `src-block)
  18757. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18758. (org-babel-eval-wipe-error-buffer)
  18759. (org-babel-execute-src-block
  18760. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18761. ((guard (org-match-line "[ \t]*$"))
  18762. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18763. (user-error
  18764. (substitute-command-keys
  18765. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18766. ((or `babel-call `inline-babel-call)
  18767. (let ((info (org-babel-lob-get-info context)))
  18768. (when info (org-babel-execute-src-block nil info))))
  18769. (`clock (org-clock-update-time-maybe))
  18770. (`dynamic-block
  18771. (save-excursion
  18772. (goto-char (org-element-property :post-affiliated context))
  18773. (org-update-dblock)))
  18774. (`footnote-definition
  18775. (goto-char (org-element-property :post-affiliated context))
  18776. (call-interactively 'org-footnote-action))
  18777. (`footnote-reference (call-interactively #'org-footnote-action))
  18778. ((or `headline `inlinetask)
  18779. (save-excursion (goto-char (org-element-property :begin context))
  18780. (call-interactively #'org-set-tags)))
  18781. (`item
  18782. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18783. ;; unconditionally, whereas `C-u' will toggle its presence.
  18784. ;; Without a universal argument, if the item has a checkbox,
  18785. ;; toggle it. Otherwise repair the list.
  18786. (let* ((box (org-element-property :checkbox context))
  18787. (struct (org-element-property :structure context))
  18788. (old-struct (copy-tree struct))
  18789. (parents (org-list-parents-alist struct))
  18790. (prevs (org-list-prevs-alist struct))
  18791. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18792. (org-list-set-checkbox
  18793. (org-element-property :begin context) struct
  18794. (cond ((equal arg '(16)) "[-]")
  18795. ((and (not box) (equal arg '(4))) "[ ]")
  18796. ((or (not box) (equal arg '(4))) nil)
  18797. ((eq box 'on) "[ ]")
  18798. (t "[X]")))
  18799. ;; Mimic `org-list-write-struct' but with grabbing a return
  18800. ;; value from `org-list-struct-fix-box'.
  18801. (org-list-struct-fix-ind struct parents 2)
  18802. (org-list-struct-fix-item-end struct)
  18803. (org-list-struct-fix-bul struct prevs)
  18804. (org-list-struct-fix-ind struct parents)
  18805. (let ((block-item
  18806. (org-list-struct-fix-box struct parents prevs orderedp)))
  18807. (if (and box (equal struct old-struct))
  18808. (if (equal arg '(16))
  18809. (message "Checkboxes already reset")
  18810. (user-error "Cannot toggle this checkbox: %s"
  18811. (if (eq box 'on)
  18812. "all subitems checked"
  18813. "unchecked subitems")))
  18814. (org-list-struct-apply-struct struct old-struct)
  18815. (org-update-checkbox-count-maybe))
  18816. (when block-item
  18817. (message "Checkboxes were removed due to empty box at line %d"
  18818. (org-current-line block-item))))))
  18819. (`keyword
  18820. (let ((org-inhibit-startup-visibility-stuff t)
  18821. (org-startup-align-all-tables nil))
  18822. (when (boundp 'org-table-coordinate-overlays)
  18823. (mapc #'delete-overlay org-table-coordinate-overlays)
  18824. (setq org-table-coordinate-overlays nil))
  18825. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18826. (message "Local setup has been refreshed"))
  18827. (`plain-list
  18828. ;; At a plain list, with a double C-u argument, set
  18829. ;; checkboxes of each item to "[-]", whereas a single one
  18830. ;; will toggle their presence according to the state of the
  18831. ;; first item in the list. Without an argument, repair the
  18832. ;; list.
  18833. (let* ((begin (org-element-property :contents-begin context))
  18834. (beginm (move-marker (make-marker) begin))
  18835. (struct (org-element-property :structure context))
  18836. (old-struct (copy-tree struct))
  18837. (first-box (save-excursion
  18838. (goto-char begin)
  18839. (looking-at org-list-full-item-re)
  18840. (match-string-no-properties 3)))
  18841. (new-box (cond ((equal arg '(16)) "[-]")
  18842. ((equal arg '(4)) (unless first-box "[ ]"))
  18843. ((equal first-box "[X]") "[ ]")
  18844. (t "[X]"))))
  18845. (cond
  18846. (arg
  18847. (dolist (pos
  18848. (org-list-get-all-items
  18849. begin struct (org-list-prevs-alist struct)))
  18850. (org-list-set-checkbox pos struct new-box)))
  18851. ((and first-box (eq (point) begin))
  18852. ;; For convenience, when point is at bol on the first
  18853. ;; item of the list and no argument is provided, simply
  18854. ;; toggle checkbox of that item, if any.
  18855. (org-list-set-checkbox begin struct new-box)))
  18856. (org-list-write-struct
  18857. struct (org-list-parents-alist struct) old-struct)
  18858. (org-update-checkbox-count-maybe)
  18859. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  18860. ((or `property-drawer `node-property)
  18861. (call-interactively #'org-property-action))
  18862. (`radio-target
  18863. (call-interactively #'org-update-radio-target-regexp))
  18864. (`statistics-cookie
  18865. (call-interactively #'org-update-statistics-cookies))
  18866. ((or `table `table-cell `table-row)
  18867. ;; At a table, recalculate every field and align it. Also
  18868. ;; send the table if necessary. If the table has
  18869. ;; a `table.el' type, just give up. At a table row or cell,
  18870. ;; maybe recalculate line but always align table.
  18871. (if (eq (org-element-property :type context) 'table.el)
  18872. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18873. Use `\\[org-edit-special]' to edit table.el tables"))
  18874. (if (or (eq type 'table)
  18875. ;; Check if point is at a TBLFM line.
  18876. (and (eq type 'table-row)
  18877. (= (point) (org-element-property :end context))))
  18878. (save-excursion
  18879. (if (org-at-TBLFM-p)
  18880. (progn (require 'org-table)
  18881. (org-table-calc-current-TBLFM))
  18882. (goto-char (org-element-property :contents-begin context))
  18883. (org-call-with-arg 'org-table-recalculate (or arg t))
  18884. (orgtbl-send-table 'maybe)))
  18885. (org-table-maybe-eval-formula)
  18886. (cond (arg (call-interactively #'org-table-recalculate))
  18887. ((org-table-maybe-recalculate-line))
  18888. (t (org-table-align))))))
  18889. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18890. (org-timestamp-change 0 'day))
  18891. ((and `nil (guard (org-at-heading-p)))
  18892. ;; When point is on an unsupported object type, we can miss
  18893. ;; the fact that it also is at a heading. Handle it here.
  18894. (call-interactively #'org-set-tags))
  18895. ((guard
  18896. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18897. (_
  18898. (user-error
  18899. (substitute-command-keys
  18900. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18901. (defun org-mode-restart ()
  18902. (interactive)
  18903. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18904. (funcall major-mode)
  18905. (hack-local-variables)
  18906. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18907. (org-indent-mode -1))
  18908. (org-reset-file-cache))
  18909. (message "%s restarted" major-mode))
  18910. (defun org-kill-note-or-show-branches ()
  18911. "Abort storing current note, or call `outline-show-branches'."
  18912. (interactive)
  18913. (if (not org-finish-function)
  18914. (progn
  18915. (outline-hide-subtree)
  18916. (call-interactively 'outline-show-branches))
  18917. (let ((org-note-abort t))
  18918. (funcall org-finish-function))))
  18919. (defun org-delete-indentation (&optional arg)
  18920. "Join current line to previous and fix whitespace at join.
  18921. If previous line is a headline add to headline title. Otherwise
  18922. the function calls `delete-indentation'.
  18923. With a non-nil optional argument, join it to the following one."
  18924. (interactive "*P")
  18925. (if (save-excursion
  18926. (beginning-of-line (if arg 1 0))
  18927. (let ((case-fold-search nil))
  18928. (looking-at org-complex-heading-regexp)))
  18929. ;; At headline.
  18930. (let ((tags-column (when (match-beginning 5)
  18931. (save-excursion (goto-char (match-beginning 5))
  18932. (current-column))))
  18933. (string (concat " " (progn (when arg (forward-line 1))
  18934. (org-trim (delete-and-extract-region
  18935. (line-beginning-position)
  18936. (line-end-position)))))))
  18937. (unless (bobp) (delete-region (point) (1- (point))))
  18938. (goto-char (or (match-end 4)
  18939. (match-beginning 5)
  18940. (match-end 0)))
  18941. (skip-chars-backward " \t")
  18942. (save-excursion (insert string))
  18943. ;; Adjust alignment of tags.
  18944. (cond
  18945. ((not tags-column)) ;no tags
  18946. (org-auto-align-tags (org-set-tags nil t))
  18947. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18948. (delete-indentation arg)))
  18949. (defun org-open-line (n)
  18950. "Insert a new row in tables, call `open-line' elsewhere.
  18951. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18952. As a special case, when a document starts with a table, allow to
  18953. call `open-line' on the very first character."
  18954. (interactive "*p")
  18955. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18956. (org-table-insert-row)
  18957. (open-line n)))
  18958. (defun org-return (&optional indent)
  18959. "Goto next table row or insert a newline.
  18960. Calls `org-table-next-row' or `newline', depending on context.
  18961. When optional INDENT argument is non-nil, call
  18962. `newline-and-indent' instead of `newline'.
  18963. When `org-return-follows-link' is non-nil and point is on
  18964. a timestamp or a link, call `org-open-at-point'. However, it
  18965. will not happen if point is in a table or on a \"dead\"
  18966. object (e.g., within a comment). In these case, you need to use
  18967. `org-open-at-point' directly."
  18968. (interactive)
  18969. (let ((context (if org-return-follows-link (org-element-context)
  18970. (org-element-at-point))))
  18971. (cond
  18972. ;; In a table, call `org-table-next-row'. However, before first
  18973. ;; column or after last one, split the table.
  18974. ((or (and (eq (org-element-type context) 'table)
  18975. (>= (point) (org-element-property :contents-begin context))
  18976. (< (point) (org-element-property :contents-end context)))
  18977. (org-element-lineage context '(table-row table-cell) t))
  18978. (if (or (looking-at-p "[ \t]*$")
  18979. (save-excursion (skip-chars-backward " \t") (bolp)))
  18980. (insert "\n")
  18981. (org-table-justify-field-maybe)
  18982. (call-interactively #'org-table-next-row)))
  18983. ;; On a link or a timestamp, call `org-open-at-point' if
  18984. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18985. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18986. ((and org-return-follows-link
  18987. (or (org-in-regexp org-ts-regexp-both nil t)
  18988. (org-in-regexp org-tsr-regexp-both nil t)
  18989. (org-in-regexp org-any-link-re nil t)))
  18990. (call-interactively #'org-open-at-point))
  18991. ;; Insert newline in heading, but preserve tags.
  18992. ((and (not (bolp))
  18993. (save-excursion (beginning-of-line)
  18994. (let ((case-fold-search nil))
  18995. (looking-at org-complex-heading-regexp))))
  18996. ;; At headline. Split line. However, if point is on keyword,
  18997. ;; priority cookie or tags, do not break any of them: add
  18998. ;; a newline after the headline instead.
  18999. (let ((tags-column (and (match-beginning 5)
  19000. (save-excursion (goto-char (match-beginning 5))
  19001. (current-column))))
  19002. (string
  19003. (when (and (match-end 4) (org-point-in-group (point) 4))
  19004. (delete-and-extract-region (point) (match-end 4)))))
  19005. ;; Adjust tag alignment.
  19006. (cond
  19007. ((not (and tags-column string)))
  19008. (org-auto-align-tags (org-set-tags nil t))
  19009. (t (org--align-tags-here tags-column))) ;preserve tags column
  19010. (end-of-line)
  19011. (org-show-entry)
  19012. (if indent (newline-and-indent) (newline))
  19013. (when string (save-excursion (insert (org-trim string))))))
  19014. ;; In a list, make sure indenting keeps trailing text within.
  19015. ((and indent
  19016. (not (eolp))
  19017. (org-element-lineage context '(item)))
  19018. (let ((trailing-data
  19019. (delete-and-extract-region (point) (line-end-position))))
  19020. (newline-and-indent)
  19021. (save-excursion (insert trailing-data))))
  19022. (t (if indent (newline-and-indent) (newline))))))
  19023. (defun org-return-indent ()
  19024. "Goto next table row or insert a newline and indent.
  19025. Calls `org-table-next-row' or `newline-and-indent', depending on
  19026. context. See the individual commands for more information."
  19027. (interactive)
  19028. (org-return t))
  19029. (defun org-ctrl-c-tab (&optional _arg)
  19030. "Toggle columns width in a table, or show children.
  19031. Call `org-table-toggle-column-width' if point is in a table.
  19032. Otherwise, call `org-show-children'."
  19033. (interactive "p")
  19034. (call-interactively
  19035. (if (org-at-table-p) #'org-table-toggle-column-width
  19036. #'org-show-children)))
  19037. (defun org-ctrl-c-star ()
  19038. "Compute table, or change heading status of lines.
  19039. Calls `org-table-recalculate' or `org-toggle-heading',
  19040. depending on context."
  19041. (interactive)
  19042. (cond
  19043. ((org-at-table-p)
  19044. (call-interactively 'org-table-recalculate))
  19045. (t
  19046. ;; Convert all lines in region to list items
  19047. (call-interactively 'org-toggle-heading))))
  19048. (defun org-ctrl-c-minus ()
  19049. "Insert separator line in table or modify bullet status of line.
  19050. Also turns a plain line or a region of lines into list items.
  19051. Calls `org-table-insert-hline', `org-toggle-item', or
  19052. `org-cycle-list-bullet', depending on context."
  19053. (interactive)
  19054. (cond
  19055. ((org-at-table-p)
  19056. (call-interactively 'org-table-insert-hline))
  19057. ((org-region-active-p)
  19058. (call-interactively 'org-toggle-item))
  19059. ((org-in-item-p)
  19060. (call-interactively 'org-cycle-list-bullet))
  19061. (t
  19062. (call-interactively 'org-toggle-item))))
  19063. (defun org-toggle-heading (&optional nstars)
  19064. "Convert headings to normal text, or items or text to headings.
  19065. If there is no active region, only convert the current line.
  19066. With a `\\[universal-argument]' prefix, convert the whole list at
  19067. point into heading.
  19068. In a region:
  19069. - If the first non blank line is a headline, remove the stars
  19070. from all headlines in the region.
  19071. - If it is a normal line, turn each and every normal line (i.e.,
  19072. not an heading or an item) in the region into headings. If you
  19073. want to convert only the first line of this region, use one
  19074. universal prefix argument.
  19075. - If it is a plain list item, turn all plain list items into headings.
  19076. When converting a line into a heading, the number of stars is chosen
  19077. such that the lines become children of the current entry. However,
  19078. when a numeric prefix argument is given, its value determines the
  19079. number of stars to add."
  19080. (interactive "P")
  19081. (let ((skip-blanks
  19082. (function
  19083. ;; Return beginning of first non-blank line, starting from
  19084. ;; line at POS.
  19085. (lambda (pos)
  19086. (save-excursion
  19087. (goto-char pos)
  19088. (while (org-at-comment-p) (forward-line))
  19089. (skip-chars-forward " \r\t\n")
  19090. (point-at-bol)))))
  19091. beg end toggled)
  19092. ;; Determine boundaries of changes. If a universal prefix has
  19093. ;; been given, put the list in a region. If region ends at a bol,
  19094. ;; do not consider the last line to be in the region.
  19095. (when (and current-prefix-arg (org-at-item-p))
  19096. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19097. (org-mark-element))
  19098. (if (org-region-active-p)
  19099. (setq beg (funcall skip-blanks (region-beginning))
  19100. end (copy-marker (save-excursion
  19101. (goto-char (region-end))
  19102. (if (bolp) (point) (point-at-eol)))))
  19103. (setq beg (funcall skip-blanks (point-at-bol))
  19104. end (copy-marker (point-at-eol))))
  19105. ;; Ensure inline tasks don't count as headings.
  19106. (org-with-limited-levels
  19107. (save-excursion
  19108. (goto-char beg)
  19109. (cond
  19110. ;; Case 1. Started at an heading: de-star headings.
  19111. ((org-at-heading-p)
  19112. (while (< (point) end)
  19113. (when (org-at-heading-p t)
  19114. (looking-at org-outline-regexp) (replace-match "")
  19115. (setq toggled t))
  19116. (forward-line)))
  19117. ;; Case 2. Started at an item: change items into headlines.
  19118. ;; One star will be added by `org-list-to-subtree'.
  19119. ((org-at-item-p)
  19120. (while (< (point) end)
  19121. (when (org-at-item-p)
  19122. ;; Pay attention to cases when region ends before list.
  19123. (let* ((struct (org-list-struct))
  19124. (list-end
  19125. (min (org-list-get-bottom-point struct) (1+ end))))
  19126. (save-restriction
  19127. (narrow-to-region (point) list-end)
  19128. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19129. (setq toggled t))
  19130. (forward-line)))
  19131. ;; Case 3. Started at normal text: make every line an heading,
  19132. ;; skipping headlines and items.
  19133. (t (let* ((stars
  19134. (make-string
  19135. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19136. (add-stars
  19137. (cond (nstars "") ; stars from prefix only
  19138. ((equal stars "") "*") ; before first heading
  19139. (org-odd-levels-only "**") ; inside heading, odd
  19140. (t "*"))) ; inside heading, oddeven
  19141. (rpl (concat stars add-stars " "))
  19142. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19143. (while (< (point) (if (equal nstars '(4)) lend end))
  19144. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19145. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19146. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19147. (forward-line)))))))
  19148. (unless toggled (message "Cannot toggle heading from here"))))
  19149. (defun org-meta-return (&optional arg)
  19150. "Insert a new heading or wrap a region in a table.
  19151. Calls `org-insert-heading', `org-insert-item' or
  19152. `org-table-wrap-region', depending on context. When called with
  19153. an argument, unconditionally call `org-insert-heading'."
  19154. (interactive "P")
  19155. (org-check-before-invisible-edit 'insert)
  19156. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19157. (call-interactively (cond (arg #'org-insert-heading)
  19158. ((org-at-table-p) #'org-table-wrap-region)
  19159. ((org-in-item-p) #'org-insert-item)
  19160. (t #'org-insert-heading)))))
  19161. ;;; Menu entries
  19162. (defsubst org-in-subtree-not-table-p ()
  19163. "Are we in a subtree and not in a table?"
  19164. (and (not (org-before-first-heading-p))
  19165. (not (org-at-table-p))))
  19166. ;; Define the Org mode menus
  19167. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19168. '("Tbl"
  19169. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19170. ["Next Field" org-cycle (org-at-table-p)]
  19171. ["Previous Field" org-shifttab (org-at-table-p)]
  19172. ["Next Row" org-return (org-at-table-p)]
  19173. "--"
  19174. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19175. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19176. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19177. "--"
  19178. ("Column"
  19179. ["Move Column Left" org-metaleft (org-at-table-p)]
  19180. ["Move Column Right" org-metaright (org-at-table-p)]
  19181. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19182. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  19183. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  19184. ("Row"
  19185. ["Move Row Up" org-metaup (org-at-table-p)]
  19186. ["Move Row Down" org-metadown (org-at-table-p)]
  19187. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19188. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19189. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19190. "--"
  19191. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19192. ("Rectangle"
  19193. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19194. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19195. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19196. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19197. "--"
  19198. ("Calculate"
  19199. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19200. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19201. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19202. "--"
  19203. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19204. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19205. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19206. "--"
  19207. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19208. "--"
  19209. ["Sum Column/Rectangle" org-table-sum
  19210. (or (org-at-table-p) (org-region-active-p))]
  19211. ["Which Column?" org-table-current-column (org-at-table-p)])
  19212. ["Debug Formulas"
  19213. org-table-toggle-formula-debugger
  19214. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19215. ["Show Col/Row Numbers"
  19216. org-table-toggle-coordinate-overlays
  19217. :style toggle
  19218. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19219. "--"
  19220. ["Create" org-table-create (not (org-at-table-p))]
  19221. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19222. ["Import from File" org-table-import (not (org-at-table-p))]
  19223. ["Export to File" org-table-export (org-at-table-p)]
  19224. "--"
  19225. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19226. "--"
  19227. ("Plot"
  19228. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19229. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19230. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19231. '("Org"
  19232. ("Show/Hide"
  19233. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19234. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19235. ["Sparse Tree..." org-sparse-tree t]
  19236. ["Reveal Context" org-reveal t]
  19237. ["Show All" outline-show-all t]
  19238. "--"
  19239. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19240. "--"
  19241. ["New Heading" org-insert-heading t]
  19242. ("Navigate Headings"
  19243. ["Up" outline-up-heading t]
  19244. ["Next" outline-next-visible-heading t]
  19245. ["Previous" outline-previous-visible-heading t]
  19246. ["Next Same Level" outline-forward-same-level t]
  19247. ["Previous Same Level" outline-backward-same-level t]
  19248. "--"
  19249. ["Jump" org-goto t])
  19250. ("Edit Structure"
  19251. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19252. "--"
  19253. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19254. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19255. "--"
  19256. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19257. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19258. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19259. "--"
  19260. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19261. "--"
  19262. ["Copy visible text" org-copy-visible t]
  19263. "--"
  19264. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19265. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19266. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19267. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19268. "--"
  19269. ["Sort Region/Children" org-sort t]
  19270. "--"
  19271. ["Convert to odd levels" org-convert-to-odd-levels t]
  19272. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19273. ("Editing"
  19274. ["Emphasis..." org-emphasize t]
  19275. ["Edit Source Example" org-edit-special t]
  19276. "--"
  19277. ["Footnote new/jump" org-footnote-action t]
  19278. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19279. ("Archive"
  19280. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19281. "--"
  19282. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19283. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19284. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19285. )
  19286. "--"
  19287. ("Hyperlinks"
  19288. ["Store Link (Global)" org-store-link t]
  19289. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19290. ["Insert Link" org-insert-link t]
  19291. ["Follow Link" org-open-at-point t]
  19292. "--"
  19293. ["Next link" org-next-link t]
  19294. ["Previous link" org-previous-link t]
  19295. "--"
  19296. ["Descriptive Links"
  19297. org-toggle-link-display
  19298. :style radio
  19299. :selected org-descriptive-links
  19300. ]
  19301. ["Literal Links"
  19302. org-toggle-link-display
  19303. :style radio
  19304. :selected (not org-descriptive-links)])
  19305. "--"
  19306. ("TODO Lists"
  19307. ["TODO/DONE/-" org-todo t]
  19308. ("Select keyword"
  19309. ["Next keyword" org-shiftright (org-at-heading-p)]
  19310. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19311. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19312. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19313. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19314. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19315. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19316. "--"
  19317. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19318. :selected org-enforce-todo-dependencies :style toggle :active t]
  19319. "Settings for tree at point"
  19320. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19321. :selected (org-entry-get nil "ORDERED")
  19322. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19323. ["Do Children parallel" org-toggle-ordered-property :style radio
  19324. :selected (not (org-entry-get nil "ORDERED"))
  19325. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19326. "--"
  19327. ["Set Priority" org-priority t]
  19328. ["Priority Up" org-shiftup t]
  19329. ["Priority Down" org-shiftdown t]
  19330. "--"
  19331. ["Get news from all feeds" org-feed-update-all t]
  19332. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19333. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19334. ("TAGS and Properties"
  19335. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19336. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19337. "--"
  19338. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19339. ["Column view of properties" org-columns t]
  19340. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19341. ("Dates and Scheduling"
  19342. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19343. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19344. ("Change Date"
  19345. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19346. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19347. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19348. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19349. ["Compute Time Range" org-evaluate-time-range t]
  19350. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19351. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19352. "--"
  19353. ["Custom time format" org-toggle-time-stamp-overlays
  19354. :style radio :selected org-display-custom-times]
  19355. "--"
  19356. ["Goto Calendar" org-goto-calendar t]
  19357. ["Date from Calendar" org-date-from-calendar t]
  19358. "--"
  19359. ["Start/Restart Timer" org-timer-start t]
  19360. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19361. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19362. ["Insert Timer String" org-timer t]
  19363. ["Insert Timer Item" org-timer-item t])
  19364. ("Logging work"
  19365. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19366. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19367. ["Clock out" org-clock-out t]
  19368. ["Clock cancel" org-clock-cancel t]
  19369. "--"
  19370. ["Mark as default task" org-clock-mark-default-task t]
  19371. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19372. ["Goto running clock" org-clock-goto t]
  19373. "--"
  19374. ["Display times" org-clock-display t]
  19375. ["Create clock table" org-clock-report t]
  19376. "--"
  19377. ["Record DONE time"
  19378. (progn (setq org-log-done (not org-log-done))
  19379. (message "Switching to %s will %s record a timestamp"
  19380. (car org-done-keywords)
  19381. (if org-log-done "automatically" "not")))
  19382. :style toggle :selected org-log-done])
  19383. "--"
  19384. ["Agenda Command..." org-agenda t]
  19385. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19386. ("File List for Agenda")
  19387. ("Special views current file"
  19388. ["TODO Tree" org-show-todo-tree t]
  19389. ["Check Deadlines" org-check-deadlines t]
  19390. ["Tags/Property tree" org-match-sparse-tree t])
  19391. "--"
  19392. ["Export/Publish..." org-export-dispatch t]
  19393. ("LaTeX"
  19394. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19395. :style toggle :selected org-cdlatex-mode]
  19396. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19397. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19398. ["Modify math symbol" org-cdlatex-math-modify
  19399. (org-inside-LaTeX-fragment-p)]
  19400. ["Insert citation" org-reftex-citation t])
  19401. "--"
  19402. ("MobileOrg"
  19403. ["Push Files and Views" org-mobile-push t]
  19404. ["Get Captured and Flagged" org-mobile-pull t]
  19405. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19406. "--"
  19407. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19408. "--"
  19409. ("Documentation"
  19410. ["Show Version" org-version t]
  19411. ["Info Documentation" org-info t])
  19412. ("Customize"
  19413. ["Browse Org Group" org-customize t]
  19414. "--"
  19415. ["Expand This Menu" org-create-customize-menu
  19416. (fboundp 'customize-menu-create)])
  19417. ["Send bug report" org-submit-bug-report t]
  19418. "--"
  19419. ("Refresh/Reload"
  19420. ["Refresh setup current buffer" org-mode-restart t]
  19421. ["Reload Org (after update)" org-reload t]
  19422. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19423. ))
  19424. (defun org-info (&optional node)
  19425. "Read documentation for Org in the info system.
  19426. With optional NODE, go directly to that node."
  19427. (interactive)
  19428. (info (format "(org)%s" (or node ""))))
  19429. ;;;###autoload
  19430. (defun org-submit-bug-report ()
  19431. "Submit a bug report on Org via mail.
  19432. Don't hesitate to report any problems or inaccurate documentation.
  19433. If you don't have setup sending mail from (X)Emacs, please copy the
  19434. output buffer into your mail program, as it gives us important
  19435. information about your Org version and configuration."
  19436. (interactive)
  19437. (require 'reporter)
  19438. (defvar reporter-prompt-for-summary-p)
  19439. (org-load-modules-maybe)
  19440. (org-require-autoloaded-modules)
  19441. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19442. (reporter-submit-bug-report
  19443. "emacs-orgmode@gnu.org"
  19444. (org-version nil 'full)
  19445. (let (list)
  19446. (save-window-excursion
  19447. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19448. (delete-other-windows)
  19449. (erase-buffer)
  19450. (insert "You are about to submit a bug report to the Org mailing list.
  19451. We would like to add your full Org and Outline configuration to the
  19452. bug report. This greatly simplifies the work of the maintainer and
  19453. other experts on the mailing list.
  19454. HOWEVER, some variables you have customized may contain private
  19455. information. The names of customers, colleagues, or friends, might
  19456. appear in the form of file names, tags, todo states, or search strings.
  19457. If you answer yes to the prompt, you might want to check and remove
  19458. such private information before sending the email.")
  19459. (add-text-properties (point-min) (point-max) '(face org-warning))
  19460. (when (yes-or-no-p "Include your Org configuration ")
  19461. (mapatoms
  19462. (lambda (v)
  19463. (and (boundp v)
  19464. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19465. (or (and (symbol-value v)
  19466. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19467. (and
  19468. (get v 'custom-type) (get v 'standard-value)
  19469. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19470. (push v list)))))
  19471. (kill-buffer (get-buffer "*Warn about privacy*"))
  19472. list))
  19473. nil nil
  19474. "Remember to cover the basics, that is, what you expected to happen and
  19475. what in fact did happen. You don't know how to make a good report? See
  19476. http://orgmode.org/manual/Feedback.html#Feedback
  19477. Your bug report will be posted to the Org mailing list.
  19478. ------------------------------------------------------------------------")
  19479. (save-excursion
  19480. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19481. (replace-match "\\1Bug: \\3 [\\2]")))))
  19482. (defun org-install-agenda-files-menu ()
  19483. (let ((bl (buffer-list)))
  19484. (save-excursion
  19485. (while bl
  19486. (set-buffer (pop bl))
  19487. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19488. (when (derived-mode-p 'org-mode)
  19489. (easy-menu-change
  19490. '("Org") "File List for Agenda"
  19491. (append
  19492. (list
  19493. ["Edit File List" (org-edit-agenda-file-list) t]
  19494. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19495. ["Remove Current File from List" org-remove-file t]
  19496. ["Cycle through agenda files" org-cycle-agenda-files t]
  19497. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19498. "--")
  19499. (mapcar 'org-file-menu-entry
  19500. ;; Prevent initialization from failing.
  19501. (ignore-errors (org-agenda-files t)))))))))
  19502. ;;;; Documentation
  19503. (defun org-require-autoloaded-modules ()
  19504. (interactive)
  19505. (mapc #'require
  19506. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19507. org-table org-timer)))
  19508. ;;;###autoload
  19509. (defun org-reload (&optional uncompiled)
  19510. "Reload all org lisp files.
  19511. With prefix arg UNCOMPILED, load the uncompiled versions."
  19512. (interactive "P")
  19513. (require 'loadhist)
  19514. (let* ((org-dir (org-find-library-dir "org"))
  19515. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19516. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19517. (remove-re (format "\\`%s\\'"
  19518. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19519. (feats (delete-dups
  19520. (mapcar 'file-name-sans-extension
  19521. (mapcar 'file-name-nondirectory
  19522. (delq nil
  19523. (mapcar 'feature-file
  19524. features))))))
  19525. (lfeat (append
  19526. (sort
  19527. (setq feats
  19528. (delq nil (mapcar
  19529. (lambda (f)
  19530. (if (and (string-match feature-re f)
  19531. (not (string-match remove-re f)))
  19532. f nil))
  19533. feats)))
  19534. 'string-lessp)
  19535. (list "org-version" "org")))
  19536. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19537. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19538. load-uncore load-misses)
  19539. (setq load-misses
  19540. (delq 't
  19541. (mapcar (lambda (f)
  19542. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19543. (and (string= org-dir contrib-dir)
  19544. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19545. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19546. (add-to-list 'load-uncore f 'append)
  19547. 't)
  19548. f))
  19549. lfeat)))
  19550. (when load-uncore
  19551. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19552. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19553. (if load-misses
  19554. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19555. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19556. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19557. ;;;###autoload
  19558. (defun org-customize ()
  19559. "Call the customize function with org as argument."
  19560. (interactive)
  19561. (org-load-modules-maybe)
  19562. (org-require-autoloaded-modules)
  19563. (customize-browse 'org))
  19564. (defun org-create-customize-menu ()
  19565. "Create a full customization menu for Org mode, insert it into the menu."
  19566. (interactive)
  19567. (org-load-modules-maybe)
  19568. (org-require-autoloaded-modules)
  19569. (if (fboundp 'customize-menu-create)
  19570. (progn
  19571. (easy-menu-change
  19572. '("Org") "Customize"
  19573. `(["Browse Org group" org-customize t]
  19574. "--"
  19575. ,(customize-menu-create 'org)
  19576. ["Set" Custom-set t]
  19577. ["Save" Custom-save t]
  19578. ["Reset to Current" Custom-reset-current t]
  19579. ["Reset to Saved" Custom-reset-saved t]
  19580. ["Reset to Standard Settings" Custom-reset-standard t]))
  19581. (message "\"Org\"-menu now contains full customization menu"))
  19582. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19583. ;;;; Miscellaneous stuff
  19584. ;;; Generally useful functions
  19585. (defun org-link-display-format (s)
  19586. "Replace links in string S with their description.
  19587. If there is no description, use the link target."
  19588. (save-match-data
  19589. (replace-regexp-in-string
  19590. org-bracket-link-analytic-regexp
  19591. (lambda (m)
  19592. (if (match-end 5) (match-string 5 m)
  19593. (concat (match-string 1 m) (match-string 3 m))))
  19594. s nil t)))
  19595. (defun org-toggle-link-display ()
  19596. "Toggle the literal or descriptive display of links."
  19597. (interactive)
  19598. (if org-descriptive-links
  19599. (progn (org-remove-from-invisibility-spec '(org-link))
  19600. (org-restart-font-lock)
  19601. (setq org-descriptive-links nil))
  19602. (progn (add-to-invisibility-spec '(org-link))
  19603. (org-restart-font-lock)
  19604. (setq org-descriptive-links t))))
  19605. (defun org-in-clocktable-p ()
  19606. "Check if the cursor is in a clocktable."
  19607. (let ((pos (point)) start)
  19608. (save-excursion
  19609. (end-of-line 1)
  19610. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19611. (setq start (match-beginning 0))
  19612. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19613. (>= (match-end 0) pos)
  19614. start))))
  19615. (defun org-in-verbatim-emphasis ()
  19616. (save-match-data
  19617. (and (org-in-regexp org-verbatim-re 2)
  19618. (>= (point) (match-beginning 3))
  19619. (<= (point) (match-end 4)))))
  19620. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19621. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19622. (if (and marker (marker-buffer marker)
  19623. (buffer-live-p (marker-buffer marker)))
  19624. (progn
  19625. (pop-to-buffer-same-window (marker-buffer marker))
  19626. (when (or (> marker (point-max)) (< marker (point-min)))
  19627. (widen))
  19628. (goto-char marker)
  19629. (org-show-context 'org-goto))
  19630. (if bookmark
  19631. (bookmark-jump bookmark)
  19632. (error "Cannot find location"))))
  19633. (defun org-quote-csv-field (s)
  19634. "Quote field for inclusion in CSV material."
  19635. (if (string-match "[\",]" s)
  19636. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19637. s))
  19638. (defun org-force-self-insert (N)
  19639. "Needed to enforce self-insert under remapping."
  19640. (interactive "p")
  19641. (self-insert-command N))
  19642. (defun org-get-indentation (&optional line)
  19643. "Get the indentation of the current line, interpreting tabs.
  19644. When LINE is given, assume it represents a line and compute its indentation."
  19645. (if line
  19646. (when (string-match "^ *" (org-remove-tabs line))
  19647. (match-end 0))
  19648. (save-excursion
  19649. (beginning-of-line 1)
  19650. (skip-chars-forward " \t")
  19651. (current-column))))
  19652. (defun org-get-string-indentation (s)
  19653. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19654. (let ((n -1) (i 0) (w tab-width) c)
  19655. (catch 'exit
  19656. (while (< (setq n (1+ n)) (length s))
  19657. (setq c (aref s n))
  19658. (cond ((= c ?\ ) (setq i (1+ i)))
  19659. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19660. (t (throw 'exit t)))))
  19661. i))
  19662. (defun org-fix-indentation (line ind)
  19663. "Fix indentation in LINE.
  19664. IND is a cons cell with target and minimum indentation.
  19665. If the current indentation in LINE is smaller than the minimum,
  19666. leave it alone. If it is larger than ind, set it to the target."
  19667. (let* ((l (org-remove-tabs line))
  19668. (i (org-get-indentation l))
  19669. (i1 (car ind)) (i2 (cdr ind)))
  19670. (when (>= i i2) (setq l (substring line i2)))
  19671. (if (> i1 0)
  19672. (concat (make-string i1 ?\ ) l)
  19673. l)))
  19674. (defun org-fill-template (template alist)
  19675. "Find each %key of ALIST in TEMPLATE and replace it."
  19676. (let ((case-fold-search nil))
  19677. (dolist (entry (sort (copy-sequence alist)
  19678. (lambda (a b) (< (length (car a)) (length (car b))))))
  19679. (setq template
  19680. (replace-regexp-in-string
  19681. (concat "%" (regexp-quote (car entry)))
  19682. (or (cdr entry) "") template t t)))
  19683. template))
  19684. (defun org-quote-vert (s)
  19685. "Replace \"|\" with \"\\vert\"."
  19686. (while (string-match "|" s)
  19687. (setq s (replace-match "\\vert" t t s)))
  19688. s)
  19689. (defun org-uuidgen-p (s)
  19690. "Is S an ID created by UUIDGEN?"
  19691. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19692. (defun org-in-src-block-p (&optional inside)
  19693. "Whether point is in a code source block.
  19694. When INSIDE is non-nil, don't consider we are within a src block
  19695. when point is at #+BEGIN_SRC or #+END_SRC."
  19696. (let ((case-fold-search t))
  19697. (or (and (eq (get-char-property (point) 'src-block) t))
  19698. (and (not inside)
  19699. (save-match-data
  19700. (save-excursion
  19701. (beginning-of-line)
  19702. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19703. (defun org-context ()
  19704. "Return a list of contexts of the current cursor position.
  19705. If several contexts apply, all are returned.
  19706. Each context entry is a list with a symbol naming the context, and
  19707. two positions indicating start and end of the context. Possible
  19708. contexts are:
  19709. :headline anywhere in a headline
  19710. :headline-stars on the leading stars in a headline
  19711. :todo-keyword on a TODO keyword (including DONE) in a headline
  19712. :tags on the TAGS in a headline
  19713. :priority on the priority cookie in a headline
  19714. :item on the first line of a plain list item
  19715. :item-bullet on the bullet/number of a plain list item
  19716. :checkbox on the checkbox in a plain list item
  19717. :table in an Org table
  19718. :table-special on a special filed in a table
  19719. :table-table in a table.el table
  19720. :clocktable in a clocktable
  19721. :src-block in a source block
  19722. :link on a hyperlink
  19723. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19724. :target on a <<target>>
  19725. :radio-target on a <<<radio-target>>>
  19726. :latex-fragment on a LaTeX fragment
  19727. :latex-preview on a LaTeX fragment with overlaid preview image
  19728. This function expects the position to be visible because it uses font-lock
  19729. faces as a help to recognize the following contexts: :table-special, :link,
  19730. and :keyword."
  19731. (let* ((f (get-text-property (point) 'face))
  19732. (faces (if (listp f) f (list f)))
  19733. (case-fold-search t)
  19734. (p (point)) clist o)
  19735. ;; First the large context
  19736. (cond
  19737. ((org-at-heading-p t)
  19738. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19739. (when (progn
  19740. (beginning-of-line 1)
  19741. (looking-at org-todo-line-tags-regexp))
  19742. (push (org-point-in-group p 1 :headline-stars) clist)
  19743. (push (org-point-in-group p 2 :todo-keyword) clist)
  19744. (push (org-point-in-group p 4 :tags) clist))
  19745. (goto-char p)
  19746. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19747. (when (looking-at "\\[#[A-Z0-9]\\]")
  19748. (push (org-point-in-group p 0 :priority) clist)))
  19749. ((org-at-item-p)
  19750. (push (org-point-in-group p 2 :item-bullet) clist)
  19751. (push (list :item (point-at-bol)
  19752. (save-excursion (org-end-of-item) (point)))
  19753. clist)
  19754. (and (org-at-item-checkbox-p)
  19755. (push (org-point-in-group p 0 :checkbox) clist)))
  19756. ((org-at-table-p)
  19757. (push (list :table (org-table-begin) (org-table-end)) clist)
  19758. (when (memq 'org-formula faces)
  19759. (push (list :table-special
  19760. (previous-single-property-change p 'face)
  19761. (next-single-property-change p 'face)) clist)))
  19762. ((org-at-table-p 'any)
  19763. (push (list :table-table) clist)))
  19764. (goto-char p)
  19765. (let ((case-fold-search t))
  19766. ;; New the "medium" contexts: clocktables, source blocks
  19767. (cond ((org-in-clocktable-p)
  19768. (push (list :clocktable
  19769. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19770. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19771. (match-beginning 1))
  19772. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19773. (match-end 0))) clist))
  19774. ((org-in-src-block-p)
  19775. (push (list :src-block
  19776. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19777. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19778. (match-beginning 1))
  19779. (and (search-forward "#+END_SRC" nil t)
  19780. (match-beginning 0))) clist))))
  19781. (goto-char p)
  19782. ;; Now the small context
  19783. (cond
  19784. ((org-at-timestamp-p)
  19785. (push (org-point-in-group p 0 :timestamp) clist))
  19786. ((memq 'org-link faces)
  19787. (push (list :link
  19788. (previous-single-property-change p 'face)
  19789. (next-single-property-change p 'face)) clist))
  19790. ((memq 'org-special-keyword faces)
  19791. (push (list :keyword
  19792. (previous-single-property-change p 'face)
  19793. (next-single-property-change p 'face)) clist))
  19794. ((org-at-target-p)
  19795. (push (org-point-in-group p 0 :target) clist)
  19796. (goto-char (1- (match-beginning 0)))
  19797. (when (looking-at org-radio-target-regexp)
  19798. (push (org-point-in-group p 0 :radio-target) clist))
  19799. (goto-char p))
  19800. ((setq o (cl-some
  19801. (lambda (o)
  19802. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19803. o))
  19804. (overlays-at (point))))
  19805. (push (list :latex-fragment
  19806. (overlay-start o) (overlay-end o)) clist)
  19807. (push (list :latex-preview
  19808. (overlay-start o) (overlay-end o)) clist))
  19809. ((org-inside-LaTeX-fragment-p)
  19810. ;; FIXME: positions wrong.
  19811. (push (list :latex-fragment (point) (point)) clist)))
  19812. (setq clist (nreverse (delq nil clist)))
  19813. clist))
  19814. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19815. "Non-nil when point is between matches of START-RE and END-RE.
  19816. Also return a non-nil value when point is on one of the matches.
  19817. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19818. buffer positions. Default values are the positions of headlines
  19819. surrounding the point.
  19820. The functions returns a cons cell whose car (resp. cdr) is the
  19821. position before START-RE (resp. after END-RE)."
  19822. (save-match-data
  19823. (let ((pos (point))
  19824. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19825. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19826. beg end)
  19827. (save-excursion
  19828. ;; Point is on a block when on START-RE or if START-RE can be
  19829. ;; found before it...
  19830. (and (or (org-in-regexp start-re)
  19831. (re-search-backward start-re limit-up t))
  19832. (setq beg (match-beginning 0))
  19833. ;; ... and END-RE after it...
  19834. (goto-char (match-end 0))
  19835. (re-search-forward end-re limit-down t)
  19836. (> (setq end (match-end 0)) pos)
  19837. ;; ... without another START-RE in-between.
  19838. (goto-char (match-beginning 0))
  19839. (not (re-search-backward start-re (1+ beg) t))
  19840. ;; Return value.
  19841. (cons beg end))))))
  19842. (defun org-in-block-p (names)
  19843. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19844. NAMES is a list of strings containing names of blocks.
  19845. Return first block name matched, or nil. Beware that in case of
  19846. nested blocks, the returned name may not belong to the closest
  19847. block from point."
  19848. (save-match-data
  19849. (catch 'exit
  19850. (let ((case-fold-search t)
  19851. (lim-up (save-excursion (outline-previous-heading)))
  19852. (lim-down (save-excursion (outline-next-heading))))
  19853. (dolist (name names)
  19854. (let ((n (regexp-quote name)))
  19855. (when (org-between-regexps-p
  19856. (concat "^[ \t]*#\\+begin_" n)
  19857. (concat "^[ \t]*#\\+end_" n)
  19858. lim-up lim-down)
  19859. (throw 'exit n)))))
  19860. nil)))
  19861. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19862. "Call `multi-occur' with buffers for all agenda files."
  19863. (interactive "sOrg-files matching: ")
  19864. (let* ((files (org-agenda-files))
  19865. (tnames (mapcar #'file-truename files))
  19866. (extra org-agenda-text-search-extra-files))
  19867. (when (eq (car extra) 'agenda-archives)
  19868. (setq extra (cdr extra))
  19869. (setq files (org-add-archive-files files)))
  19870. (dolist (f extra)
  19871. (unless (member (file-truename f) tnames)
  19872. (unless (member f files) (setq files (append files (list f))))
  19873. (setq tnames (append tnames (list (file-truename f))))))
  19874. (multi-occur
  19875. (mapcar (lambda (x)
  19876. (with-current-buffer
  19877. ;; FIXME: Why not just (find-file-noselect x)?
  19878. ;; Is it to avoid the "revert buffer" prompt?
  19879. (or (get-file-buffer x) (find-file-noselect x))
  19880. (widen)
  19881. (current-buffer)))
  19882. files)
  19883. regexp)))
  19884. (add-hook 'occur-mode-find-occurrence-hook
  19885. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19886. (defun org-occur-link-in-agenda-files ()
  19887. "Create a link and search for it in the agendas.
  19888. The link is not stored in `org-stored-links', it is just created
  19889. for the search purpose."
  19890. (interactive)
  19891. (let ((link (condition-case nil
  19892. (org-store-link nil)
  19893. (error "Unable to create a link to here"))))
  19894. (org-occur-in-agenda-files (regexp-quote link))))
  19895. (defun org-back-over-empty-lines ()
  19896. "Move backwards over whitespace, to the beginning of the first empty line.
  19897. Returns the number of empty lines passed."
  19898. (let ((pos (point)))
  19899. (if (cdr (assq 'heading org-blank-before-new-entry))
  19900. (skip-chars-backward " \t\n\r")
  19901. (unless (eobp)
  19902. (forward-line -1)))
  19903. (beginning-of-line 2)
  19904. (goto-char (min (point) pos))
  19905. (count-lines (point) pos)))
  19906. (defun org-switch-to-buffer-other-window (&rest args)
  19907. "Switch to buffer in a second window on the current frame.
  19908. In particular, do not allow pop-up frames.
  19909. Returns the newly created buffer."
  19910. (org-no-popups
  19911. (apply 'switch-to-buffer-other-window args)))
  19912. (defun org-replace-escapes (string table)
  19913. "Replace %-escapes in STRING with values in TABLE.
  19914. TABLE is an association list with keys like \"%a\" and string values.
  19915. The sequences in STRING may contain normal field width and padding information,
  19916. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19917. so values can contain further %-escapes if they are define later in TABLE."
  19918. (let ((tbl (copy-alist table))
  19919. (case-fold-search nil)
  19920. (pchg 0)
  19921. re rpl)
  19922. (dolist (e tbl)
  19923. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19924. (when (and (cdr e) (string-match re (cdr e)))
  19925. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19926. (safe "SREF"))
  19927. (add-text-properties 0 3 (list 'sref sref) safe)
  19928. (setcdr e (replace-match safe t t (cdr e)))))
  19929. (while (string-match re string)
  19930. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19931. (cdr e)))
  19932. (setq string (replace-match rpl t t string))))
  19933. (while (setq pchg (next-property-change pchg string))
  19934. (let ((sref (get-text-property pchg 'sref string)))
  19935. (when (and sref (string-match "SREF" string pchg))
  19936. (setq string (replace-match sref t t string)))))
  19937. string))
  19938. ;;; TODO: Only called once, from ox-odt which should probably use
  19939. ;;; org-export-inline-image-p or something.
  19940. (defun org-file-image-p (file)
  19941. "Return non-nil if FILE is an image."
  19942. (save-match-data
  19943. (string-match (image-file-name-regexp) file)))
  19944. (defun org-get-cursor-date (&optional with-time)
  19945. "Return the date at cursor in as a time.
  19946. This works in the calendar and in the agenda, anywhere else it just
  19947. returns the current time.
  19948. If WITH-TIME is non-nil, returns the time of the event at point (in
  19949. the agenda) or the current time of the day."
  19950. (let (date day defd tp hod mod)
  19951. (when with-time
  19952. (setq tp (get-text-property (point) 'time))
  19953. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19954. (setq hod (string-to-number (match-string 1 tp))
  19955. mod (string-to-number (match-string 2 tp))))
  19956. (or tp (let ((now (decode-time)))
  19957. (setq hod (nth 2 now)
  19958. mod (nth 1 now)))))
  19959. (cond
  19960. ((eq major-mode 'calendar-mode)
  19961. (setq date (calendar-cursor-to-date)
  19962. defd (encode-time 0 (or mod 0) (or hod 0)
  19963. (nth 1 date) (nth 0 date) (nth 2 date))))
  19964. ((eq major-mode 'org-agenda-mode)
  19965. (setq day (get-text-property (point) 'day))
  19966. (when day
  19967. (setq date (calendar-gregorian-from-absolute day)
  19968. defd (encode-time 0 (or mod 0) (or hod 0)
  19969. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19970. (or defd (current-time))))
  19971. (defun org-mark-subtree (&optional up)
  19972. "Mark the current subtree.
  19973. This puts point at the start of the current subtree, and mark at
  19974. the end. If a numeric prefix UP is given, move up into the
  19975. hierarchy of headlines by UP levels before marking the subtree."
  19976. (interactive "P")
  19977. (org-with-limited-levels
  19978. (cond ((org-at-heading-p) (beginning-of-line))
  19979. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19980. (t (outline-previous-visible-heading 1))))
  19981. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19982. (if (called-interactively-p 'any)
  19983. (call-interactively 'org-mark-element)
  19984. (org-mark-element)))
  19985. (defun org-file-newer-than-p (file time)
  19986. "Non-nil if FILE is newer than TIME.
  19987. FILE is a filename, as a string, TIME is a list of integers, as
  19988. returned by, e.g., `current-time'."
  19989. (and (file-exists-p file)
  19990. ;; Only compare times up to whole seconds as some file-systems
  19991. ;; (e.g. HFS+) do not retain any finer granularity. As
  19992. ;; a consequence, make sure we return non-nil when the two
  19993. ;; times are equal.
  19994. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  19995. (cl-subseq time 0 2)))))
  19996. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  19997. "Compile a SOURCE file using PROCESS.
  19998. PROCESS is either a function or a list of shell commands, as
  19999. strings. EXT is a file extension, without the leading dot, as
  20000. a string. It is used to check if the process actually succeeded.
  20001. PROCESS must create a file with the same base name and directory
  20002. as SOURCE, but ending with EXT. The function then returns its
  20003. filename. Otherwise, it raises an error. The error message can
  20004. then be refined by providing string ERR-MSG, which is appended to
  20005. the standard message.
  20006. If PROCESS is a function, it is called with a single argument:
  20007. the SOURCE file.
  20008. If it is a list of commands, each of them is called using
  20009. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20010. %O are replaced with, respectively, SOURCE base name, name, full
  20011. name, directory and absolute output file name. It is possible,
  20012. however, to use more place-holders by specifying them in optional
  20013. argument SPEC, as an alist following the pattern
  20014. (CHARACTER . REPLACEMENT-STRING).
  20015. When PROCESS is a list of commands, optional argument LOG-BUF can
  20016. be set to a buffer or a buffer name. `shell-command' then uses
  20017. it for output."
  20018. (let* ((base-name (file-name-base source))
  20019. (full-name (file-truename source))
  20020. (out-dir (or (file-name-directory source) "./"))
  20021. (output (expand-file-name (concat base-name "." ext) out-dir))
  20022. (time (current-time))
  20023. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20024. (save-window-excursion
  20025. (pcase process
  20026. ((pred functionp) (funcall process (shell-quote-argument source)))
  20027. ((pred consp)
  20028. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20029. (spec (append spec
  20030. `((?b . ,(shell-quote-argument base-name))
  20031. (?f . ,(shell-quote-argument source))
  20032. (?F . ,(shell-quote-argument full-name))
  20033. (?o . ,(shell-quote-argument out-dir))
  20034. (?O . ,(shell-quote-argument output))))))
  20035. (dolist (command process)
  20036. (shell-command (format-spec command spec) log-buf))
  20037. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20038. (_ (error "No valid command to process %S%s" source err-msg))))
  20039. ;; Check for process failure. Output file is expected to be
  20040. ;; located in the same directory as SOURCE.
  20041. (unless (org-file-newer-than-p output time)
  20042. (error (format "File %S wasn't produced%s" output err-msg)))
  20043. output))
  20044. ;;; Indentation
  20045. (defvar org-element-greater-elements)
  20046. (defun org--get-expected-indentation (element contentsp)
  20047. "Expected indentation column for current line, according to ELEMENT.
  20048. ELEMENT is an element containing point. CONTENTSP is non-nil
  20049. when indentation is to be computed according to contents of
  20050. ELEMENT."
  20051. (let ((type (org-element-type element))
  20052. (start (org-element-property :begin element))
  20053. (post-affiliated (org-element-property :post-affiliated element)))
  20054. (org-with-wide-buffer
  20055. (cond
  20056. (contentsp
  20057. (cl-case type
  20058. ((diary-sexp footnote-definition) 0)
  20059. ((headline inlinetask nil)
  20060. (if (not org-adapt-indentation) 0
  20061. (let ((level (org-current-level)))
  20062. (if level (1+ level) 0))))
  20063. ((item plain-list) (org-list-item-body-column post-affiliated))
  20064. (t
  20065. (goto-char start)
  20066. (org-get-indentation))))
  20067. ((memq type '(headline inlinetask nil))
  20068. (if (org-match-line "[ \t]*$")
  20069. (org--get-expected-indentation element t)
  20070. 0))
  20071. ((memq type '(diary-sexp footnote-definition)) 0)
  20072. ;; First paragraph of a footnote definition or an item.
  20073. ;; Indent like parent.
  20074. ((< (line-beginning-position) start)
  20075. (org--get-expected-indentation
  20076. (org-element-property :parent element) t))
  20077. ;; At first line: indent according to previous sibling, if any,
  20078. ;; ignoring footnote definitions and inline tasks, or parent's
  20079. ;; contents.
  20080. ((= (line-beginning-position) start)
  20081. (catch 'exit
  20082. (while t
  20083. (if (= (point-min) start) (throw 'exit 0)
  20084. (goto-char (1- start))
  20085. (let* ((previous (org-element-at-point))
  20086. (parent previous))
  20087. (while (and parent (<= (org-element-property :end parent) start))
  20088. (setq previous parent
  20089. parent (org-element-property :parent parent)))
  20090. (cond
  20091. ((not previous) (throw 'exit 0))
  20092. ((> (org-element-property :end previous) start)
  20093. (throw 'exit (org--get-expected-indentation previous t)))
  20094. ((memq (org-element-type previous)
  20095. '(footnote-definition inlinetask))
  20096. (setq start (org-element-property :begin previous)))
  20097. (t (goto-char (org-element-property :begin previous))
  20098. (throw 'exit
  20099. (if (bolp) (org-get-indentation)
  20100. ;; At first paragraph in an item or
  20101. ;; a footnote definition.
  20102. (org--get-expected-indentation
  20103. (org-element-property :parent previous) t))))))))))
  20104. ;; Otherwise, move to the first non-blank line above.
  20105. (t
  20106. (beginning-of-line)
  20107. (let ((pos (point)))
  20108. (skip-chars-backward " \r\t\n")
  20109. (cond
  20110. ;; Two blank lines end a footnote definition or a plain
  20111. ;; list. When we indent an empty line after them, the
  20112. ;; containing list or footnote definition is over, so it
  20113. ;; qualifies as a previous sibling. Therefore, we indent
  20114. ;; like its first line.
  20115. ((and (memq type '(footnote-definition plain-list))
  20116. (> (count-lines (point) pos) 2))
  20117. (goto-char start)
  20118. (org-get-indentation))
  20119. ;; Line above is the first one of a paragraph at the
  20120. ;; beginning of an item or a footnote definition. Indent
  20121. ;; like parent.
  20122. ((< (line-beginning-position) start)
  20123. (org--get-expected-indentation
  20124. (org-element-property :parent element) t))
  20125. ;; Line above is the beginning of an element, i.e., point
  20126. ;; was originally on the blank lines between element's start
  20127. ;; and contents.
  20128. ((= (line-beginning-position) post-affiliated)
  20129. (org--get-expected-indentation element t))
  20130. ;; POS is after contents in a greater element. Indent like
  20131. ;; the beginning of the element.
  20132. ((and (memq type org-element-greater-elements)
  20133. (let ((cend (org-element-property :contents-end element)))
  20134. (and cend (<= cend pos))))
  20135. ;; As a special case, if point is at the end of a footnote
  20136. ;; definition or an item, indent like the very last element
  20137. ;; within. If that last element is an item, indent like
  20138. ;; its contents.
  20139. (if (memq type '(footnote-definition item plain-list))
  20140. (let ((last (org-element-at-point)))
  20141. (goto-char pos)
  20142. (org--get-expected-indentation
  20143. last (eq (org-element-type last) 'item)))
  20144. (goto-char start)
  20145. (org-get-indentation)))
  20146. ;; In any other case, indent like the current line.
  20147. (t (org-get-indentation)))))))))
  20148. (defun org--align-node-property ()
  20149. "Align node property at point.
  20150. Alignment is done according to `org-property-format', which see."
  20151. (when (save-excursion
  20152. (beginning-of-line)
  20153. (looking-at org-property-re))
  20154. (replace-match
  20155. (concat (match-string 4)
  20156. (org-trim
  20157. (format org-property-format (match-string 1) (match-string 3))))
  20158. t t)))
  20159. (defun org-indent-line ()
  20160. "Indent line depending on context.
  20161. Indentation is done according to the following rules:
  20162. - Footnote definitions, diary sexps, headlines and inline tasks
  20163. have to start at column 0.
  20164. - On the very first line of an element, consider, in order, the
  20165. next rules until one matches:
  20166. 1. If there's a sibling element before, ignoring footnote
  20167. definitions and inline tasks, indent like its first line.
  20168. 2. If element has a parent, indent like its contents. More
  20169. precisely, if parent is an item, indent after the
  20170. description part, if any, or the bullet (see
  20171. `org-list-description-max-indent'). Else, indent like
  20172. parent's first line.
  20173. 3. Otherwise, indent relatively to current level, if
  20174. `org-adapt-indentation' is non-nil, or to left margin.
  20175. - On a blank line at the end of an element, indent according to
  20176. the type of the element. More precisely
  20177. 1. If element is a plain list, an item, or a footnote
  20178. definition, indent like the very last element within.
  20179. 2. If element is a paragraph, indent like its last non blank
  20180. line.
  20181. 3. Otherwise, indent like its very first line.
  20182. - In the code part of a source block, use language major mode
  20183. to indent current line if `org-src-tab-acts-natively' is
  20184. non-nil. If it is nil, do nothing.
  20185. - Otherwise, indent like the first non-blank line above.
  20186. The function doesn't indent an item as it could break the whole
  20187. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20188. `\\[org-shiftmetaright]'.
  20189. Also align node properties according to `org-property-format'."
  20190. (interactive)
  20191. (cond
  20192. (orgstruct-is-++
  20193. (let ((indent-line-function
  20194. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20195. (indent-according-to-mode)))
  20196. ((org-at-heading-p) 'noindent)
  20197. (t
  20198. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20199. (type (org-element-type element)))
  20200. (cond ((and (memq type '(plain-list item))
  20201. (= (line-beginning-position)
  20202. (org-element-property :post-affiliated element)))
  20203. 'noindent)
  20204. ((and (eq type 'latex-environment)
  20205. (>= (point) (org-element-property :post-affiliated element))
  20206. (< (point) (org-with-wide-buffer
  20207. (goto-char (org-element-property :end element))
  20208. (skip-chars-backward " \r\t\n")
  20209. (line-beginning-position 2))))
  20210. 'noindent)
  20211. ((and (eq type 'src-block)
  20212. org-src-tab-acts-natively
  20213. (> (line-beginning-position)
  20214. (org-element-property :post-affiliated element))
  20215. (< (line-beginning-position)
  20216. (org-with-wide-buffer
  20217. (goto-char (org-element-property :end element))
  20218. (skip-chars-backward " \r\t\n")
  20219. (line-beginning-position))))
  20220. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20221. (t
  20222. (let ((column (org--get-expected-indentation element nil)))
  20223. ;; Preserve current column.
  20224. (if (<= (current-column) (current-indentation))
  20225. (indent-line-to column)
  20226. (save-excursion (indent-line-to column))))
  20227. ;; Align node property. Also preserve current column.
  20228. (when (eq type 'node-property)
  20229. (let ((column (current-column)))
  20230. (org--align-node-property)
  20231. (org-move-to-column column)))))))))
  20232. (defun org-indent-region (start end)
  20233. "Indent each non-blank line in the region.
  20234. Called from a program, START and END specify the region to
  20235. indent. The function will not indent contents of example blocks,
  20236. verse blocks and export blocks as leading white spaces are
  20237. assumed to be significant there."
  20238. (interactive "r")
  20239. (save-excursion
  20240. (goto-char start)
  20241. (skip-chars-forward " \r\t\n")
  20242. (unless (eobp) (beginning-of-line))
  20243. (let ((indent-to
  20244. (lambda (ind pos)
  20245. ;; Set IND as indentation for all lines between point and
  20246. ;; POS. Blank lines are ignored. Leave point after POS
  20247. ;; once done.
  20248. (let ((limit (copy-marker pos)))
  20249. (while (< (point) limit)
  20250. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20251. (forward-line))
  20252. (set-marker limit nil))))
  20253. (end (copy-marker end)))
  20254. (while (< (point) end)
  20255. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20256. (let* ((element (org-element-at-point))
  20257. (type (org-element-type element))
  20258. (element-end (copy-marker (org-element-property :end element)))
  20259. (ind (org--get-expected-indentation element nil)))
  20260. (cond
  20261. ;; Element indented as a single block. Example blocks
  20262. ;; preserving indentation are a special case since the
  20263. ;; "contents" must not be indented whereas the block
  20264. ;; boundaries can.
  20265. ((or (memq type '(export-block latex-environment))
  20266. (and (eq type 'example-block)
  20267. (not
  20268. (or org-src-preserve-indentation
  20269. (org-element-property :preserve-indent element)))))
  20270. (let ((offset (- ind (org-get-indentation))))
  20271. (unless (zerop offset)
  20272. (indent-rigidly (org-element-property :begin element)
  20273. (org-element-property :end element)
  20274. offset)))
  20275. (goto-char element-end))
  20276. ;; Elements indented line wise. Be sure to exclude
  20277. ;; example blocks (preserving indentation) and source
  20278. ;; blocks from this category as they are treated
  20279. ;; specially later.
  20280. ((or (memq type '(paragraph table table-row))
  20281. (not (or (org-element-property :contents-begin element)
  20282. (memq type '(example-block src-block)))))
  20283. (when (eq type 'node-property)
  20284. (org--align-node-property)
  20285. (beginning-of-line))
  20286. (funcall indent-to ind (min element-end end)))
  20287. ;; Elements consisting of three parts: before the
  20288. ;; contents, the contents, and after the contents. The
  20289. ;; contents are treated specially, according to the
  20290. ;; element type, or not indented at all. Other parts are
  20291. ;; indented as a single block.
  20292. (t
  20293. (let* ((post (copy-marker
  20294. (org-element-property :post-affiliated element)))
  20295. (cbeg
  20296. (copy-marker
  20297. (cond
  20298. ((not (org-element-property :contents-begin element))
  20299. ;; Fake contents for source blocks.
  20300. (org-with-wide-buffer
  20301. (goto-char post)
  20302. (line-beginning-position 2)))
  20303. ((memq type '(footnote-definition item plain-list))
  20304. ;; Contents in these elements could start on
  20305. ;; the same line as the beginning of the
  20306. ;; element. Make sure we start indenting
  20307. ;; from the second line.
  20308. (org-with-wide-buffer
  20309. (goto-char post)
  20310. (end-of-line)
  20311. (skip-chars-forward " \r\t\n")
  20312. (if (eobp) (point) (line-beginning-position))))
  20313. (t (org-element-property :contents-begin element)))))
  20314. (cend (copy-marker
  20315. (or (org-element-property :contents-end element)
  20316. ;; Fake contents for source blocks.
  20317. (org-with-wide-buffer
  20318. (goto-char element-end)
  20319. (skip-chars-backward " \r\t\n")
  20320. (line-beginning-position)))
  20321. t)))
  20322. ;; Do not change items indentation individually as it
  20323. ;; might break the list as a whole. On the other
  20324. ;; hand, when at a plain list, indent it as a whole.
  20325. (cond ((eq type 'plain-list)
  20326. (let ((offset (- ind (org-get-indentation))))
  20327. (unless (zerop offset)
  20328. (indent-rigidly (org-element-property :begin element)
  20329. (org-element-property :end element)
  20330. offset))
  20331. (goto-char cbeg)))
  20332. ((eq type 'item) (goto-char cbeg))
  20333. (t (funcall indent-to ind (min cbeg end))))
  20334. (when (< (point) end)
  20335. (cl-case type
  20336. ((example-block verse-block))
  20337. (src-block
  20338. ;; In a source block, indent source code
  20339. ;; according to language major mode, but only if
  20340. ;; `org-src-tab-acts-natively' is non-nil.
  20341. (when (and (< (point) end) org-src-tab-acts-natively)
  20342. (ignore-errors
  20343. (org-babel-do-in-edit-buffer
  20344. (indent-region (point-min) (point-max))))))
  20345. (t (org-indent-region (point) (min cend end))))
  20346. (goto-char (min cend end))
  20347. (when (< (point) end)
  20348. (funcall indent-to ind (min element-end end))))
  20349. (set-marker post nil)
  20350. (set-marker cbeg nil)
  20351. (set-marker cend nil))))
  20352. (set-marker element-end nil))))
  20353. (set-marker end nil))))
  20354. (defun org-indent-drawer ()
  20355. "Indent the drawer at point."
  20356. (interactive)
  20357. (unless (save-excursion
  20358. (beginning-of-line)
  20359. (looking-at-p org-drawer-regexp))
  20360. (user-error "Not at a drawer"))
  20361. (let ((element (org-element-at-point)))
  20362. (unless (memq (org-element-type element) '(drawer property-drawer))
  20363. (user-error "Not at a drawer"))
  20364. (org-with-wide-buffer
  20365. (org-indent-region (org-element-property :begin element)
  20366. (org-element-property :end element))))
  20367. (message "Drawer at point indented"))
  20368. (defun org-indent-block ()
  20369. "Indent the block at point."
  20370. (interactive)
  20371. (unless (save-excursion
  20372. (beginning-of-line)
  20373. (let ((case-fold-search t))
  20374. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20375. (user-error "Not at a block"))
  20376. (let ((element (org-element-at-point)))
  20377. (unless (memq (org-element-type element)
  20378. '(comment-block center-block dynamic-block example-block
  20379. export-block quote-block special-block
  20380. src-block verse-block))
  20381. (user-error "Not at a block"))
  20382. (org-with-wide-buffer
  20383. (org-indent-region (org-element-property :begin element)
  20384. (org-element-property :end element))))
  20385. (message "Block at point indented"))
  20386. ;;; Filling
  20387. ;; We use our own fill-paragraph and auto-fill functions.
  20388. ;; `org-fill-paragraph' relies on adaptive filling and context
  20389. ;; checking. Appropriate `fill-prefix' is computed with
  20390. ;; `org-adaptive-fill-function'.
  20391. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20392. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20393. ;; `org-adaptive-fill-function' value. Internally,
  20394. ;; `org-comment-line-break-function' breaks the line.
  20395. ;; `org-setup-filling' installs filling and auto-filling related
  20396. ;; variables during `org-mode' initialization.
  20397. (defun org-setup-filling ()
  20398. (require 'org-element)
  20399. ;; Prevent auto-fill from inserting unwanted new items.
  20400. (when (boundp 'fill-nobreak-predicate)
  20401. (setq-local
  20402. fill-nobreak-predicate
  20403. (org-uniquify
  20404. (append fill-nobreak-predicate
  20405. '(org-fill-line-break-nobreak-p
  20406. org-fill-n-macro-as-item-nobreak-p
  20407. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20408. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20409. (setq-local paragraph-start paragraph-ending)
  20410. (setq-local paragraph-separate paragraph-ending))
  20411. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20412. (setq-local auto-fill-inhibit-regexp nil)
  20413. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20414. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20415. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20416. (defun org-fill-line-break-nobreak-p ()
  20417. "Non-nil when a new line at point would create an Org line break."
  20418. (save-excursion
  20419. (skip-chars-backward "[ \t]")
  20420. (skip-chars-backward "\\\\")
  20421. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20422. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20423. "Non-nil when a new line at point would split a timestamp."
  20424. (and (org-at-timestamp-p 'lax)
  20425. (not (looking-at org-ts-regexp-both))))
  20426. (defun org-fill-n-macro-as-item-nobreak-p ()
  20427. "Non-nil when a new line at point would create a new list."
  20428. ;; During export, a "n" macro followed by a dot or a closing
  20429. ;; parenthesis can end up being parsed as a new list item.
  20430. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20431. (declare-function message-in-body-p "message" ())
  20432. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20433. (defun org-adaptive-fill-function ()
  20434. "Compute a fill prefix for the current line.
  20435. Return fill prefix, as a string, or nil if current line isn't
  20436. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20437. matches in paragraphs or comments, use it."
  20438. (catch 'exit
  20439. (when (derived-mode-p 'message-mode)
  20440. (save-excursion
  20441. (beginning-of-line)
  20442. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20443. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20444. ((looking-at message-cite-prefix-regexp)
  20445. (throw 'exit (match-string-no-properties 0)))
  20446. ((looking-at org-outline-regexp)
  20447. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20448. (org-with-wide-buffer
  20449. (unless (org-at-heading-p)
  20450. (let* ((p (line-beginning-position))
  20451. (element (save-excursion
  20452. (beginning-of-line)
  20453. (org-element-at-point)))
  20454. (type (org-element-type element))
  20455. (post-affiliated (org-element-property :post-affiliated element)))
  20456. (unless (< p post-affiliated)
  20457. (cl-case type
  20458. (comment
  20459. (save-excursion
  20460. (beginning-of-line)
  20461. (looking-at "[ \t]*")
  20462. (concat (match-string 0) "# ")))
  20463. (footnote-definition "")
  20464. ((item plain-list)
  20465. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20466. (paragraph
  20467. ;; Fill prefix is usually the same as the current line,
  20468. ;; unless the paragraph is at the beginning of an item.
  20469. (let ((parent (org-element-property :parent element)))
  20470. (save-excursion
  20471. (beginning-of-line)
  20472. (cond ((eq (org-element-type parent) 'item)
  20473. (make-string (org-list-item-body-column
  20474. (org-element-property :begin parent))
  20475. ?\s))
  20476. ((and adaptive-fill-regexp
  20477. ;; Locally disable
  20478. ;; `adaptive-fill-function' to let
  20479. ;; `fill-context-prefix' handle
  20480. ;; `adaptive-fill-regexp' variable.
  20481. (let (adaptive-fill-function)
  20482. (fill-context-prefix
  20483. post-affiliated
  20484. (org-element-property :end element)))))
  20485. ((looking-at "[ \t]+") (match-string 0))
  20486. (t "")))))
  20487. (comment-block
  20488. ;; Only fill contents if P is within block boundaries.
  20489. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20490. (forward-line)
  20491. (point)))
  20492. (cend (save-excursion
  20493. (goto-char (org-element-property :end element))
  20494. (skip-chars-backward " \r\t\n")
  20495. (line-beginning-position))))
  20496. (when (and (>= p cbeg) (< p cend))
  20497. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20498. (match-string 0)
  20499. "")))))))))))
  20500. (declare-function message-goto-body "message" ())
  20501. (defvar message-cite-prefix-regexp) ; From message.el
  20502. (defun org-fill-element (&optional justify)
  20503. "Fill element at point, when applicable.
  20504. This function only applies to comment blocks, comments, example
  20505. blocks and paragraphs. Also, as a special case, re-align table
  20506. when point is at one.
  20507. If JUSTIFY is non-nil (interactively, with prefix argument),
  20508. justify as well. If `sentence-end-double-space' is non-nil, then
  20509. period followed by one space does not end a sentence, so don't
  20510. break a line there. The variable `fill-column' controls the
  20511. width for filling.
  20512. For convenience, when point is at a plain list, an item or
  20513. a footnote definition, try to fill the first paragraph within."
  20514. (with-syntax-table org-mode-transpose-word-syntax-table
  20515. ;; Move to end of line in order to get the first paragraph within
  20516. ;; a plain list or a footnote definition.
  20517. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20518. ;; First check if point is in a blank line at the beginning of
  20519. ;; the buffer. In that case, ignore filling.
  20520. (cl-case (org-element-type element)
  20521. ;; Use major mode filling function is src blocks.
  20522. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20523. ;; Align Org tables, leave table.el tables as-is.
  20524. (table-row (org-table-align) t)
  20525. (table
  20526. (when (eq (org-element-property :type element) 'org)
  20527. (save-excursion
  20528. (goto-char (org-element-property :post-affiliated element))
  20529. (org-table-align)))
  20530. t)
  20531. (paragraph
  20532. ;; Paragraphs may contain `line-break' type objects.
  20533. (let ((beg (max (point-min)
  20534. (org-element-property :contents-begin element)))
  20535. (end (min (point-max)
  20536. (org-element-property :contents-end element))))
  20537. ;; Do nothing if point is at an affiliated keyword.
  20538. (if (< (line-end-position) beg) t
  20539. (when (derived-mode-p 'message-mode)
  20540. ;; In `message-mode', do not fill following citation
  20541. ;; in current paragraph nor text before message body.
  20542. (let ((body-start (save-excursion (message-goto-body))))
  20543. (when body-start (setq beg (max body-start beg))))
  20544. (when (save-excursion
  20545. (re-search-forward
  20546. (concat "^" message-cite-prefix-regexp) end t))
  20547. (setq end (match-beginning 0))))
  20548. ;; Fill paragraph, taking line breaks into account.
  20549. (save-excursion
  20550. (goto-char beg)
  20551. (let ((cuts (list beg)))
  20552. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20553. (when (eq 'line-break
  20554. (org-element-type
  20555. (save-excursion (backward-char)
  20556. (org-element-context))))
  20557. (push (point) cuts)))
  20558. (dolist (c (delq end cuts))
  20559. (fill-region-as-paragraph c end justify)
  20560. (setq end c))))
  20561. t)))
  20562. ;; Contents of `comment-block' type elements should be
  20563. ;; filled as plain text, but only if point is within block
  20564. ;; markers.
  20565. (comment-block
  20566. (let* ((case-fold-search t)
  20567. (beg (save-excursion
  20568. (goto-char (org-element-property :begin element))
  20569. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20570. (forward-line)
  20571. (point)))
  20572. (end (save-excursion
  20573. (goto-char (org-element-property :end element))
  20574. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20575. (line-beginning-position))))
  20576. (if (or (< (point) beg) (> (point) end)) t
  20577. (fill-region-as-paragraph
  20578. (save-excursion (end-of-line)
  20579. (re-search-backward "^[ \t]*$" beg 'move)
  20580. (line-beginning-position))
  20581. (save-excursion (beginning-of-line)
  20582. (re-search-forward "^[ \t]*$" end 'move)
  20583. (line-beginning-position))
  20584. justify))))
  20585. ;; Fill comments.
  20586. (comment
  20587. (let ((begin (org-element-property :post-affiliated element))
  20588. (end (org-element-property :end element)))
  20589. (when (and (>= (point) begin) (<= (point) end))
  20590. (let ((begin (save-excursion
  20591. (end-of-line)
  20592. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20593. (progn (forward-line) (point))
  20594. begin)))
  20595. (end (save-excursion
  20596. (end-of-line)
  20597. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20598. (1- (line-beginning-position))
  20599. (skip-chars-backward " \r\t\n")
  20600. (line-end-position)))))
  20601. ;; Do not fill comments when at a blank line.
  20602. (when (> end begin)
  20603. (let ((fill-prefix
  20604. (save-excursion
  20605. (beginning-of-line)
  20606. (looking-at "[ \t]*#")
  20607. (let ((comment-prefix (match-string 0)))
  20608. (goto-char (match-end 0))
  20609. (if (looking-at adaptive-fill-regexp)
  20610. (concat comment-prefix (match-string 0))
  20611. (concat comment-prefix " "))))))
  20612. (save-excursion
  20613. (fill-region-as-paragraph begin end justify))))))
  20614. t))
  20615. ;; Ignore every other element.
  20616. (otherwise t)))))
  20617. (defun org-fill-paragraph (&optional justify region)
  20618. "Fill element at point, when applicable.
  20619. This function only applies to comment blocks, comments, example
  20620. blocks and paragraphs. Also, as a special case, re-align table
  20621. when point is at one.
  20622. For convenience, when point is at a plain list, an item or
  20623. a footnote definition, try to fill the first paragraph within.
  20624. If JUSTIFY is non-nil (interactively, with prefix argument),
  20625. justify as well. If `sentence-end-double-space' is non-nil, then
  20626. period followed by one space does not end a sentence, so don't
  20627. break a line there. The variable `fill-column' controls the
  20628. width for filling.
  20629. The REGION argument is non-nil if called interactively; in that
  20630. case, if Transient Mark mode is enabled and the mark is active,
  20631. fill each of the elements in the active region, instead of just
  20632. filling the current element."
  20633. (interactive (progn
  20634. (barf-if-buffer-read-only)
  20635. (list (if current-prefix-arg 'full) t)))
  20636. (cond
  20637. ((and (derived-mode-p 'message-mode)
  20638. (or (not (message-in-body-p))
  20639. (save-excursion (move-beginning-of-line 1)
  20640. (looking-at message-cite-prefix-regexp))))
  20641. ;; First ensure filling is correct in message-mode.
  20642. (let ((fill-paragraph-function
  20643. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  20644. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  20645. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  20646. (paragraph-separate
  20647. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  20648. (fill-paragraph nil)))
  20649. ((and region transient-mark-mode mark-active
  20650. (not (eq (region-beginning) (region-end))))
  20651. (let ((origin (point-marker))
  20652. (start (region-beginning)))
  20653. (unwind-protect
  20654. (progn
  20655. (goto-char (region-end))
  20656. (while (> (point) start)
  20657. (org-backward-paragraph)
  20658. (org-fill-element justify)))
  20659. (goto-char origin)
  20660. (set-marker origin nil))))
  20661. (t (org-fill-element justify))))
  20662. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  20663. (defun org-auto-fill-function ()
  20664. "Auto-fill function."
  20665. ;; Check if auto-filling is meaningful.
  20666. (let ((fc (current-fill-column)))
  20667. (when (and fc (> (current-column) fc))
  20668. (let* ((fill-prefix (org-adaptive-fill-function))
  20669. ;; Enforce empty fill prefix, if required. Otherwise, it
  20670. ;; will be computed again.
  20671. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20672. (when fill-prefix (do-auto-fill))))))
  20673. (defun org-comment-line-break-function (&optional soft)
  20674. "Break line at point and indent, continuing comment if within one.
  20675. The inserted newline is marked hard if variable
  20676. `use-hard-newlines' is true, unless optional argument SOFT is
  20677. non-nil."
  20678. (if soft (insert-and-inherit ?\n) (newline 1))
  20679. (save-excursion (forward-char -1) (delete-horizontal-space))
  20680. (delete-horizontal-space)
  20681. (indent-to-left-margin)
  20682. (insert-before-markers-and-inherit fill-prefix))
  20683. ;;; Fixed Width Areas
  20684. (defun org-toggle-fixed-width ()
  20685. "Toggle fixed-width markup.
  20686. Add or remove fixed-width markup on current line, whenever it
  20687. makes sense. Return an error otherwise.
  20688. If a region is active and if it contains only fixed-width areas
  20689. or blank lines, remove all fixed-width markup in it. If the
  20690. region contains anything else, convert all non-fixed-width lines
  20691. to fixed-width ones.
  20692. Blank lines at the end of the region are ignored unless the
  20693. region only contains such lines."
  20694. (interactive)
  20695. (if (not (org-region-active-p))
  20696. ;; No region:
  20697. ;;
  20698. ;; Remove fixed width marker only in a fixed-with element.
  20699. ;;
  20700. ;; Add fixed width maker in paragraphs, in blank lines after
  20701. ;; elements or at the beginning of a headline or an inlinetask,
  20702. ;; and before any one-line elements (e.g., a clock).
  20703. (progn
  20704. (beginning-of-line)
  20705. (let* ((element (org-element-at-point))
  20706. (type (org-element-type element)))
  20707. (cond
  20708. ((and (eq type 'fixed-width)
  20709. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20710. (replace-match
  20711. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20712. ((and (memq type '(babel-call clock comment diary-sexp headline
  20713. horizontal-rule keyword paragraph
  20714. planning))
  20715. (<= (org-element-property :post-affiliated element) (point)))
  20716. (skip-chars-forward " \t")
  20717. (insert ": "))
  20718. ((and (looking-at-p "[ \t]*$")
  20719. (or (eq type 'inlinetask)
  20720. (save-excursion
  20721. (skip-chars-forward " \r\t\n")
  20722. (<= (org-element-property :end element) (point)))))
  20723. (delete-region (point) (line-end-position))
  20724. (org-indent-line)
  20725. (insert ": "))
  20726. (t (user-error "Cannot insert a fixed-width line here")))))
  20727. ;; Region active.
  20728. (let* ((begin (save-excursion
  20729. (goto-char (region-beginning))
  20730. (line-beginning-position)))
  20731. (end (copy-marker
  20732. (save-excursion
  20733. (goto-char (region-end))
  20734. (unless (eolp) (beginning-of-line))
  20735. (if (save-excursion (re-search-backward "\\S-" begin t))
  20736. (progn (skip-chars-backward " \r\t\n") (point))
  20737. (point)))))
  20738. (all-fixed-width-p
  20739. (catch 'not-all-p
  20740. (save-excursion
  20741. (goto-char begin)
  20742. (skip-chars-forward " \r\t\n")
  20743. (when (eobp) (throw 'not-all-p nil))
  20744. (while (< (point) end)
  20745. (let ((element (org-element-at-point)))
  20746. (if (eq (org-element-type element) 'fixed-width)
  20747. (goto-char (org-element-property :end element))
  20748. (throw 'not-all-p nil))))
  20749. t))))
  20750. (if all-fixed-width-p
  20751. (save-excursion
  20752. (goto-char begin)
  20753. (while (< (point) end)
  20754. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20755. (replace-match
  20756. "" nil nil nil
  20757. (if (= (line-end-position) (match-end 0)) 0 1)))
  20758. (forward-line)))
  20759. (let ((min-ind (point-max)))
  20760. ;; Find minimum indentation across all lines.
  20761. (save-excursion
  20762. (goto-char begin)
  20763. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20764. (setq min-ind 0)
  20765. (catch 'zerop
  20766. (while (< (point) end)
  20767. (unless (looking-at-p "[ \t]*$")
  20768. (let ((ind (org-get-indentation)))
  20769. (setq min-ind (min min-ind ind))
  20770. (when (zerop ind) (throw 'zerop t))))
  20771. (forward-line)))))
  20772. ;; Loop over all lines and add fixed-width markup everywhere
  20773. ;; but in fixed-width lines.
  20774. (save-excursion
  20775. (goto-char begin)
  20776. (while (< (point) end)
  20777. (cond
  20778. ((org-at-heading-p)
  20779. (insert ": ")
  20780. (forward-line)
  20781. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20782. (insert ":")
  20783. (forward-line)))
  20784. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20785. (let* ((element (org-element-at-point))
  20786. (element-end (org-element-property :end element)))
  20787. (if (eq (org-element-type element) 'fixed-width)
  20788. (progn (goto-char element-end)
  20789. (skip-chars-backward " \r\t\n")
  20790. (forward-line))
  20791. (let ((limit (min end element-end)))
  20792. (while (< (point) limit)
  20793. (org-move-to-column min-ind t)
  20794. (insert ": ")
  20795. (forward-line))))))
  20796. (t
  20797. (org-move-to-column min-ind t)
  20798. (insert ": ")
  20799. (forward-line)))))))
  20800. (set-marker end nil))))
  20801. ;;; Comments
  20802. ;; Org comments syntax is quite complex. It requires the entire line
  20803. ;; to be just a comment. Also, even with the right syntax at the
  20804. ;; beginning of line, some elements (e.g., verse-block or
  20805. ;; example-block) don't accept comments. Usual Emacs comment commands
  20806. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20807. ;; Org still relies on `comment-dwim', but cannot trust
  20808. ;; `comment-only-p'. So, `comment-region-function' and
  20809. ;; `uncomment-region-function' both point
  20810. ;; to`org-comment-or-uncomment-region'. Eventually,
  20811. ;; `org-insert-comment' takes care of insertion of comments at the
  20812. ;; beginning of line.
  20813. ;; `org-setup-comments-handling' install comments related variables
  20814. ;; during `org-mode' initialization.
  20815. (defun org-setup-comments-handling ()
  20816. (interactive)
  20817. (setq-local comment-use-syntax nil)
  20818. (setq-local comment-start "# ")
  20819. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20820. (setq-local comment-insert-comment-function 'org-insert-comment)
  20821. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20822. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20823. (defun org-insert-comment ()
  20824. "Insert an empty comment above current line.
  20825. If the line is empty, insert comment at its beginning. When
  20826. point is within a source block, comment according to the related
  20827. major mode."
  20828. (if (let ((element (org-element-at-point)))
  20829. (and (eq (org-element-type element) 'src-block)
  20830. (< (save-excursion
  20831. (goto-char (org-element-property :post-affiliated element))
  20832. (line-end-position))
  20833. (point))
  20834. (> (save-excursion
  20835. (goto-char (org-element-property :end element))
  20836. (skip-chars-backward " \r\t\n")
  20837. (line-beginning-position))
  20838. (point))))
  20839. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20840. (beginning-of-line)
  20841. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20842. (open-line 1))
  20843. (org-indent-line)
  20844. (insert "# ")))
  20845. (defvar comment-empty-lines) ; From newcomment.el.
  20846. (defun org-comment-or-uncomment-region (beg end &rest _)
  20847. "Comment or uncomment each non-blank line in the region.
  20848. Uncomment each non-blank line between BEG and END if it only
  20849. contains commented lines. Otherwise, comment them. If region is
  20850. strictly within a source block, use appropriate comment syntax."
  20851. (if (let ((element (org-element-at-point)))
  20852. (and (eq (org-element-type element) 'src-block)
  20853. (< (save-excursion
  20854. (goto-char (org-element-property :post-affiliated element))
  20855. (line-end-position))
  20856. beg)
  20857. (>= (save-excursion
  20858. (goto-char (org-element-property :end element))
  20859. (skip-chars-backward " \r\t\n")
  20860. (line-beginning-position))
  20861. end)))
  20862. ;; Translate region boundaries for the Org buffer to the source
  20863. ;; buffer.
  20864. (let ((offset (- end beg)))
  20865. (save-excursion
  20866. (goto-char beg)
  20867. (org-babel-do-in-edit-buffer
  20868. (comment-or-uncomment-region (point) (+ offset (point))))))
  20869. (save-restriction
  20870. ;; Restrict region
  20871. (narrow-to-region (save-excursion (goto-char beg)
  20872. (skip-chars-forward " \r\t\n" end)
  20873. (line-beginning-position))
  20874. (save-excursion (goto-char end)
  20875. (skip-chars-backward " \r\t\n" beg)
  20876. (line-end-position)))
  20877. (let ((uncommentp
  20878. ;; UNCOMMENTP is non-nil when every non blank line between
  20879. ;; BEG and END is a comment.
  20880. (save-excursion
  20881. (goto-char (point-min))
  20882. (while (and (not (eobp))
  20883. (let ((element (org-element-at-point)))
  20884. (and (eq (org-element-type element) 'comment)
  20885. (goto-char (min (point-max)
  20886. (org-element-property
  20887. :end element)))))))
  20888. (eobp))))
  20889. (if uncommentp
  20890. ;; Only blank lines and comments in region: uncomment it.
  20891. (save-excursion
  20892. (goto-char (point-min))
  20893. (while (not (eobp))
  20894. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20895. (replace-match "" nil nil nil 1))
  20896. (forward-line)))
  20897. ;; Comment each line in region.
  20898. (let ((min-indent (point-max)))
  20899. ;; First find the minimum indentation across all lines.
  20900. (save-excursion
  20901. (goto-char (point-min))
  20902. (while (and (not (eobp)) (not (zerop min-indent)))
  20903. (unless (looking-at "[ \t]*$")
  20904. (setq min-indent (min min-indent (current-indentation))))
  20905. (forward-line)))
  20906. ;; Then loop over all lines.
  20907. (save-excursion
  20908. (goto-char (point-min))
  20909. (while (not (eobp))
  20910. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20911. ;; Don't get fooled by invisible text (e.g. link path)
  20912. ;; when moving to column MIN-INDENT.
  20913. (let ((buffer-invisibility-spec nil))
  20914. (org-move-to-column min-indent t))
  20915. (insert comment-start))
  20916. (forward-line)))))))))
  20917. (defun org-comment-dwim (_arg)
  20918. "Call the comment command you mean.
  20919. Call `org-toggle-comment' if on a heading, otherwise call
  20920. `comment-dwim', within a source edit buffer if needed."
  20921. (interactive "*P")
  20922. (cond ((org-at-heading-p)
  20923. (call-interactively #'org-toggle-comment))
  20924. ((org-in-src-block-p)
  20925. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20926. (t (call-interactively #'comment-dwim))))
  20927. ;;; Timestamps API
  20928. ;; This section contains tools to operate on timestamp objects, as
  20929. ;; returned by, e.g. `org-element-context'.
  20930. (defun org-timestamp--to-internal-time (timestamp &optional end)
  20931. "Encode TIMESTAMP object into Emacs internal time.
  20932. Use end of date range or time range when END is non-nil."
  20933. (apply #'encode-time
  20934. (cons 0
  20935. (mapcar
  20936. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20937. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20938. '(:minute-start :hour-start :day-start :month-start
  20939. :year-start))))))
  20940. (defun org-timestamp-has-time-p (timestamp)
  20941. "Non-nil when TIMESTAMP has a time specified."
  20942. (org-element-property :hour-start timestamp))
  20943. (defun org-timestamp-format (timestamp format &optional end utc)
  20944. "Format a TIMESTAMP object into a string.
  20945. FORMAT is a format specifier to be passed to
  20946. `format-time-string'.
  20947. When optional argument END is non-nil, use end of date-range or
  20948. time-range, if possible.
  20949. When optional argument UTC is non-nil, time will be expressed as
  20950. Universal Time."
  20951. (format-time-string
  20952. format (org-timestamp--to-internal-time timestamp end)
  20953. (and utc t)))
  20954. (defun org-timestamp-split-range (timestamp &optional end)
  20955. "Extract a TIMESTAMP object from a date or time range.
  20956. END, when non-nil, means extract the end of the range.
  20957. Otherwise, extract its start.
  20958. Return a new timestamp object."
  20959. (let ((type (org-element-property :type timestamp)))
  20960. (if (memq type '(active inactive diary)) timestamp
  20961. (let ((split-ts (org-element-copy timestamp)))
  20962. ;; Set new type.
  20963. (org-element-put-property
  20964. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20965. ;; Copy start properties over end properties if END is
  20966. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20967. (let ((p-alist '((:minute-start . :minute-end)
  20968. (:hour-start . :hour-end)
  20969. (:day-start . :day-end)
  20970. (:month-start . :month-end)
  20971. (:year-start . :year-end))))
  20972. (dolist (p-cell p-alist)
  20973. (org-element-put-property
  20974. split-ts
  20975. (funcall (if end #'car #'cdr) p-cell)
  20976. (org-element-property
  20977. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20978. ;; Eventually refresh `:raw-value'.
  20979. (org-element-put-property split-ts :raw-value nil)
  20980. (org-element-put-property
  20981. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20982. (defun org-timestamp-translate (timestamp &optional boundary)
  20983. "Translate TIMESTAMP object to custom format.
  20984. Format string is defined in `org-time-stamp-custom-formats',
  20985. which see.
  20986. When optional argument BOUNDARY is non-nil, it is either the
  20987. symbol `start' or `end'. In this case, only translate the
  20988. starting or ending part of TIMESTAMP if it is a date or time
  20989. range. Otherwise, translate both parts.
  20990. Return timestamp as-is if `org-display-custom-times' is nil or if
  20991. it has a `diary' type."
  20992. (let ((type (org-element-property :type timestamp)))
  20993. (if (or (not org-display-custom-times) (eq type 'diary))
  20994. (org-element-interpret-data timestamp)
  20995. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20996. org-time-stamp-custom-formats)))
  20997. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20998. (concat (org-timestamp-format timestamp fmt)
  20999. "--"
  21000. (org-timestamp-format timestamp fmt t))
  21001. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21002. ;;; Other stuff.
  21003. (defvar reftex-docstruct-symbol)
  21004. (defvar org--rds)
  21005. (defun org-reftex-citation ()
  21006. "Use reftex-citation to insert a citation into the buffer.
  21007. This looks for a line like
  21008. #+BIBLIOGRAPHY: foo plain option:-d
  21009. and derives from it that foo.bib is the bibliography file relevant
  21010. for this document. It then installs the necessary environment for RefTeX
  21011. to work in this buffer and calls `reftex-citation' to insert a citation
  21012. into the buffer.
  21013. Export of such citations to both LaTeX and HTML is handled by the contributed
  21014. package ox-bibtex by Taru Karttunen."
  21015. (interactive)
  21016. (let ((reftex-docstruct-symbol 'org--rds)
  21017. org--rds bib)
  21018. (org-with-wide-buffer
  21019. (let ((case-fold-search t)
  21020. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21021. (if (not (save-excursion
  21022. (or (re-search-forward re nil t)
  21023. (re-search-backward re nil t))))
  21024. (user-error "No bibliography defined in file")
  21025. (setq bib (concat (match-string 1) ".bib")
  21026. org--rds (list (list 'bib bib))))))
  21027. (call-interactively 'reftex-citation)))
  21028. ;;;; Functions extending outline functionality
  21029. (defun org-beginning-of-line (&optional n)
  21030. "Go to the beginning of the current visible line.
  21031. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21032. tags on the first attempt, and only move to after the tags when
  21033. the cursor is already beyond the end of the headline.
  21034. With argument N not nil or 1, move forward N - 1 lines first."
  21035. (interactive "^p")
  21036. (let ((origin (point))
  21037. (special (pcase org-special-ctrl-a/e
  21038. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21039. deactivate-mark)
  21040. ;; First move to a visible line.
  21041. (if (bound-and-true-p visual-line-mode)
  21042. (beginning-of-visual-line n)
  21043. (move-beginning-of-line n)
  21044. ;; `move-beginning-of-line' may leave point after invisible
  21045. ;; characters if line starts with such of these (e.g., with
  21046. ;; a link at column 0). Really move to the beginning of the
  21047. ;; current visible line.
  21048. (beginning-of-line))
  21049. (cond
  21050. ;; No special behavior. Point is already at the beginning of
  21051. ;; a line, logical or visual.
  21052. ((not special))
  21053. ;; `beginning-of-visual-line' left point before logical beginning
  21054. ;; of line: point is at the beginning of a visual line. Bail
  21055. ;; out.
  21056. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21057. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21058. ;; At a headline, special position is before the title, but
  21059. ;; after any TODO keyword or priority cookie.
  21060. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21061. (line-end-position)))
  21062. (bol (point)))
  21063. (if (eq special 'reversed)
  21064. (when (and (= origin bol) (eq last-command this-command))
  21065. (goto-char refpos))
  21066. (when (or (> origin refpos) (= origin bol))
  21067. (goto-char refpos)))))
  21068. ((and (looking-at org-list-full-item-re)
  21069. (memq (org-element-type (save-match-data (org-element-at-point)))
  21070. '(item plain-list)))
  21071. ;; Set special position at first white space character after
  21072. ;; bullet, and check-box, if any.
  21073. (let ((after-bullet
  21074. (let ((box (match-end 3)))
  21075. (cond ((not box) (match-end 1))
  21076. ((eq (char-after box) ?\s) (1+ box))
  21077. (t box)))))
  21078. (if (eq special 'reversed)
  21079. (when (and (= (point) origin) (eq last-command this-command))
  21080. (goto-char after-bullet))
  21081. (when (or (> origin after-bullet) (= (point) origin))
  21082. (goto-char after-bullet)))))
  21083. ;; No special context. Point is already at beginning of line.
  21084. (t nil))))
  21085. (defun org-end-of-line (&optional n)
  21086. "Go to the end of the line, but before ellipsis, if any.
  21087. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21088. tags on the first attempt, and only move to after the tags when
  21089. the cursor is already beyond the end of the headline.
  21090. With argument N not nil or 1, move forward N - 1 lines first."
  21091. (interactive "^p")
  21092. (let ((origin (point))
  21093. (special (pcase org-special-ctrl-a/e
  21094. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21095. deactivate-mark)
  21096. ;; First move to a visible line.
  21097. (if (bound-and-true-p visual-line-mode)
  21098. (beginning-of-visual-line n)
  21099. (move-beginning-of-line n))
  21100. (cond
  21101. ;; At a headline, with tags.
  21102. ((and special
  21103. (save-excursion
  21104. (beginning-of-line)
  21105. (let ((case-fold-search nil))
  21106. (looking-at org-complex-heading-regexp)))
  21107. (match-end 5))
  21108. (let ((tags (save-excursion
  21109. (goto-char (match-beginning 5))
  21110. (skip-chars-backward " \t")
  21111. (point)))
  21112. (visual-end (and (bound-and-true-p visual-line-mode)
  21113. (save-excursion
  21114. (end-of-visual-line)
  21115. (point)))))
  21116. ;; If `end-of-visual-line' brings us before end of line or
  21117. ;; even tags, i.e., the headline spans over multiple visual
  21118. ;; lines, move there.
  21119. (cond ((and visual-end
  21120. (< visual-end tags)
  21121. (<= origin visual-end))
  21122. (goto-char visual-end))
  21123. ((eq special 'reversed)
  21124. (if (and (= origin (line-end-position))
  21125. (eq this-command last-command))
  21126. (goto-char tags)
  21127. (end-of-line)))
  21128. (t
  21129. (if (or (< origin tags) (= origin (line-end-position)))
  21130. (goto-char tags)
  21131. (end-of-line))))))
  21132. ((bound-and-true-p visual-line-mode)
  21133. (let ((bol (line-beginning-position)))
  21134. (end-of-visual-line)
  21135. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21136. ;; end of a line, backtrack and use `end-of-line' instead.
  21137. (when (/= bol (line-beginning-position))
  21138. (goto-char bol)
  21139. (end-of-line))))
  21140. (t (end-of-line)))))
  21141. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21142. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21143. (defun org-backward-sentence (&optional _arg)
  21144. "Go to beginning of sentence, or beginning of table field.
  21145. This will call `backward-sentence' or `org-table-beginning-of-field',
  21146. depending on context."
  21147. (interactive)
  21148. (let* ((element (org-element-at-point))
  21149. (contents-begin (org-element-property :contents-begin element))
  21150. (table (org-element-lineage element '(table) t)))
  21151. (if (and table
  21152. (> (point) contents-begin)
  21153. (<= (point) (org-element-property :contents-end table)))
  21154. (call-interactively #'org-table-beginning-of-field)
  21155. (save-restriction
  21156. (when (and contents-begin
  21157. (< (point-min) contents-begin)
  21158. (> (point) contents-begin))
  21159. (narrow-to-region contents-begin
  21160. (org-element-property :contents-end element)))
  21161. (call-interactively #'backward-sentence)))))
  21162. (defun org-forward-sentence (&optional _arg)
  21163. "Go to end of sentence, or end of table field.
  21164. This will call `forward-sentence' or `org-table-end-of-field',
  21165. depending on context."
  21166. (interactive)
  21167. (if (and (org-at-heading-p)
  21168. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21169. (save-restriction
  21170. (narrow-to-region (line-beginning-position) (line-end-position))
  21171. (call-interactively #'forward-sentence))
  21172. (let* ((element (org-element-at-point))
  21173. (contents-end (org-element-property :contents-end element))
  21174. (table (org-element-lineage element '(table) t)))
  21175. (if (and table
  21176. (>= (point) (org-element-property :contents-begin table))
  21177. (< (point) contents-end))
  21178. (call-interactively #'org-table-end-of-field)
  21179. (save-restriction
  21180. (when (and contents-end
  21181. (> (point-max) contents-end)
  21182. ;; Skip blank lines between elements.
  21183. (< (org-element-property :end element)
  21184. (save-excursion (goto-char contents-end)
  21185. (skip-chars-forward " \r\t\n"))))
  21186. (narrow-to-region (org-element-property :contents-begin element)
  21187. contents-end))
  21188. ;; End of heading is considered as the end of a sentence.
  21189. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  21190. (call-interactively #'forward-sentence)))))))
  21191. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21192. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21193. (defun org-kill-line (&optional _arg)
  21194. "Kill line, to tags or end of line."
  21195. (interactive)
  21196. (cond
  21197. ((or (not org-special-ctrl-k)
  21198. (bolp)
  21199. (not (org-at-heading-p)))
  21200. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21201. org-ctrl-k-protect-subtree
  21202. (or (eq org-ctrl-k-protect-subtree 'error)
  21203. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21204. (user-error "C-k aborted as it would kill a hidden subtree"))
  21205. (call-interactively
  21206. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21207. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21208. (kill-region (point) (match-beginning 1))
  21209. (org-set-tags nil t))
  21210. (t (kill-region (point) (point-at-eol)))))
  21211. (define-key org-mode-map "\C-k" 'org-kill-line)
  21212. (defun org-yank (&optional arg)
  21213. "Yank. If the kill is a subtree, treat it specially.
  21214. This command will look at the current kill and check if is a single
  21215. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21216. cursor is at the beginning of a line or after the stars of a currently
  21217. empty headline, then the yank is handled specially. How exactly depends
  21218. on the value of the following variables.
  21219. `org-yank-folded-subtrees'
  21220. By default, this variable is non-nil, which results in
  21221. subtree(s) being folded after insertion, except if doing so
  21222. would swallow text after the yanked text.
  21223. `org-yank-adjusted-subtrees'
  21224. When non-nil (the default value is nil), the subtree will be
  21225. promoted or demoted in order to fit into the local outline tree
  21226. structure, which means that the level will be adjusted so that it
  21227. becomes the smaller one of the two *visible* surrounding headings.
  21228. Any prefix to this command will cause `yank' to be called directly with
  21229. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21230. will just
  21231. plainly yank the text as it is.
  21232. \[1] The test checks if the first non-white line is a heading
  21233. and if there are no other headings with fewer stars."
  21234. (interactive "P")
  21235. (org-yank-generic 'yank arg))
  21236. (defun org-yank-generic (command arg)
  21237. "Perform some yank-like command.
  21238. This function implements the behavior described in the `org-yank'
  21239. documentation. However, it has been generalized to work for any
  21240. interactive command with similar behavior."
  21241. ;; pretend to be command COMMAND
  21242. (setq this-command command)
  21243. (if arg
  21244. (call-interactively command)
  21245. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21246. (and (org-kill-is-subtree-p)
  21247. (or (bolp)
  21248. (and (looking-at "[ \t]*$")
  21249. (string-match
  21250. "\\`\\*+\\'"
  21251. (buffer-substring (point-at-bol) (point)))))))
  21252. swallowp)
  21253. (cond
  21254. ((and subtreep org-yank-folded-subtrees)
  21255. (let ((beg (point))
  21256. end)
  21257. (if (and subtreep org-yank-adjusted-subtrees)
  21258. (org-paste-subtree nil nil 'for-yank)
  21259. (call-interactively command))
  21260. (setq end (point))
  21261. (goto-char beg)
  21262. (when (and (bolp) subtreep
  21263. (not (setq swallowp
  21264. (org-yank-folding-would-swallow-text beg end))))
  21265. (org-with-limited-levels
  21266. (or (looking-at org-outline-regexp)
  21267. (re-search-forward org-outline-regexp-bol end t))
  21268. (while (and (< (point) end) (looking-at org-outline-regexp))
  21269. (outline-hide-subtree)
  21270. (org-cycle-show-empty-lines 'folded)
  21271. (condition-case nil
  21272. (outline-forward-same-level 1)
  21273. (error (goto-char end))))))
  21274. (when swallowp
  21275. (message
  21276. "Inserted text not folded because that would swallow text"))
  21277. (goto-char end)
  21278. (skip-chars-forward " \t\n\r")
  21279. (beginning-of-line 1)
  21280. (push-mark beg 'nomsg)))
  21281. ((and subtreep org-yank-adjusted-subtrees)
  21282. (let ((beg (point-at-bol)))
  21283. (org-paste-subtree nil nil 'for-yank)
  21284. (push-mark beg 'nomsg)))
  21285. (t
  21286. (call-interactively command))))))
  21287. (defun org-yank-folding-would-swallow-text (beg end)
  21288. "Would hide-subtree at BEG swallow any text after END?"
  21289. (let (level)
  21290. (org-with-limited-levels
  21291. (save-excursion
  21292. (goto-char beg)
  21293. (when (or (looking-at org-outline-regexp)
  21294. (re-search-forward org-outline-regexp-bol end t))
  21295. (setq level (org-outline-level)))
  21296. (goto-char end)
  21297. (skip-chars-forward " \t\r\n\v\f")
  21298. (not (or (eobp)
  21299. (and (bolp) (looking-at-p org-outline-regexp)
  21300. (<= (org-outline-level) level))))))))
  21301. (define-key org-mode-map "\C-y" 'org-yank)
  21302. (defun org-back-to-heading (&optional invisible-ok)
  21303. "Call `outline-back-to-heading', but provide a better error message."
  21304. (condition-case nil
  21305. (outline-back-to-heading invisible-ok)
  21306. (error (error "Before first headline at position %d in buffer %s"
  21307. (point) (current-buffer)))))
  21308. (defun org-before-first-heading-p ()
  21309. "Before first heading?"
  21310. (save-excursion
  21311. (end-of-line)
  21312. (null (re-search-backward org-outline-regexp-bol nil t))))
  21313. (defun org-at-heading-p (&optional ignored)
  21314. (outline-on-heading-p t))
  21315. (defun org-in-commented-heading-p (&optional no-inheritance)
  21316. "Non-nil if point is under a commented heading.
  21317. This function also checks ancestors of the current headline,
  21318. unless optional argument NO-INHERITANCE is non-nil."
  21319. (cond
  21320. ((org-before-first-heading-p) nil)
  21321. ((let ((headline (nth 4 (org-heading-components))))
  21322. (and headline
  21323. (let ((case-fold-search nil))
  21324. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21325. headline)))))
  21326. (no-inheritance nil)
  21327. (t
  21328. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21329. (defun org-at-comment-p nil
  21330. "Is cursor in a commented line?"
  21331. (save-excursion
  21332. (save-match-data
  21333. (beginning-of-line)
  21334. (looking-at "^[ \t]*# "))))
  21335. (defun org-at-drawer-p nil
  21336. "Is cursor at a drawer keyword?"
  21337. (save-excursion
  21338. (move-beginning-of-line 1)
  21339. (looking-at org-drawer-regexp)))
  21340. (defun org-at-block-p nil
  21341. "Is cursor at a block keyword?"
  21342. (save-excursion
  21343. (move-beginning-of-line 1)
  21344. (looking-at org-block-regexp)))
  21345. (defun org-point-at-end-of-empty-headline ()
  21346. "If point is at the end of an empty headline, return t, else nil.
  21347. If the heading only contains a TODO keyword, it is still still considered
  21348. empty."
  21349. (let ((case-fold-search nil))
  21350. (and (looking-at "[ \t]*$")
  21351. org-todo-line-regexp
  21352. (save-excursion
  21353. (beginning-of-line)
  21354. (looking-at org-todo-line-regexp)
  21355. (string= (match-string 3) "")))))
  21356. (defun org-at-heading-or-item-p ()
  21357. (or (org-at-heading-p) (org-at-item-p)))
  21358. (defun org-at-target-p ()
  21359. (or (org-in-regexp org-radio-target-regexp)
  21360. (org-in-regexp org-target-regexp)))
  21361. ;; Compatibility alias with Org versions < 7.8.03
  21362. (defalias 'org-on-target-p 'org-at-target-p)
  21363. (defun org-up-heading-all (arg)
  21364. "Move to the heading line of which the present line is a subheading.
  21365. This function considers both visible and invisible heading lines.
  21366. With argument, move up ARG levels."
  21367. (outline-up-heading arg t))
  21368. (defun org-up-heading-safe ()
  21369. "Move to the heading line of which the present line is a subheading.
  21370. This version will not throw an error. It will return the level of the
  21371. headline found, or nil if no higher level is found.
  21372. Also, this function will be a lot faster than `outline-up-heading',
  21373. because it relies on stars being the outline starters. This can really
  21374. make a significant difference in outlines with very many siblings."
  21375. (when (ignore-errors (org-back-to-heading t))
  21376. (let ((level-up (1- (funcall outline-level))))
  21377. (and (> level-up 0)
  21378. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21379. (funcall outline-level)))))
  21380. (defun org-first-sibling-p ()
  21381. "Is this heading the first child of its parents?"
  21382. (interactive)
  21383. (let ((re org-outline-regexp-bol)
  21384. level l)
  21385. (unless (org-at-heading-p t)
  21386. (user-error "Not at a heading"))
  21387. (setq level (funcall outline-level))
  21388. (save-excursion
  21389. (if (not (re-search-backward re nil t))
  21390. t
  21391. (setq l (funcall outline-level))
  21392. (< l level)))))
  21393. (defun org-goto-sibling (&optional previous)
  21394. "Goto the next sibling, even if it is invisible.
  21395. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21396. when a sibling was found. When none is found, return nil and don't
  21397. move point."
  21398. (let ((fun (if previous 're-search-backward 're-search-forward))
  21399. (pos (point))
  21400. (re org-outline-regexp-bol)
  21401. level l)
  21402. (when (ignore-errors (org-back-to-heading t))
  21403. (setq level (funcall outline-level))
  21404. (catch 'exit
  21405. (or previous (forward-char 1))
  21406. (while (funcall fun re nil t)
  21407. (setq l (funcall outline-level))
  21408. (when (< l level) (goto-char pos) (throw 'exit nil))
  21409. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21410. (goto-char pos)
  21411. nil))))
  21412. (defun org-show-siblings ()
  21413. "Show all siblings of the current headline."
  21414. (save-excursion
  21415. (while (org-goto-sibling) (org-flag-heading nil)))
  21416. (save-excursion
  21417. (while (org-goto-sibling 'previous)
  21418. (org-flag-heading nil))))
  21419. (defun org-goto-first-child ()
  21420. "Goto the first child, even if it is invisible.
  21421. Return t when a child was found. Otherwise don't move point and
  21422. return nil."
  21423. (let (level (pos (point)) (re org-outline-regexp-bol))
  21424. (when (ignore-errors (org-back-to-heading t))
  21425. (setq level (outline-level))
  21426. (forward-char 1)
  21427. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21428. (progn (goto-char (match-beginning 0)) t)
  21429. (goto-char pos) nil))))
  21430. (defun org-show-hidden-entry ()
  21431. "Show an entry where even the heading is hidden."
  21432. (save-excursion
  21433. (org-show-entry)))
  21434. (defun org-flag-heading (flag &optional entry)
  21435. "Flag the current heading. FLAG non-nil means make invisible.
  21436. When ENTRY is non-nil, show the entire entry."
  21437. (save-excursion
  21438. (org-back-to-heading t)
  21439. ;; Check if we should show the entire entry
  21440. (if entry
  21441. (progn
  21442. (org-show-entry)
  21443. (save-excursion
  21444. (and (outline-next-heading)
  21445. (org-flag-heading nil))))
  21446. (outline-flag-region (max (point-min) (1- (point)))
  21447. (save-excursion (outline-end-of-heading) (point))
  21448. flag))))
  21449. (defun org-get-next-sibling ()
  21450. "Move to next heading of the same level, and return point.
  21451. If there is no such heading, return nil.
  21452. This is like outline-next-sibling, but invisible headings are ok."
  21453. (let ((level (funcall outline-level)))
  21454. (outline-next-heading)
  21455. (while (and (not (eobp)) (> (funcall outline-level) level))
  21456. (outline-next-heading))
  21457. (unless (or (eobp) (< (funcall outline-level) level))
  21458. (point))))
  21459. (defun org-get-last-sibling ()
  21460. "Move to previous heading of the same level, and return point.
  21461. If there is no such heading, return nil."
  21462. (let ((opoint (point))
  21463. (level (funcall outline-level)))
  21464. (outline-previous-heading)
  21465. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21466. (while (and (> (funcall outline-level) level)
  21467. (not (bobp)))
  21468. (outline-previous-heading))
  21469. (unless (< (funcall outline-level) level)
  21470. (point)))))
  21471. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21472. "Goto to the end of a subtree."
  21473. ;; This contains an exact copy of the original function, but it uses
  21474. ;; `org-back-to-heading', to make it work also in invisible
  21475. ;; trees. And is uses an invisible-ok argument.
  21476. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21477. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21478. ;; with many children and grandchildren etc, this can be much faster
  21479. ;; than the outline version.
  21480. (org-back-to-heading invisible-ok)
  21481. (let ((first t)
  21482. (level (funcall outline-level)))
  21483. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21484. ;; A true heading (not a plain list item), in Org
  21485. ;; This means we can easily find the end by looking
  21486. ;; only for the right number of stars. Using a regexp to do
  21487. ;; this is so much faster than using a Lisp loop.
  21488. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21489. (forward-char 1)
  21490. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21491. ;; something else, do it the slow way
  21492. (while (and (not (eobp))
  21493. (or first (> (funcall outline-level) level)))
  21494. (setq first nil)
  21495. (outline-next-heading)))
  21496. (unless to-heading
  21497. (when (memq (preceding-char) '(?\n ?\^M))
  21498. ;; Go to end of line before heading
  21499. (forward-char -1)
  21500. (when (memq (preceding-char) '(?\n ?\^M))
  21501. ;; leave blank line before heading
  21502. (forward-char -1)))))
  21503. (point))
  21504. (defun org-end-of-meta-data (&optional full)
  21505. "Skip planning line and properties drawer in current entry.
  21506. When optional argument FULL is non-nil, also skip empty lines,
  21507. clocking lines and regular drawers at the beginning of the
  21508. entry."
  21509. (org-back-to-heading t)
  21510. (forward-line)
  21511. (when (looking-at-p org-planning-line-re) (forward-line))
  21512. (when (looking-at org-property-drawer-re)
  21513. (goto-char (match-end 0))
  21514. (forward-line))
  21515. (when (and full (not (org-at-heading-p)))
  21516. (catch 'exit
  21517. (let ((end (save-excursion (outline-next-heading) (point)))
  21518. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21519. (while (not (eobp))
  21520. (cond ((looking-at-p org-drawer-regexp)
  21521. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21522. (forward-line)
  21523. (throw 'exit t)))
  21524. ((looking-at-p re) (forward-line))
  21525. (t (throw 'exit t))))))))
  21526. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21527. "Move forward to the ARG'th subheading at same level as this one.
  21528. Stop at the first and last subheadings of a superior heading.
  21529. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21530. non-nil it will also look at invisible ones."
  21531. (interactive "p")
  21532. (let ((backward? (and arg (< arg 0))))
  21533. (if (org-before-first-heading-p)
  21534. (if backward? (goto-char (point-min)) (outline-next-heading))
  21535. (org-back-to-heading invisible-ok)
  21536. (unless backward? (end-of-line)) ;do not match current headline
  21537. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21538. (f (if backward? #'re-search-backward #'re-search-forward))
  21539. (count (if arg (abs arg) 1))
  21540. (result (point)))
  21541. (while (and (> count 0)
  21542. (funcall f org-outline-regexp-bol nil 'move))
  21543. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21544. (cond ((< l level) (setq count 0))
  21545. ((and (= l level)
  21546. (or invisible-ok
  21547. (not (org-invisible-p
  21548. (line-beginning-position)))))
  21549. (cl-decf count)
  21550. (when (= l level) (setq result (point)))))))
  21551. (goto-char result))
  21552. (beginning-of-line))))
  21553. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21554. "Move backward to the ARG'th subheading at same level as this one.
  21555. Stop at the first and last subheadings of a superior heading."
  21556. (interactive "p")
  21557. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21558. (defun org-next-visible-heading (arg)
  21559. "Move to the next visible heading.
  21560. This function wraps `outline-next-visible-heading' with
  21561. `org-with-limited-levels' in order to skip over inline tasks and
  21562. respect customization of `org-odd-levels-only'."
  21563. (interactive "p")
  21564. (org-with-limited-levels
  21565. (outline-next-visible-heading arg)))
  21566. (defun org-previous-visible-heading (arg)
  21567. "Move to the previous visible heading.
  21568. This function wraps `outline-previous-visible-heading' with
  21569. `org-with-limited-levels' in order to skip over inline tasks and
  21570. respect customization of `org-odd-levels-only'."
  21571. (interactive "p")
  21572. (org-with-limited-levels
  21573. (outline-previous-visible-heading arg)))
  21574. (defun org-next-block (arg &optional backward block-regexp)
  21575. "Jump to the next block.
  21576. With a prefix argument ARG, jump forward ARG many blocks.
  21577. When BACKWARD is non-nil, jump to the previous block.
  21578. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  21579. Match data is set according to this regexp when the function
  21580. returns.
  21581. Return point at beginning of the opening line of found block.
  21582. Throw an error if no block is found."
  21583. (interactive "p")
  21584. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  21585. (case-fold-search t)
  21586. (search-fn (if backward #'re-search-backward #'re-search-forward))
  21587. (count (or arg 1))
  21588. (origin (point))
  21589. last-element)
  21590. (if backward (beginning-of-line) (end-of-line))
  21591. (while (and (> count 0) (funcall search-fn re nil t))
  21592. (let ((element (save-excursion
  21593. (goto-char (match-beginning 0))
  21594. (save-match-data (org-element-at-point)))))
  21595. (when (and (memq (org-element-type element)
  21596. '(center-block comment-block dynamic-block
  21597. example-block export-block quote-block
  21598. special-block src-block verse-block))
  21599. (<= (match-beginning 0)
  21600. (org-element-property :post-affiliated element)))
  21601. (setq last-element element)
  21602. (cl-decf count))))
  21603. (if (= count 0)
  21604. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  21605. (save-match-data (org-show-context)))
  21606. (goto-char origin)
  21607. (user-error "No %s code blocks" (if backward "previous" "further")))))
  21608. (defun org-previous-block (arg &optional block-regexp)
  21609. "Jump to the previous block.
  21610. With a prefix argument ARG, jump backward ARG many source blocks.
  21611. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  21612. (interactive "p")
  21613. (org-next-block arg t block-regexp))
  21614. (defun org-forward-paragraph ()
  21615. "Move forward to beginning of next paragraph or equivalent.
  21616. The function moves point to the beginning of the next visible
  21617. structural element, which can be a paragraph, a table, a list
  21618. item, etc. It also provides some special moves for convenience:
  21619. - On an affiliated keyword, jump to the beginning of the
  21620. relative element.
  21621. - On an item or a footnote definition, move to the second
  21622. element inside, if any.
  21623. - On a table or a property drawer, jump after it.
  21624. - On a verse or source block, stop after blank lines."
  21625. (interactive)
  21626. (unless (eobp)
  21627. (let* ((deactivate-mark nil)
  21628. (element (org-element-at-point))
  21629. (type (org-element-type element))
  21630. (post-affiliated (org-element-property :post-affiliated element))
  21631. (contents-begin (org-element-property :contents-begin element))
  21632. (contents-end (org-element-property :contents-end element))
  21633. (end (let ((end (org-element-property :end element)) (parent element))
  21634. (while (and (setq parent (org-element-property :parent parent))
  21635. (= (org-element-property :contents-end parent) end))
  21636. (setq end (org-element-property :end parent)))
  21637. end)))
  21638. (cond ((not element)
  21639. (skip-chars-forward " \r\t\n")
  21640. (or (eobp) (beginning-of-line)))
  21641. ;; On affiliated keywords, move to element's beginning.
  21642. ((< (point) post-affiliated)
  21643. (goto-char post-affiliated))
  21644. ;; At a table row, move to the end of the table. Similarly,
  21645. ;; at a node property, move to the end of the property
  21646. ;; drawer.
  21647. ((memq type '(node-property table-row))
  21648. (goto-char (org-element-property
  21649. :end (org-element-property :parent element))))
  21650. ((memq type '(property-drawer table)) (goto-char end))
  21651. ;; Consider blank lines as separators in verse and source
  21652. ;; blocks to ease editing.
  21653. ((memq type '(src-block verse-block))
  21654. (when (eq type 'src-block)
  21655. (setq contents-end
  21656. (save-excursion (goto-char end)
  21657. (skip-chars-backward " \r\t\n")
  21658. (line-beginning-position))))
  21659. (beginning-of-line)
  21660. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21661. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21662. (goto-char end)
  21663. (skip-chars-forward " \r\t\n")
  21664. (if (= (point) contents-end) (goto-char end)
  21665. (beginning-of-line))))
  21666. ;; With no contents, just skip element.
  21667. ((not contents-begin) (goto-char end))
  21668. ;; If contents are invisible, skip the element altogether.
  21669. ((org-invisible-p (line-end-position))
  21670. (cl-case type
  21671. (headline
  21672. (org-with-limited-levels (outline-next-visible-heading 1)))
  21673. ;; At a plain list, make sure we move to the next item
  21674. ;; instead of skipping the whole list.
  21675. (plain-list (forward-char)
  21676. (org-forward-paragraph))
  21677. (otherwise (goto-char end))))
  21678. ((>= (point) contents-end) (goto-char end))
  21679. ((>= (point) contents-begin)
  21680. ;; This can only happen on paragraphs and plain lists.
  21681. (cl-case type
  21682. (paragraph (goto-char end))
  21683. ;; At a plain list, try to move to second element in
  21684. ;; first item, if possible.
  21685. (plain-list (end-of-line)
  21686. (org-forward-paragraph))))
  21687. ;; When contents start on the middle of a line (e.g. in
  21688. ;; items and footnote definitions), try to reach first
  21689. ;; element starting after current line.
  21690. ((> (line-end-position) contents-begin)
  21691. (end-of-line)
  21692. (org-forward-paragraph))
  21693. (t (goto-char contents-begin))))))
  21694. (defun org-backward-paragraph ()
  21695. "Move backward to start of previous paragraph or equivalent.
  21696. The function moves point to the beginning of the current
  21697. structural element, which can be a paragraph, a table, a list
  21698. item, etc., or to the beginning of the previous visible one if
  21699. point is already there. It also provides some special moves for
  21700. convenience:
  21701. - On an affiliated keyword, jump to the first one.
  21702. - On a table or a property drawer, move to its beginning.
  21703. - On comment, example, export, src and verse blocks, stop
  21704. before blank lines."
  21705. (interactive)
  21706. (unless (bobp)
  21707. (let* ((deactivate-mark nil)
  21708. (element (org-element-at-point))
  21709. (type (org-element-type element))
  21710. (contents-end (org-element-property :contents-end element))
  21711. (post-affiliated (org-element-property :post-affiliated element))
  21712. (begin (org-element-property :begin element))
  21713. (special? ;blocks handled specially
  21714. (memq type '(comment-block example-block export-block src-block
  21715. verse-block)))
  21716. (contents-begin
  21717. (if special?
  21718. ;; These types have no proper contents. Fake line
  21719. ;; below the block opening line as contents beginning.
  21720. (save-excursion (goto-char begin) (line-beginning-position 2))
  21721. (org-element-property :contents-begin element))))
  21722. (cond
  21723. ((not element) (goto-char (point-min)))
  21724. ((= (point) begin)
  21725. (backward-char)
  21726. (org-backward-paragraph))
  21727. ((<= (point) post-affiliated) (goto-char begin))
  21728. ;; Special behavior: on a table or a property drawer, move to
  21729. ;; its beginning.
  21730. ((memq type '(node-property table-row))
  21731. (goto-char (org-element-property
  21732. :post-affiliated (org-element-property :parent element))))
  21733. (special?
  21734. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21735. ;; Inside a verse block, see blank lines as paragraph
  21736. ;; separators.
  21737. (let ((origin (point)))
  21738. (skip-chars-backward " \r\t\n" contents-begin)
  21739. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21740. (skip-chars-forward " \r\t\n" origin)
  21741. (if (= (point) origin) (goto-char contents-begin)
  21742. (beginning-of-line))))))
  21743. ((eq type 'paragraph) (goto-char contents-begin)
  21744. ;; When at first paragraph in an item or a footnote definition,
  21745. ;; move directly to beginning of line.
  21746. (let ((parent-contents
  21747. (org-element-property
  21748. :contents-begin (org-element-property :parent element))))
  21749. (when (and parent-contents (= parent-contents contents-begin))
  21750. (beginning-of-line))))
  21751. ;; At the end of a greater element, move to the beginning of
  21752. ;; the last element within.
  21753. ((and contents-end (>= (point) contents-end))
  21754. (goto-char (1- contents-end))
  21755. (org-backward-paragraph))
  21756. (t (goto-char (or post-affiliated begin))))
  21757. ;; Ensure we never leave point invisible.
  21758. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21759. (defun org-forward-element ()
  21760. "Move forward by one element.
  21761. Move to the next element at the same level, when possible."
  21762. (interactive)
  21763. (cond ((eobp) (user-error "Cannot move further down"))
  21764. ((org-with-limited-levels (org-at-heading-p))
  21765. (let ((origin (point)))
  21766. (goto-char (org-end-of-subtree nil t))
  21767. (unless (org-with-limited-levels (org-at-heading-p))
  21768. (goto-char origin)
  21769. (user-error "Cannot move further down"))))
  21770. (t
  21771. (let* ((elem (org-element-at-point))
  21772. (end (org-element-property :end elem))
  21773. (parent (org-element-property :parent elem)))
  21774. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21775. (goto-char (org-element-property :end parent)))
  21776. ((integer-or-marker-p end) (goto-char end))
  21777. (t (message "No element at point")))))))
  21778. (defun org-backward-element ()
  21779. "Move backward by one element.
  21780. Move to the previous element at the same level, when possible."
  21781. (interactive)
  21782. (cond ((bobp) (user-error "Cannot move further up"))
  21783. ((org-with-limited-levels (org-at-heading-p))
  21784. ;; At a headline, move to the previous one, if any, or stay
  21785. ;; here.
  21786. (let ((origin (point)))
  21787. (org-with-limited-levels (org-backward-heading-same-level 1))
  21788. ;; When current headline has no sibling above, move to its
  21789. ;; parent.
  21790. (when (= (point) origin)
  21791. (or (org-with-limited-levels (org-up-heading-safe))
  21792. (progn (goto-char origin)
  21793. (user-error "Cannot move further up"))))))
  21794. (t
  21795. (let* ((elem (org-element-at-point))
  21796. (beg (org-element-property :begin elem)))
  21797. (cond
  21798. ;; Move to beginning of current element if point isn't
  21799. ;; there already.
  21800. ((null beg) (message "No element at point"))
  21801. ((/= (point) beg) (goto-char beg))
  21802. (t (goto-char beg)
  21803. (skip-chars-backward " \r\t\n")
  21804. (unless (bobp)
  21805. (let ((prev (org-element-at-point)))
  21806. (goto-char (org-element-property :begin prev))
  21807. (while (and (setq prev (org-element-property :parent prev))
  21808. (<= (org-element-property :end prev) beg))
  21809. (goto-char (org-element-property :begin prev)))))))))))
  21810. (defun org-up-element ()
  21811. "Move to upper element."
  21812. (interactive)
  21813. (if (org-with-limited-levels (org-at-heading-p))
  21814. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21815. (let* ((elem (org-element-at-point))
  21816. (parent (org-element-property :parent elem)))
  21817. (if parent (goto-char (org-element-property :begin parent))
  21818. (if (org-with-limited-levels (org-before-first-heading-p))
  21819. (user-error "No surrounding element")
  21820. (org-with-limited-levels (org-back-to-heading)))))))
  21821. (defun org-down-element ()
  21822. "Move to inner element."
  21823. (interactive)
  21824. (let ((element (org-element-at-point)))
  21825. (cond
  21826. ((memq (org-element-type element) '(plain-list table))
  21827. (goto-char (org-element-property :contents-begin element))
  21828. (forward-char))
  21829. ((memq (org-element-type element) org-element-greater-elements)
  21830. ;; If contents are hidden, first disclose them.
  21831. (when (org-invisible-p (line-end-position)) (org-cycle))
  21832. (goto-char (or (org-element-property :contents-begin element)
  21833. (user-error "No content for this element"))))
  21834. (t (user-error "No inner element")))))
  21835. (defun org-drag-element-backward ()
  21836. "Move backward element at point."
  21837. (interactive)
  21838. (let ((elem (or (org-element-at-point)
  21839. (user-error "No element at point"))))
  21840. (if (eq (org-element-type elem) 'headline)
  21841. ;; Preserve point when moving a whole tree, even if point was
  21842. ;; on blank lines below the headline.
  21843. (let ((offset (skip-chars-backward " \t\n")))
  21844. (unwind-protect (org-move-subtree-up)
  21845. (forward-char (- offset))))
  21846. (let ((prev-elem
  21847. (save-excursion
  21848. (goto-char (org-element-property :begin elem))
  21849. (skip-chars-backward " \r\t\n")
  21850. (unless (bobp)
  21851. (let* ((beg (org-element-property :begin elem))
  21852. (prev (org-element-at-point))
  21853. (up prev))
  21854. (while (and (setq up (org-element-property :parent up))
  21855. (<= (org-element-property :end up) beg))
  21856. (setq prev up))
  21857. prev)))))
  21858. ;; Error out if no previous element or previous element is
  21859. ;; a parent of the current one.
  21860. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21861. (user-error "Cannot drag element backward")
  21862. (let ((pos (point)))
  21863. (org-element-swap-A-B prev-elem elem)
  21864. (goto-char (+ (org-element-property :begin prev-elem)
  21865. (- pos (org-element-property :begin elem))))))))))
  21866. (defun org-drag-element-forward ()
  21867. "Move forward element at point."
  21868. (interactive)
  21869. (let* ((pos (point))
  21870. (elem (or (org-element-at-point)
  21871. (user-error "No element at point"))))
  21872. (when (= (point-max) (org-element-property :end elem))
  21873. (user-error "Cannot drag element forward"))
  21874. (goto-char (org-element-property :end elem))
  21875. (let ((next-elem (org-element-at-point)))
  21876. (when (or (org-element-nested-p elem next-elem)
  21877. (and (eq (org-element-type next-elem) 'headline)
  21878. (not (eq (org-element-type elem) 'headline))))
  21879. (goto-char pos)
  21880. (user-error "Cannot drag element forward"))
  21881. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21882. ;; body's length (without final blanks) and by the length of
  21883. ;; blanks between ELEM and NEXT-ELEM.
  21884. (let ((size-next (- (save-excursion
  21885. (goto-char (org-element-property :end next-elem))
  21886. (skip-chars-backward " \r\t\n")
  21887. (forward-line)
  21888. ;; Small correction if buffer doesn't end
  21889. ;; with a newline character.
  21890. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21891. (org-element-property :begin next-elem)))
  21892. (size-blank (- (org-element-property :end elem)
  21893. (save-excursion
  21894. (goto-char (org-element-property :end elem))
  21895. (skip-chars-backward " \r\t\n")
  21896. (forward-line)
  21897. (point)))))
  21898. (org-element-swap-A-B elem next-elem)
  21899. (goto-char (+ pos size-next size-blank))))))
  21900. (defun org-drag-line-forward (arg)
  21901. "Drag the line at point ARG lines forward."
  21902. (interactive "p")
  21903. (dotimes (_ (abs arg))
  21904. (let ((c (current-column)))
  21905. (if (< 0 arg)
  21906. (progn
  21907. (beginning-of-line 2)
  21908. (transpose-lines 1)
  21909. (beginning-of-line 0))
  21910. (transpose-lines 1)
  21911. (beginning-of-line -1))
  21912. (org-move-to-column c))))
  21913. (defun org-drag-line-backward (arg)
  21914. "Drag the line at point ARG lines backward."
  21915. (interactive "p")
  21916. (org-drag-line-forward (- arg)))
  21917. (defun org-mark-element ()
  21918. "Put point at beginning of this element, mark at end.
  21919. Interactively, if this command is repeated or (in Transient Mark
  21920. mode) if the mark is active, it marks the next element after the
  21921. ones already marked."
  21922. (interactive)
  21923. (let (deactivate-mark)
  21924. (if (and (called-interactively-p 'any)
  21925. (or (and (eq last-command this-command) (mark t))
  21926. (and transient-mark-mode mark-active)))
  21927. (set-mark
  21928. (save-excursion
  21929. (goto-char (mark))
  21930. (goto-char (org-element-property :end (org-element-at-point)))))
  21931. (let ((element (org-element-at-point)))
  21932. (end-of-line)
  21933. (push-mark (org-element-property :end element) t t)
  21934. (goto-char (org-element-property :begin element))))))
  21935. (defun org-narrow-to-element ()
  21936. "Narrow buffer to current element."
  21937. (interactive)
  21938. (let ((elem (org-element-at-point)))
  21939. (cond
  21940. ((eq (car elem) 'headline)
  21941. (narrow-to-region
  21942. (org-element-property :begin elem)
  21943. (org-element-property :end elem)))
  21944. ((memq (car elem) org-element-greater-elements)
  21945. (narrow-to-region
  21946. (org-element-property :contents-begin elem)
  21947. (org-element-property :contents-end elem)))
  21948. (t
  21949. (narrow-to-region
  21950. (org-element-property :begin elem)
  21951. (org-element-property :end elem))))))
  21952. (defun org-transpose-element ()
  21953. "Transpose current and previous elements, keeping blank lines between.
  21954. Point is moved after both elements."
  21955. (interactive)
  21956. (org-skip-whitespace)
  21957. (let ((end (org-element-property :end (org-element-at-point))))
  21958. (org-drag-element-backward)
  21959. (goto-char end)))
  21960. (defun org-unindent-buffer ()
  21961. "Un-indent the visible part of the buffer.
  21962. Relative indentation (between items, inside blocks, etc.) isn't
  21963. modified."
  21964. (interactive)
  21965. (unless (eq major-mode 'org-mode)
  21966. (user-error "Cannot un-indent a buffer not in Org mode"))
  21967. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21968. (unindent-tree
  21969. (lambda (contents)
  21970. (dolist (element (reverse contents))
  21971. (if (memq (org-element-type element) '(headline section))
  21972. (funcall unindent-tree (org-element-contents element))
  21973. (save-excursion
  21974. (save-restriction
  21975. (narrow-to-region
  21976. (org-element-property :begin element)
  21977. (org-element-property :end element))
  21978. (org-do-remove-indentation))))))))
  21979. (funcall unindent-tree (org-element-contents parse-tree))))
  21980. (defun org-show-children (&optional level)
  21981. "Show all direct subheadings of this heading.
  21982. Prefix arg LEVEL is how many levels below the current level
  21983. should be shown. Default is enough to cause the following
  21984. heading to appear."
  21985. (interactive "p")
  21986. ;; If `orgstruct-mode' is active, use the slower version.
  21987. (if orgstruct-mode (call-interactively #'outline-show-children)
  21988. (save-excursion
  21989. (org-back-to-heading t)
  21990. (let* ((current-level (funcall outline-level))
  21991. (max-level (org-get-valid-level
  21992. current-level
  21993. (if level (prefix-numeric-value level) 1)))
  21994. (end (save-excursion (org-end-of-subtree t t)))
  21995. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  21996. (past-first-child nil)
  21997. ;; Make sure to skip inlinetasks.
  21998. (re (format regexp-fmt
  21999. current-level
  22000. (cond
  22001. ((not (featurep 'org-inlinetask)) "")
  22002. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22003. 3))
  22004. (t (1- org-inlinetask-min-level))))))
  22005. ;; Display parent heading.
  22006. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22007. (forward-line)
  22008. ;; Display children. First child may be deeper than expected
  22009. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22010. ;; MAX-LEVEL accordingly.
  22011. (while (re-search-forward re end t)
  22012. (unless past-first-child
  22013. (setq re (format regexp-fmt
  22014. current-level
  22015. (max (funcall outline-level) max-level)))
  22016. (setq past-first-child t))
  22017. (outline-flag-region
  22018. (line-end-position 0) (line-end-position) nil))))))
  22019. (defun org-show-subtree ()
  22020. "Show everything after this heading at deeper levels."
  22021. (interactive)
  22022. (outline-flag-region
  22023. (point)
  22024. (save-excursion
  22025. (org-end-of-subtree t t))
  22026. nil))
  22027. (defun org-show-entry ()
  22028. "Show the body directly following this heading.
  22029. Show the heading too, if it is currently invisible."
  22030. (interactive)
  22031. (save-excursion
  22032. (ignore-errors
  22033. (org-back-to-heading t)
  22034. (outline-flag-region
  22035. (max (point-min) (1- (point)))
  22036. (save-excursion
  22037. (if (re-search-forward
  22038. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22039. (match-beginning 1)
  22040. (point-max)))
  22041. nil)
  22042. (org-cycle-hide-drawers 'children))))
  22043. (defun org-make-options-regexp (kwds &optional extra)
  22044. "Make a regular expression for keyword lines.
  22045. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22046. when non-nil, is a regexp matching keywords names."
  22047. (concat "^[ \t]*#\\+\\("
  22048. (regexp-opt kwds)
  22049. (and extra (concat (and kwds "\\|") extra))
  22050. "\\):[ \t]*\\(.*\\)"))
  22051. ;;;; Finish up
  22052. (provide 'org)
  22053. (run-hooks 'org-load-hook)
  22054. ;;; org.el ends here