org.el 911 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078
  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 " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  607. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  608. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  609. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  610. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  611. (const :tag "C collector: Collect properties into tables" org-collector)
  612. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  613. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  614. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  615. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  616. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  617. (const :tag "C eval: Include command output as text" org-eval)
  618. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  619. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  620. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  621. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  622. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  623. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  624. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  625. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  626. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  627. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  628. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  629. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  630. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  631. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  632. (const :tag "C registry: A registry for Org links" org-registry)
  633. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  634. (const :tag "C secretary: Team management with org-mode" org-secretary)
  635. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  636. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  637. (const :tag "C track: Keep up with Org mode development" org-track)
  638. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  639. (const :tag "C vm: Links to VM folders/messages" org-vm)
  640. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  641. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  642. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  643. (defvar org-export-registered-backends) ; From ox.el.
  644. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  645. (declare-function org-export-backend-name "ox" (backend) t)
  646. (defcustom org-export-backends '(ascii html icalendar latex odt)
  647. "List of export back-ends that should be always available.
  648. If a description starts with <C>, the file is not part of Emacs
  649. and loading it will require that you have downloaded and properly
  650. installed the Org mode distribution.
  651. Unlike to `org-modules', libraries in this list will not be
  652. loaded along with Org, but only once the export framework is
  653. needed.
  654. This variable needs to be set before org.el is loaded. If you
  655. need to make a change while Emacs is running, use the customize
  656. interface or run the following code, where VAL stands for the new
  657. value of the variable, after updating it:
  658. (progn
  659. (setq org-export-registered-backends
  660. (cl-remove-if-not
  661. (lambda (backend)
  662. (let ((name (org-export-backend-name backend)))
  663. (or (memq name val)
  664. (catch \\='parentp
  665. (dolist (b val)
  666. (and (org-export-derived-backend-p b name)
  667. (throw \\='parentp t)))))))
  668. org-export-registered-backends))
  669. (let ((new-list (mapcar #\\='org-export-backend-name
  670. org-export-registered-backends)))
  671. (dolist (backend val)
  672. (cond
  673. ((not (load (format \"ox-%s\" backend) t t))
  674. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  675. backend))
  676. ((not (memq backend new-list)) (push backend new-list))))
  677. (set-default \\='org-export-backends new-list)))
  678. Adding a back-end to this list will also pull the back-end it
  679. depends on, if any."
  680. :group 'org
  681. :group 'org-export
  682. :version "26.1"
  683. :package-version '(Org . "9.0")
  684. :initialize 'custom-initialize-set
  685. :set (lambda (var val)
  686. (if (not (featurep 'ox)) (set-default var val)
  687. ;; Any back-end not required anymore (not present in VAL and not
  688. ;; a parent of any back-end in the new value) is removed from the
  689. ;; list of registered back-ends.
  690. (setq org-export-registered-backends
  691. (cl-remove-if-not
  692. (lambda (backend)
  693. (let ((name (org-export-backend-name backend)))
  694. (or (memq name val)
  695. (catch 'parentp
  696. (dolist (b val)
  697. (and (org-export-derived-backend-p b name)
  698. (throw 'parentp t)))))))
  699. org-export-registered-backends))
  700. ;; Now build NEW-LIST of both new back-ends and required
  701. ;; parents.
  702. (let ((new-list (mapcar #'org-export-backend-name
  703. org-export-registered-backends)))
  704. (dolist (backend val)
  705. (cond
  706. ((not (load (format "ox-%s" backend) t t))
  707. (message "Problems while trying to load export back-end `%s'"
  708. backend))
  709. ((not (memq backend new-list)) (push backend new-list))))
  710. ;; Set VAR to that list with fixed dependencies.
  711. (set-default var new-list))))
  712. :type '(set :greedy t
  713. (const :tag " ascii Export buffer to ASCII format" ascii)
  714. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  715. (const :tag " html Export buffer to HTML format" html)
  716. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  717. (const :tag " latex Export buffer to LaTeX format" latex)
  718. (const :tag " man Export buffer to MAN format" man)
  719. (const :tag " md Export buffer to Markdown format" md)
  720. (const :tag " odt Export buffer to ODT format" odt)
  721. (const :tag " org Export buffer to Org format" org)
  722. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  723. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  724. (const :tag "C deck Export buffer to deck.js presentations" deck)
  725. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  726. (const :tag "C groff Export buffer to Groff format" groff)
  727. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  728. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  729. (const :tag "C s5 Export buffer to s5 presentations" s5)
  730. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  731. (eval-after-load 'ox
  732. '(dolist (backend org-export-backends)
  733. (condition-case nil (require (intern (format "ox-%s" backend)))
  734. (error (message "Problems while trying to load export back-end `%s'"
  735. backend)))))
  736. (defcustom org-support-shift-select nil
  737. "Non-nil means make shift-cursor commands select text when possible.
  738. \\<org-mode-map>\
  739. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  740. start selecting a region, or enlarge regions started in this way.
  741. In Org mode, in special contexts, these same keys are used for
  742. other purposes, important enough to compete with shift selection.
  743. Org tries to balance these needs by supporting `shift-select-mode'
  744. outside these special contexts, under control of this variable.
  745. The default of this variable is nil, to avoid confusing behavior. Shifted
  746. cursor keys will then execute Org commands in the following contexts:
  747. - on a headline, changing TODO state (left/right) and priority (up/down)
  748. - on a time stamp, changing the time
  749. - in a plain list item, changing the bullet type
  750. - in a property definition line, switching between allowed values
  751. - in the BEGIN line of a clock table (changing the time block).
  752. Outside these contexts, the commands will throw an error.
  753. When this variable is t and the cursor is not in a special
  754. context, Org mode will support shift-selection for making and
  755. enlarging regions. To make this more effective, the bullet
  756. cycling will no longer happen anywhere in an item line, but only
  757. if the cursor is exactly on the bullet.
  758. If you set this variable to the symbol `always', then the keys
  759. will not be special in headlines, property lines, and item lines,
  760. to make shift selection work there as well. If this is what you
  761. want, you can use the following alternative commands:
  762. `\\[org-todo]' and `\\[org-priority]' \
  763. to change TODO state and priority,
  764. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  765. can be used to switch TODO sets,
  766. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  767. and properties can be edited by hand or in column view.
  768. However, when the cursor is on a timestamp, shift-cursor commands
  769. will still edit the time stamp - this is just too good to give up."
  770. :group 'org
  771. :type '(choice
  772. (const :tag "Never" nil)
  773. (const :tag "When outside special context" t)
  774. (const :tag "Everywhere except timestamps" always)))
  775. (defcustom org-loop-over-headlines-in-active-region nil
  776. "Shall some commands act upon headlines in the active region?
  777. When set to t, some commands will be performed in all headlines
  778. within the active region.
  779. When set to `start-level', some commands will be performed in all
  780. headlines within the active region, provided that these headlines
  781. are of the same level than the first one.
  782. When set to a string, those commands will be performed on the
  783. matching headlines within the active region. Such string must be
  784. a tags/property/todo match as it is used in the agenda tags view.
  785. The list of commands is: `org-schedule', `org-deadline',
  786. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  787. `org-archive-to-archive-sibling'. The archiving commands skip
  788. already archived entries."
  789. :type '(choice (const :tag "Don't loop" nil)
  790. (const :tag "All headlines in active region" t)
  791. (const :tag "In active region, headlines at the same level than the first one" start-level)
  792. (string :tag "Tags/Property/Todo matcher"))
  793. :version "24.1"
  794. :group 'org-todo
  795. :group 'org-archive)
  796. (defcustom org-startup-folded t
  797. "Non-nil means entering Org mode will switch to OVERVIEW.
  798. This can also be configured on a per-file basis by adding one of
  799. the following lines anywhere in the buffer:
  800. #+STARTUP: fold (or `overview', this is equivalent)
  801. #+STARTUP: nofold (or `showall', this is equivalent)
  802. #+STARTUP: content
  803. #+STARTUP: showeverything
  804. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  805. to ignore this option when Org opens agenda files for the first
  806. time."
  807. :group 'org-startup
  808. :type '(choice
  809. (const :tag "nofold: show all" nil)
  810. (const :tag "fold: overview" t)
  811. (const :tag "content: all headlines" content)
  812. (const :tag "show everything, even drawers" showeverything)))
  813. (defcustom org-startup-truncated t
  814. "Non-nil means entering Org mode will set `truncate-lines'.
  815. This is useful since some lines containing links can be very long and
  816. uninteresting. Also tables look terrible when wrapped.
  817. The variable `org-startup-truncated' allows to configure
  818. truncation for Org mode different to the other modes that use the
  819. variable `truncate-lines' and as a shortcut instead of putting
  820. the variable `truncate-lines' into the `org-mode-hook'. If one
  821. wants to configure truncation for Org mode not statically but
  822. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  823. the variable `truncate-lines' has to be used because in such a
  824. case it is too late to set the variable `org-startup-truncated'."
  825. :group 'org-startup
  826. :type 'boolean)
  827. (defcustom org-startup-indented nil
  828. "Non-nil means turn on `org-indent-mode' on startup.
  829. This can also be configured on a per-file basis by adding one of
  830. the following lines anywhere in the buffer:
  831. #+STARTUP: indent
  832. #+STARTUP: noindent"
  833. :group 'org-structure
  834. :type '(choice
  835. (const :tag "Not" nil)
  836. (const :tag "Globally (slow on startup in large files)" t)))
  837. (defcustom org-use-sub-superscripts t
  838. "Non-nil means interpret \"_\" and \"^\" for display.
  839. If you want to control how Org exports those characters, see
  840. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  841. used to be an alias for `org-export-with-sub-superscripts' in
  842. Org <8.0, it is not anymore.
  843. When this option is turned on, you can use TeX-like syntax for
  844. sub- and superscripts within the buffer. Several characters after
  845. \"_\" or \"^\" will be considered as a single item - so grouping
  846. with {} is normally not needed. For example, the following things
  847. will be parsed as single sub- or superscripts:
  848. 10^24 or 10^tau several digits will be considered 1 item.
  849. 10^-12 or 10^-tau a leading sign with digits or a word
  850. x^2-y^3 will be read as x^2 - y^3, because items are
  851. terminated by almost any nonword/nondigit char.
  852. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  853. Still, ambiguity is possible. So when in doubt, use {} to enclose
  854. the sub/superscript. If you set this variable to the symbol `{}',
  855. the braces are *required* in order to trigger interpretations as
  856. sub/superscript. This can be helpful in documents that need \"_\"
  857. frequently in plain text."
  858. :group 'org-startup
  859. :version "24.4"
  860. :package-version '(Org . "8.0")
  861. :type '(choice
  862. (const :tag "Always interpret" t)
  863. (const :tag "Only with braces" {})
  864. (const :tag "Never interpret" nil)))
  865. (defcustom org-startup-with-beamer-mode nil
  866. "Non-nil means turn on `org-beamer-mode' on startup.
  867. This can also be configured on a per-file basis by adding one of
  868. the following lines anywhere in the buffer:
  869. #+STARTUP: beamer"
  870. :group 'org-startup
  871. :version "24.1"
  872. :type 'boolean)
  873. (defcustom org-startup-align-all-tables nil
  874. "Non-nil means align all tables when visiting a file.
  875. This can also be configured on a per-file basis by adding one of
  876. the following lines anywhere in the buffer:
  877. #+STARTUP: align
  878. #+STARTUP: noalign"
  879. :group 'org-startup
  880. :type 'boolean)
  881. (defcustom org-startup-shrink-all-tables nil
  882. "Non-nil means shrink all table columns with a width cookie.
  883. This can also be configured on a per-file basis by adding one of
  884. the following lines anywhere in the buffer:
  885. #+STARTUP: shrink"
  886. :group 'org-startup
  887. :type 'boolean
  888. :version "27.1"
  889. :package-version '(Org . "9.2")
  890. :safe #'booleanp)
  891. (defcustom org-startup-with-inline-images nil
  892. "Non-nil means show inline images when loading a new Org file.
  893. This can also be configured on a per-file basis by adding one of
  894. the following lines anywhere in the buffer:
  895. #+STARTUP: inlineimages
  896. #+STARTUP: noinlineimages"
  897. :group 'org-startup
  898. :version "24.1"
  899. :type 'boolean)
  900. (defcustom org-startup-with-latex-preview nil
  901. "Non-nil means preview LaTeX fragments when loading a new Org file.
  902. This can also be configured on a per-file basis by adding one of
  903. the following lines anywhere in the buffer:
  904. #+STARTUP: latexpreview
  905. #+STARTUP: nolatexpreview"
  906. :group 'org-startup
  907. :version "24.4"
  908. :package-version '(Org . "8.0")
  909. :type 'boolean)
  910. (defcustom org-insert-mode-line-in-empty-file nil
  911. "Non-nil means insert the first line setting Org mode in empty files.
  912. When the function `org-mode' is called interactively in an empty file, this
  913. normally means that the file name does not automatically trigger Org mode.
  914. To ensure that the file will always be in Org mode in the future, a
  915. line enforcing Org mode will be inserted into the buffer, if this option
  916. has been set."
  917. :group 'org-startup
  918. :type 'boolean)
  919. (defcustom org-replace-disputed-keys nil
  920. "Non-nil means use alternative key bindings for some keys.
  921. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  922. These keys are also used by other packages like shift-selection-mode'
  923. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  924. If you want to use Org mode together with one of these other modes,
  925. or more generally if you would like to move some Org mode commands to
  926. other keys, set this variable and configure the keys with the variable
  927. `org-disputed-keys'.
  928. This option is only relevant at load-time of Org mode, and must be set
  929. *before* org.el is loaded. Changing it requires a restart of Emacs to
  930. become effective."
  931. :group 'org-startup
  932. :type 'boolean)
  933. (defcustom org-use-extra-keys nil
  934. "Non-nil means use extra key sequence definitions for certain commands.
  935. This happens automatically if `window-system' is nil. This
  936. variable lets you do the same manually. You must set it before
  937. loading Org."
  938. :group 'org-startup
  939. :type 'boolean)
  940. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  941. (defcustom org-disputed-keys
  942. '(([(shift up)] . [(meta p)])
  943. ([(shift down)] . [(meta n)])
  944. ([(shift left)] . [(meta -)])
  945. ([(shift right)] . [(meta +)])
  946. ([(control shift right)] . [(meta shift +)])
  947. ([(control shift left)] . [(meta shift -)]))
  948. "Keys for which Org mode and other modes compete.
  949. This is an alist, cars are the default keys, second element specifies
  950. the alternative to use when `org-replace-disputed-keys' is t.
  951. Keys can be specified in any syntax supported by `define-key'.
  952. The value of this option takes effect only at Org mode startup,
  953. therefore you'll have to restart Emacs to apply it after changing."
  954. :group 'org-startup
  955. :type 'alist)
  956. (defun org-key (key)
  957. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  958. Or return the original if not disputed."
  959. (when org-replace-disputed-keys
  960. (let* ((nkey (key-description key))
  961. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  962. org-disputed-keys)))
  963. (setq key (if x (cdr x) key))))
  964. key)
  965. (defun org-defkey (keymap key def)
  966. "Define a key, possibly translated, as returned by `org-key'."
  967. (define-key keymap (org-key key) def))
  968. (defcustom org-ellipsis nil
  969. "The ellipsis to use in the Org mode outline.
  970. When nil, just use the standard three dots. When a non-empty string,
  971. use that string instead.
  972. The change affects only Org mode (which will then use its own display table).
  973. Changing this requires executing `\\[org-mode]' in a buffer to become
  974. effective."
  975. :group 'org-startup
  976. :type '(choice (const :tag "Default" nil)
  977. (string :tag "String" :value "...#"))
  978. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  979. (defvar org-display-table nil
  980. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  981. (defgroup org-keywords nil
  982. "Keywords in Org mode."
  983. :tag "Org Keywords"
  984. :group 'org)
  985. (defcustom org-closed-keep-when-no-todo nil
  986. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  987. :group 'org-todo
  988. :group 'org-keywords
  989. :version "24.4"
  990. :package-version '(Org . "8.0")
  991. :type 'boolean)
  992. (defgroup org-structure nil
  993. "Options concerning the general structure of Org files."
  994. :tag "Org Structure"
  995. :group 'org)
  996. (defgroup org-reveal-location nil
  997. "Options about how to make context of a location visible."
  998. :tag "Org Reveal Location"
  999. :group 'org-structure)
  1000. (defcustom org-show-context-detail '((agenda . local)
  1001. (bookmark-jump . lineage)
  1002. (isearch . lineage)
  1003. (default . ancestors))
  1004. "Alist between context and visibility span when revealing a location.
  1005. \\<org-mode-map>Some actions may move point into invisible
  1006. locations. As a consequence, Org always expose a neighborhood
  1007. around point. How much is shown depends on the initial action,
  1008. or context. Valid contexts are
  1009. agenda when exposing an entry from the agenda
  1010. org-goto when using the command `org-goto' (`\\[org-goto]')
  1011. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1012. tags-tree when constructing a sparse tree based on tags matches
  1013. link-search when exposing search matches associated with a link
  1014. mark-goto when exposing the jump goal of a mark
  1015. bookmark-jump when exposing a bookmark location
  1016. isearch when exiting from an incremental search
  1017. default default for all contexts not set explicitly
  1018. Allowed visibility spans are
  1019. minimal show current headline; if point is not on headline,
  1020. also show entry
  1021. local show current headline, entry and next headline
  1022. ancestors show current headline and its direct ancestors; if
  1023. point is not on headline, also show entry
  1024. lineage show current headline, its direct ancestors and all
  1025. their children; if point is not on headline, also show
  1026. entry and first child
  1027. tree show current headline, its direct ancestors and all
  1028. their children; if point is not on headline, also show
  1029. entry and all children
  1030. canonical show current headline, its direct ancestors along with
  1031. their entries and children; if point is not located on
  1032. the headline, also show current entry and all children
  1033. As special cases, a nil or t value means show all contexts in
  1034. `minimal' or `canonical' view, respectively.
  1035. Some views can make displayed information very compact, but also
  1036. make it harder to edit the location of the match. In such
  1037. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1038. more context."
  1039. :group 'org-reveal-location
  1040. :version "26.1"
  1041. :package-version '(Org . "9.0")
  1042. :type '(choice
  1043. (const :tag "Canonical" t)
  1044. (const :tag "Minimal" nil)
  1045. (repeat :greedy t :tag "Individual contexts"
  1046. (cons
  1047. (choice :tag "Context"
  1048. (const agenda)
  1049. (const org-goto)
  1050. (const occur-tree)
  1051. (const tags-tree)
  1052. (const link-search)
  1053. (const mark-goto)
  1054. (const bookmark-jump)
  1055. (const isearch)
  1056. (const default))
  1057. (choice :tag "Detail level"
  1058. (const minimal)
  1059. (const local)
  1060. (const ancestors)
  1061. (const lineage)
  1062. (const tree)
  1063. (const canonical))))))
  1064. (defcustom org-indirect-buffer-display 'other-window
  1065. "How should indirect tree buffers be displayed?
  1066. This applies to indirect buffers created with the commands
  1067. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1068. Valid values are:
  1069. current-window Display in the current window
  1070. other-window Just display in another window.
  1071. dedicated-frame Create one new frame, and re-use it each time.
  1072. new-frame Make a new frame each time. Note that in this case
  1073. previously-made indirect buffers are kept, and you need to
  1074. kill these buffers yourself."
  1075. :group 'org-structure
  1076. :group 'org-agenda-windows
  1077. :type '(choice
  1078. (const :tag "In current window" current-window)
  1079. (const :tag "In current frame, other window" other-window)
  1080. (const :tag "Each time a new frame" new-frame)
  1081. (const :tag "One dedicated frame" dedicated-frame)))
  1082. (defcustom org-use-speed-commands nil
  1083. "Non-nil means activate single letter commands at beginning of a headline.
  1084. This may also be a function to test for appropriate locations where speed
  1085. commands should be active.
  1086. For example, to activate speed commands when the point is on any
  1087. star at the beginning of the headline, you can do this:
  1088. (setq org-use-speed-commands
  1089. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1090. :group 'org-structure
  1091. :type '(choice
  1092. (const :tag "Never" nil)
  1093. (const :tag "At beginning of headline stars" t)
  1094. (function)))
  1095. (defcustom org-speed-commands-user nil
  1096. "Alist of additional speed commands.
  1097. This list will be checked before `org-speed-commands-default'
  1098. when the variable `org-use-speed-commands' is non-nil
  1099. and when the cursor is at the beginning of a headline.
  1100. The car of each entry is a string with a single letter, which must
  1101. be assigned to `self-insert-command' in the global map.
  1102. The cdr is either a command to be called interactively, a function
  1103. to be called, or a form to be evaluated.
  1104. An entry that is just a list with a single string will be interpreted
  1105. as a descriptive headline that will be added when listing the speed
  1106. commands in the Help buffer using the `?' speed command."
  1107. :group 'org-structure
  1108. :type '(repeat :value ("k" . ignore)
  1109. (choice :value ("k" . ignore)
  1110. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1111. (cons :tag "Letter and Command"
  1112. (string :tag "Command letter")
  1113. (choice
  1114. (function)
  1115. (sexp))))))
  1116. (defcustom org-bookmark-names-plist
  1117. '(:last-capture "org-capture-last-stored"
  1118. :last-refile "org-refile-last-stored"
  1119. :last-capture-marker "org-capture-last-stored-marker")
  1120. "Names for bookmarks automatically set by some Org commands.
  1121. This can provide strings as names for a number of bookmarks Org sets
  1122. automatically. The following keys are currently implemented:
  1123. :last-capture
  1124. :last-capture-marker
  1125. :last-refile
  1126. When a key does not show up in the property list, the corresponding bookmark
  1127. is not set."
  1128. :group 'org-structure
  1129. :type 'plist)
  1130. (defgroup org-cycle nil
  1131. "Options concerning visibility cycling in Org mode."
  1132. :tag "Org Cycle"
  1133. :group 'org-structure)
  1134. (defcustom org-cycle-skip-children-state-if-no-children t
  1135. "Non-nil means skip CHILDREN state in entries that don't have any."
  1136. :group 'org-cycle
  1137. :type 'boolean)
  1138. (defcustom org-cycle-max-level nil
  1139. "Maximum level which should still be subject to visibility cycling.
  1140. Levels higher than this will, for cycling, be treated as text, not a headline.
  1141. When `org-odd-levels-only' is set, a value of N in this variable actually
  1142. means 2N-1 stars as the limiting headline.
  1143. When nil, cycle all levels.
  1144. Note that the limiting level of cycling is also influenced by
  1145. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1146. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1147. than its value."
  1148. :group 'org-cycle
  1149. :type '(choice
  1150. (const :tag "No limit" nil)
  1151. (integer :tag "Maximum level")))
  1152. (defcustom org-hide-block-startup nil
  1153. "Non-nil means entering Org mode will fold all blocks.
  1154. This can also be set in on a per-file basis with
  1155. #+STARTUP: hideblocks
  1156. #+STARTUP: showblocks"
  1157. :group 'org-startup
  1158. :group 'org-cycle
  1159. :type 'boolean)
  1160. (defcustom org-cycle-global-at-bob nil
  1161. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1162. This makes it possible to do global cycling without having to use `S-TAB'
  1163. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1164. line of the buffer
  1165. must not be a headline -- it may be empty or some other text.
  1166. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1167. sure the cursor stays at the beginning of the buffer.
  1168. When this option is nil, don't do anything special at the beginning of
  1169. the buffer."
  1170. :group 'org-cycle
  1171. :type 'boolean)
  1172. (defcustom org-cycle-level-after-item/entry-creation t
  1173. "Non-nil means cycle entry level or item indentation in new empty entries.
  1174. When the cursor is at the end of an empty headline, i.e., with only stars
  1175. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1176. and then all possible ancestor states, before returning to the original state.
  1177. This makes data entry extremely fast: M-RET to create a new headline,
  1178. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1179. When the cursor is at the end of an empty plain list item, one TAB will
  1180. make it a subitem, two or more tabs will back up to make this an item
  1181. higher up in the item hierarchy."
  1182. :group 'org-cycle
  1183. :type 'boolean)
  1184. (defcustom org-cycle-emulate-tab t
  1185. "Where should `org-cycle' emulate TAB.
  1186. nil Never
  1187. white Only in completely white lines
  1188. whitestart Only at the beginning of lines, before the first non-white char
  1189. t Everywhere except in headlines
  1190. exc-hl-bol Everywhere except at the start of a headline
  1191. If TAB is used in a place where it does not emulate TAB, the current subtree
  1192. visibility is cycled."
  1193. :group 'org-cycle
  1194. :type '(choice (const :tag "Never" nil)
  1195. (const :tag "Only in completely white lines" white)
  1196. (const :tag "Before first char in a line" whitestart)
  1197. (const :tag "Everywhere except in headlines" t)
  1198. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1199. (defcustom org-cycle-separator-lines 2
  1200. "Number of empty lines needed to keep an empty line between collapsed trees.
  1201. If you leave an empty line between the end of a subtree and the following
  1202. headline, this empty line is hidden when the subtree is folded.
  1203. Org mode will leave (exactly) one empty line visible if the number of
  1204. empty lines is equal or larger to the number given in this variable.
  1205. So the default 2 means at least 2 empty lines after the end of a subtree
  1206. are needed to produce free space between a collapsed subtree and the
  1207. following headline.
  1208. If the number is negative, and the number of empty lines is at least -N,
  1209. all empty lines are shown.
  1210. Special case: when 0, never leave empty lines in collapsed view."
  1211. :group 'org-cycle
  1212. :type 'integer)
  1213. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1214. (defcustom org-pre-cycle-hook nil
  1215. "Hook that is run before visibility cycling is happening.
  1216. The function(s) in this hook must accept a single argument which indicates
  1217. the new state that will be set right after running this hook. The
  1218. argument is a symbol. Before a global state change, it can have the values
  1219. `overview', `content', or `all'. Before a local state change, it can have
  1220. the values `folded', `children', or `subtree'."
  1221. :group 'org-cycle
  1222. :type 'hook)
  1223. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1224. org-cycle-hide-drawers
  1225. org-cycle-show-empty-lines
  1226. org-optimize-window-after-visibility-change)
  1227. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1228. The function(s) in this hook must accept a single argument which indicates
  1229. the new state that was set by the most recent `org-cycle' command. The
  1230. argument is a symbol. After a global state change, it can have the values
  1231. `overview', `contents', or `all'. After a local state change, it can have
  1232. the values `folded', `children', or `subtree'."
  1233. :group 'org-cycle
  1234. :type 'hook
  1235. :version "26.1"
  1236. :package-version '(Org . "8.3"))
  1237. (defgroup org-edit-structure nil
  1238. "Options concerning structure editing in Org mode."
  1239. :tag "Org Edit Structure"
  1240. :group 'org-structure)
  1241. (defcustom org-odd-levels-only nil
  1242. "Non-nil means skip even levels and only use odd levels for the outline.
  1243. This has the effect that two stars are being added/taken away in
  1244. promotion/demotion commands. It also influences how levels are
  1245. handled by the exporters.
  1246. Changing it requires restart of `font-lock-mode' to become effective
  1247. for fontification also in regions already fontified.
  1248. You may also set this on a per-file basis by adding one of the following
  1249. lines to the buffer:
  1250. #+STARTUP: odd
  1251. #+STARTUP: oddeven"
  1252. :group 'org-edit-structure
  1253. :group 'org-appearance
  1254. :type 'boolean)
  1255. (defcustom org-adapt-indentation t
  1256. "Non-nil means adapt indentation to outline node level.
  1257. When this variable is set, Org assumes that you write outlines by
  1258. indenting text in each node to align with the headline (after the
  1259. stars). The following issues are influenced by this variable:
  1260. - The indentation is increased by one space in a demotion
  1261. command, and decreased by one in a promotion command. However,
  1262. in the latter case, if shifting some line in the entry body
  1263. would alter document structure (e.g., insert a new headline),
  1264. indentation is not changed at all.
  1265. - Property drawers and planning information is inserted indented
  1266. when this variable is set. When nil, they will not be indented.
  1267. - TAB indents a line relative to current level. The lines below
  1268. a headline will be indented when this variable is set.
  1269. Note that this is all about true indentation, by adding and
  1270. removing space characters. See also `org-indent.el' which does
  1271. level-dependent indentation in a virtual way, i.e. at display
  1272. time in Emacs."
  1273. :group 'org-edit-structure
  1274. :type 'boolean)
  1275. (defcustom org-special-ctrl-a/e nil
  1276. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1277. When t, `C-a' will bring back the cursor to the beginning of the
  1278. headline text, i.e. after the stars and after a possible TODO
  1279. keyword. In an item, this will be the position after bullet and
  1280. check-box, if any. When the cursor is already at that position,
  1281. another `C-a' will bring it to the beginning of the line.
  1282. `C-e' will jump to the end of the headline, ignoring the presence
  1283. of tags in the headline. A second `C-e' will then jump to the
  1284. true end of the line, after any tags. This also means that, when
  1285. this variable is non-nil, `C-e' also will never jump beyond the
  1286. end of the heading of a folded section, i.e. not after the
  1287. ellipses.
  1288. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1289. normally, going to the true line boundary first. Only a directly
  1290. following, identical keypress will bring the cursor to the
  1291. special positions.
  1292. This may also be a cons cell where the behavior for `C-a' and
  1293. `C-e' is set separately."
  1294. :group 'org-edit-structure
  1295. :type '(choice
  1296. (const :tag "off" nil)
  1297. (const :tag "on: after stars/bullet and before tags first" t)
  1298. (const :tag "reversed: true line boundary first" reversed)
  1299. (cons :tag "Set C-a and C-e separately"
  1300. (choice :tag "Special C-a"
  1301. (const :tag "off" nil)
  1302. (const :tag "on: after stars/bullet first" t)
  1303. (const :tag "reversed: before stars/bullet first" reversed))
  1304. (choice :tag "Special C-e"
  1305. (const :tag "off" nil)
  1306. (const :tag "on: before tags first" t)
  1307. (const :tag "reversed: after tags first" reversed)))))
  1308. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1309. (defcustom org-special-ctrl-k nil
  1310. "Non-nil means `C-k' will behave specially in headlines.
  1311. When nil, `C-k' will call the default `kill-line' command.
  1312. When t, the following will happen while the cursor is in the headline:
  1313. - When the cursor is at the beginning of a headline, kill the entire
  1314. line and possible the folded subtree below the line.
  1315. - When in the middle of the headline text, kill the headline up to the tags.
  1316. - When after the headline text, kill the tags."
  1317. :group 'org-edit-structure
  1318. :type 'boolean)
  1319. (defcustom org-ctrl-k-protect-subtree nil
  1320. "Non-nil means, do not delete a hidden subtree with C-k.
  1321. When set to the symbol `error', simply throw an error when C-k is
  1322. used to kill (part-of) a headline that has hidden text behind it.
  1323. Any other non-nil value will result in a query to the user, if it is
  1324. OK to kill that hidden subtree. When nil, kill without remorse."
  1325. :group 'org-edit-structure
  1326. :version "24.1"
  1327. :type '(choice
  1328. (const :tag "Do not protect hidden subtrees" nil)
  1329. (const :tag "Protect hidden subtrees with a security query" t)
  1330. (const :tag "Never kill a hidden subtree with C-k" error)))
  1331. (defcustom org-special-ctrl-o t
  1332. "Non-nil means, make `C-o' insert a row in tables."
  1333. :group 'org-edit-structure
  1334. :type 'boolean)
  1335. (defcustom org-catch-invisible-edits nil
  1336. "Check if in invisible region before inserting or deleting a character.
  1337. Valid values are:
  1338. nil Do not check, so just do invisible edits.
  1339. error Throw an error and do nothing.
  1340. show Make point visible, and do the requested edit.
  1341. show-and-error Make point visible, then throw an error and abort the edit.
  1342. smart Make point visible, and do insertion/deletion if it is
  1343. adjacent to visible text and the change feels predictable.
  1344. Never delete a previously invisible character or add in the
  1345. middle or right after an invisible region. Basically, this
  1346. allows insertion and backward-delete right before ellipses.
  1347. FIXME: maybe in this case we should not even show?"
  1348. :group 'org-edit-structure
  1349. :version "24.1"
  1350. :type '(choice
  1351. (const :tag "Do not check" nil)
  1352. (const :tag "Throw error when trying to edit" error)
  1353. (const :tag "Unhide, but do not do the edit" show-and-error)
  1354. (const :tag "Show invisible part and do the edit" show)
  1355. (const :tag "Be smart and do the right thing" smart)))
  1356. (defcustom org-yank-folded-subtrees t
  1357. "Non-nil means when yanking subtrees, fold them.
  1358. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1359. it starts with a heading and all other headings in it are either children
  1360. or siblings, then fold all the subtrees. However, do this only if no
  1361. text after the yank would be swallowed into a folded tree by this action."
  1362. :group 'org-edit-structure
  1363. :type 'boolean)
  1364. (defcustom org-yank-adjusted-subtrees nil
  1365. "Non-nil means when yanking subtrees, adjust the level.
  1366. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1367. this function for details."
  1368. :group 'org-edit-structure
  1369. :type 'boolean)
  1370. (defcustom org-M-RET-may-split-line '((default . t))
  1371. "Non-nil means M-RET will split the line at the cursor position.
  1372. When nil, it will go to the end of the line before making a
  1373. new line.
  1374. You may also set this option in a different way for different
  1375. contexts. Valid contexts are:
  1376. headline when creating a new headline
  1377. item when creating a new item
  1378. table in a table field
  1379. default the value to be used for all contexts not explicitly
  1380. customized"
  1381. :group 'org-structure
  1382. :group 'org-table
  1383. :type '(choice
  1384. (const :tag "Always" t)
  1385. (const :tag "Never" nil)
  1386. (repeat :greedy t :tag "Individual contexts"
  1387. (cons
  1388. (choice :tag "Context"
  1389. (const headline)
  1390. (const item)
  1391. (const table)
  1392. (const default))
  1393. (boolean)))))
  1394. (defcustom org-insert-heading-respect-content nil
  1395. "Non-nil means insert new headings after the current subtree.
  1396. \\<org-mode-map>
  1397. When nil, the new heading is created directly after the current line.
  1398. The commands `\\[org-insert-heading-respect-content]' and \
  1399. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1400. for the duration of the command."
  1401. :group 'org-structure
  1402. :type 'boolean)
  1403. (defcustom org-blank-before-new-entry '((heading . auto)
  1404. (plain-list-item . auto))
  1405. "Should `org-insert-heading' leave a blank line before new heading/item?
  1406. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1407. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1408. which case Org will look at the surrounding headings/items and try to
  1409. make an intelligent decision whether to insert a blank line or not."
  1410. :group 'org-edit-structure
  1411. :type '(list
  1412. (cons (const heading)
  1413. (choice (const :tag "Never" nil)
  1414. (const :tag "Always" t)
  1415. (const :tag "Auto" auto)))
  1416. (cons (const plain-list-item)
  1417. (choice (const :tag "Never" nil)
  1418. (const :tag "Always" t)
  1419. (const :tag "Auto" auto)))))
  1420. (defcustom org-insert-heading-hook nil
  1421. "Hook being run after inserting a new heading."
  1422. :group 'org-edit-structure
  1423. :type 'hook)
  1424. (defcustom org-enable-fixed-width-editor t
  1425. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1426. This currently only means they are never auto-wrapped.
  1427. When nil, such lines will be treated like ordinary lines."
  1428. :group 'org-edit-structure
  1429. :type 'boolean)
  1430. (defgroup org-sparse-trees nil
  1431. "Options concerning sparse trees in Org mode."
  1432. :tag "Org Sparse Trees"
  1433. :group 'org-structure)
  1434. (defcustom org-highlight-sparse-tree-matches t
  1435. "Non-nil means highlight all matches that define a sparse tree.
  1436. The highlights will automatically disappear the next time the buffer is
  1437. changed by an edit command."
  1438. :group 'org-sparse-trees
  1439. :type 'boolean)
  1440. (defcustom org-remove-highlights-with-change t
  1441. "Non-nil means any change to the buffer will remove temporary highlights.
  1442. \\<org-mode-map>\
  1443. Such highlights are created by `org-occur' and `org-clock-display'.
  1444. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1445. to get rid of the highlights.
  1446. The highlights created by `org-toggle-latex-fragment' always need
  1447. `\\[org-toggle-latex-fragment]' to be removed."
  1448. :group 'org-sparse-trees
  1449. :group 'org-time
  1450. :type 'boolean)
  1451. (defcustom org-occur-case-fold-search t
  1452. "Non-nil means `org-occur' should be case-insensitive.
  1453. If set to `smart' the search will be case-insensitive only if it
  1454. doesn't specify any upper case character."
  1455. :group 'org-sparse-trees
  1456. :version "26.1"
  1457. :type '(choice
  1458. (const :tag "Case-sensitive" nil)
  1459. (const :tag "Case-insensitive" t)
  1460. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1461. (defcustom org-occur-hook '(org-first-headline-recenter)
  1462. "Hook that is run after `org-occur' has constructed a sparse tree.
  1463. This can be used to recenter the window to show as much of the structure
  1464. as possible."
  1465. :group 'org-sparse-trees
  1466. :type 'hook)
  1467. (defgroup org-table nil
  1468. "Options concerning tables in Org mode."
  1469. :tag "Org Table"
  1470. :group 'org)
  1471. (defcustom org-self-insert-cluster-for-undo nil
  1472. "Non-nil means cluster self-insert commands for undo when possible.
  1473. If this is set, then, like in the Emacs command loop, 20 consecutive
  1474. characters will be undone together.
  1475. This is configurable, because there is some impact on typing performance."
  1476. :group 'org-table
  1477. :type 'boolean)
  1478. (defcustom org-table-tab-recognizes-table.el t
  1479. "Non-nil means TAB will automatically notice a table.el table.
  1480. When it sees such a table, it moves point into it and - if necessary -
  1481. calls `table-recognize-table'."
  1482. :group 'org-table-editing
  1483. :type 'boolean)
  1484. (defgroup org-link nil
  1485. "Options concerning links in Org mode."
  1486. :tag "Org Link"
  1487. :group 'org)
  1488. (defvar-local org-link-abbrev-alist-local nil
  1489. "Buffer-local version of `org-link-abbrev-alist', which see.
  1490. The value of this is taken from the #+LINK lines.")
  1491. (defcustom org-link-parameters
  1492. '(("doi" :follow org--open-doi-link)
  1493. ("elisp" :follow org--open-elisp-link)
  1494. ("file" :complete org-file-complete-link)
  1495. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1496. ("help" :follow org--open-help-link)
  1497. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1498. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1499. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1500. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1501. ("shell" :follow org--open-shell-link))
  1502. "An alist of properties that defines all the links in Org mode.
  1503. The key in each association is a string of the link type.
  1504. Subsequent optional elements make up a p-list of link properties.
  1505. :follow - A function that takes the link path as an argument.
  1506. :export - A function that takes the link path, description and
  1507. export-backend as arguments.
  1508. :store - A function responsible for storing the link. See the
  1509. function `org-store-link-functions'.
  1510. :complete - A function that inserts a link with completion. The
  1511. function takes one optional prefix arg.
  1512. :face - A face for the link, or a function that returns a face.
  1513. The function takes one argument which is the link path. The
  1514. default face is `org-link'.
  1515. :mouse-face - The mouse-face. The default is `highlight'.
  1516. :display - `full' will not fold the link in descriptive
  1517. display. Default is `org-link'.
  1518. :help-echo - A string or function that takes (window object position)
  1519. as arguments and returns a string.
  1520. :keymap - A keymap that is active on the link. The default is
  1521. `org-mouse-map'.
  1522. :htmlize-link - A function for the htmlize-link. Defaults
  1523. to (list :uri \"type:path\")
  1524. :activate-func - A function to run at the end of font-lock
  1525. activation. The function must accept (link-start link-end path bracketp)
  1526. as arguments."
  1527. :group 'org-link
  1528. :type '(alist :tag "Link display parameters"
  1529. :value-type plist)
  1530. :version "26.1"
  1531. :package-version '(Org . "9.1"))
  1532. (defun org-link-get-parameter (type key)
  1533. "Get TYPE link property for KEY.
  1534. TYPE is a string and KEY is a plist keyword."
  1535. (plist-get
  1536. (cdr (assoc type org-link-parameters))
  1537. key))
  1538. (defun org-link-set-parameters (type &rest parameters)
  1539. "Set link TYPE properties to PARAMETERS.
  1540. PARAMETERS should be :key val pairs."
  1541. (let ((data (assoc type org-link-parameters)))
  1542. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1543. (push (cons type parameters) org-link-parameters)
  1544. (org-make-link-regexps)
  1545. (org-element-update-syntax))))
  1546. (defun org-link-types ()
  1547. "Return a list of known link types."
  1548. (mapcar #'car org-link-parameters))
  1549. (defcustom org-link-abbrev-alist nil
  1550. "Alist of link abbreviations.
  1551. The car of each element is a string, to be replaced at the start of a link.
  1552. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1553. links in Org buffers can have an optional tag after a double colon, e.g.,
  1554. [[linkkey:tag][description]]
  1555. The `linkkey' must be a single word, starting with a letter, followed
  1556. by letters, numbers, `-' or `_'.
  1557. If REPLACE is a string, the tag will simply be appended to create the link.
  1558. If the string contains \"%s\", the tag will be inserted there. If the string
  1559. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1560. at that point (see the function `url-hexify-string'). If the string contains
  1561. the specifier \"%(my-function)\", then the custom function `my-function' will
  1562. be invoked: this function takes the tag as its only argument and must return
  1563. a string.
  1564. REPLACE may also be a function that will be called with the tag as the
  1565. only argument to create the link, which should be returned as a string.
  1566. See the manual for examples."
  1567. :group 'org-link
  1568. :type '(repeat
  1569. (cons
  1570. (string :tag "Protocol")
  1571. (choice
  1572. (string :tag "Format")
  1573. (function)))))
  1574. (defcustom org-descriptive-links t
  1575. "Non-nil means Org will display descriptive links.
  1576. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1577. \"Org Website\", hiding the link itself and just displaying its
  1578. description. When set to nil, Org will display the full links
  1579. literally.
  1580. You can interactively set the value of this variable by calling
  1581. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1582. :group 'org-link
  1583. :type 'boolean)
  1584. (defcustom org-link-file-path-type 'adaptive
  1585. "How the path name in file links should be stored.
  1586. Valid values are:
  1587. relative Relative to the current directory, i.e. the directory of the file
  1588. into which the link is being inserted.
  1589. absolute Absolute path, if possible with ~ for home directory.
  1590. noabbrev Absolute path, no abbreviation of home directory.
  1591. adaptive Use relative path for files in the current directory and sub-
  1592. directories of it. For other files, use an absolute path."
  1593. :group 'org-link
  1594. :type '(choice
  1595. (const relative)
  1596. (const absolute)
  1597. (const noabbrev)
  1598. (const adaptive)))
  1599. (defvaralias 'org-activate-links 'org-highlight-links)
  1600. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1601. "Types of links that should be highlighted in Org files.
  1602. This is a list of symbols, each one of them leading to the
  1603. highlighting of a certain link type.
  1604. You can still open links that are not highlighted.
  1605. In principle, it does not hurt to turn on highlighting for all
  1606. link types. There may be a small gain when turning off unused
  1607. link types. The types are:
  1608. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1609. angle Links in angular brackets that may contain whitespace like
  1610. <bbdb:Carsten Dominik>.
  1611. plain Plain links in normal text, no whitespace, like http://google.com.
  1612. radio Text that is matched by a radio target, see manual for details.
  1613. tag Tag settings in a headline (link to tag search).
  1614. date Time stamps (link to calendar).
  1615. footnote Footnote labels.
  1616. If you set this variable during an Emacs session, use `org-mode-restart'
  1617. in the Org buffer so that the change takes effect."
  1618. :group 'org-link
  1619. :group 'org-appearance
  1620. :type '(set :greedy t
  1621. (const :tag "Double bracket links" bracket)
  1622. (const :tag "Angular bracket links" angle)
  1623. (const :tag "Plain text links" plain)
  1624. (const :tag "Radio target matches" radio)
  1625. (const :tag "Tags" tag)
  1626. (const :tag "Timestamps" date)
  1627. (const :tag "Footnotes" footnote)))
  1628. (defcustom org-make-link-description-function nil
  1629. "Function to use for generating link descriptions from links.
  1630. This function must take two parameters: the first one is the
  1631. link, the second one is the description generated by
  1632. `org-insert-link'. The function should return the description to
  1633. use."
  1634. :group 'org-link
  1635. :type '(choice (const nil) (function)))
  1636. (defgroup org-link-store nil
  1637. "Options concerning storing links in Org mode."
  1638. :tag "Org Store Link"
  1639. :group 'org-link)
  1640. (defcustom org-url-hexify-p t
  1641. "When non-nil, hexify URL when creating a link."
  1642. :type 'boolean
  1643. :version "24.3"
  1644. :group 'org-link-store)
  1645. (defcustom org-email-link-description-format "Email %c: %.30s"
  1646. "Format of the description part of a link to an email or usenet message.
  1647. The following %-escapes will be replaced by corresponding information:
  1648. %F full \"From\" field
  1649. %f name, taken from \"From\" field, address if no name
  1650. %T full \"To\" field
  1651. %t first name in \"To\" field, address if no name
  1652. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1653. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1654. %s subject
  1655. %d date
  1656. %m message-id.
  1657. You may use normal field width specification between the % and the letter.
  1658. This is for example useful to limit the length of the subject.
  1659. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1660. :group 'org-link-store
  1661. :type 'string)
  1662. (defcustom org-from-is-user-regexp
  1663. (let (r1 r2)
  1664. (when (and user-mail-address (not (string= user-mail-address "")))
  1665. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1666. (when (and user-full-name (not (string= user-full-name "")))
  1667. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1668. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1669. "Regexp matched against the \"From:\" header of an email or usenet message.
  1670. It should match if the message is from the user him/herself."
  1671. :group 'org-link-store
  1672. :type 'regexp)
  1673. (defcustom org-context-in-file-links t
  1674. "Non-nil means file links from `org-store-link' contain context.
  1675. \\<org-mode-map>
  1676. A search string will be added to the file name with :: as separator
  1677. and used to find the context when the link is activated by the command
  1678. `org-open-at-point'. When this option is t, the entire active region
  1679. will be placed in the search string of the file link. If set to a
  1680. positive integer, only the first n lines of context will be stored.
  1681. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1682. \\[org-store-link]')
  1683. negates this setting for the duration of the command."
  1684. :group 'org-link-store
  1685. :type '(choice boolean integer))
  1686. (defcustom org-keep-stored-link-after-insertion nil
  1687. "Non-nil means keep link in list for entire session.
  1688. \\<org-mode-map>
  1689. The command `org-store-link' adds a link pointing to the current
  1690. location to an internal list. These links accumulate during a session.
  1691. The command `org-insert-link' can be used to insert links into any
  1692. Org file (offering completion for all stored links).
  1693. When this option is nil, every link which has been inserted once using
  1694. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1695. unused
  1696. links more efficient."
  1697. :group 'org-link-store
  1698. :type 'boolean)
  1699. (defgroup org-link-follow nil
  1700. "Options concerning following links in Org mode."
  1701. :tag "Org Follow Link"
  1702. :group 'org-link)
  1703. (defcustom org-link-translation-function nil
  1704. "Function to translate links with different syntax to Org syntax.
  1705. This can be used to translate links created for example by the Planner
  1706. or emacs-wiki packages to Org syntax.
  1707. The function must accept two parameters, a TYPE containing the link
  1708. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1709. which is everything after the link protocol. It should return a cons
  1710. with possibly modified values of type and path.
  1711. Org contains a function for this, so if you set this variable to
  1712. `org-translate-link-from-planner', you should be able follow many
  1713. links created by planner."
  1714. :group 'org-link-follow
  1715. :type '(choice (const nil) (function)))
  1716. (defcustom org-follow-link-hook nil
  1717. "Hook that is run after a link has been followed."
  1718. :group 'org-link-follow
  1719. :type 'hook)
  1720. (defcustom org-tab-follows-link nil
  1721. "Non-nil means on links TAB will follow the link.
  1722. Needs to be set before org.el is loaded.
  1723. This really should not be used, it does not make sense, and the
  1724. implementation is bad."
  1725. :group 'org-link-follow
  1726. :type 'boolean)
  1727. (defcustom org-return-follows-link nil
  1728. "Non-nil means on links RET will follow the link.
  1729. In tables, the special behavior of RET has precedence."
  1730. :group 'org-link-follow
  1731. :type 'boolean)
  1732. (defcustom org-mouse-1-follows-link
  1733. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1734. "Non-nil means mouse-1 on a link will follow the link.
  1735. A longer mouse click will still set point. Needs to be set
  1736. before org.el is loaded."
  1737. :group 'org-link-follow
  1738. :version "26.1"
  1739. :package-version '(Org . "8.3")
  1740. :type '(choice
  1741. (const :tag "A double click follows the link" double)
  1742. (const :tag "Unconditionally follow the link with mouse-1" t)
  1743. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1744. (defcustom org-mark-ring-length 4
  1745. "Number of different positions to be recorded in the ring.
  1746. Changing this requires a restart of Emacs to work correctly."
  1747. :group 'org-link-follow
  1748. :type 'integer)
  1749. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1750. "Non-nil means internal fuzzy links can only match headlines.
  1751. When nil, the a fuzzy link may point to a target or a named
  1752. construct in the document. When set to the special value
  1753. `query-to-create', offer to create a new headline when none
  1754. matched.
  1755. Spaces and statistics cookies are ignored during heading searches."
  1756. :group 'org-link-follow
  1757. :version "24.1"
  1758. :type '(choice
  1759. (const :tag "Use fuzzy text search" nil)
  1760. (const :tag "Match only exact headline" t)
  1761. (const :tag "Match exact headline or query to create it"
  1762. query-to-create))
  1763. :safe #'symbolp)
  1764. (defcustom org-link-frame-setup
  1765. '((vm . vm-visit-folder-other-frame)
  1766. (vm-imap . vm-visit-imap-folder-other-frame)
  1767. (gnus . org-gnus-no-new-news)
  1768. (file . find-file-other-window)
  1769. (wl . wl-other-frame))
  1770. "Setup the frame configuration for following links.
  1771. When following a link with Emacs, it may often be useful to display
  1772. this link in another window or frame. This variable can be used to
  1773. set this up for the different types of links.
  1774. For VM, use any of
  1775. `vm-visit-folder'
  1776. `vm-visit-folder-other-window'
  1777. `vm-visit-folder-other-frame'
  1778. For Gnus, use any of
  1779. `gnus'
  1780. `gnus-other-frame'
  1781. `org-gnus-no-new-news'
  1782. For FILE, use any of
  1783. `find-file'
  1784. `find-file-other-window'
  1785. `find-file-other-frame'
  1786. For Wanderlust use any of
  1787. `wl'
  1788. `wl-other-frame'
  1789. For the calendar, use the variable `calendar-setup'.
  1790. For BBDB, it is currently only possible to display the matches in
  1791. another window."
  1792. :group 'org-link-follow
  1793. :type '(list
  1794. (cons (const vm)
  1795. (choice
  1796. (const vm-visit-folder)
  1797. (const vm-visit-folder-other-window)
  1798. (const vm-visit-folder-other-frame)))
  1799. (cons (const vm-imap)
  1800. (choice
  1801. (const vm-visit-imap-folder)
  1802. (const vm-visit-imap-folder-other-window)
  1803. (const vm-visit-imap-folder-other-frame)))
  1804. (cons (const gnus)
  1805. (choice
  1806. (const gnus)
  1807. (const gnus-other-frame)
  1808. (const org-gnus-no-new-news)))
  1809. (cons (const file)
  1810. (choice
  1811. (const find-file)
  1812. (const find-file-other-window)
  1813. (const find-file-other-frame)))
  1814. (cons (const wl)
  1815. (choice
  1816. (const wl)
  1817. (const wl-other-frame)))))
  1818. (defcustom org-display-internal-link-with-indirect-buffer nil
  1819. "Non-nil means use indirect buffer to display infile links.
  1820. Activating internal links (from one location in a file to another location
  1821. in the same file) normally just jumps to the location. When the link is
  1822. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1823. is displayed in
  1824. another window. When this option is set, the other window actually displays
  1825. an indirect buffer clone of the current buffer, to avoid any visibility
  1826. changes to the current buffer."
  1827. :group 'org-link-follow
  1828. :type 'boolean)
  1829. (defcustom org-open-non-existing-files nil
  1830. "Non-nil means `org-open-file' will open non-existing files.
  1831. When nil, an error will be generated.
  1832. This variable applies only to external applications because they
  1833. might choke on non-existing files. If the link is to a file that
  1834. will be opened in Emacs, the variable is ignored."
  1835. :group 'org-link-follow
  1836. :type 'boolean)
  1837. (defcustom org-open-directory-means-index-dot-org nil
  1838. "Non-nil means a link to a directory really means to index.org.
  1839. When nil, following a directory link will run dired or open a finder/explorer
  1840. window on that directory."
  1841. :group 'org-link-follow
  1842. :type 'boolean)
  1843. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1844. "Non-nil means ask for confirmation before executing shell links.
  1845. Shell links can be dangerous: just think about a link
  1846. [[shell:rm -rf ~/*][Google Search]]
  1847. This link would show up in your Org document as \"Google Search\",
  1848. but really it would remove your entire home directory.
  1849. Therefore we advise against setting this variable to nil.
  1850. Just change it to `y-or-n-p' if you want to confirm with a
  1851. single keystroke rather than having to type \"yes\"."
  1852. :group 'org-link-follow
  1853. :type '(choice
  1854. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1855. (const :tag "with y-or-n (faster)" y-or-n-p)
  1856. (const :tag "no confirmation (dangerous)" nil)))
  1857. (put 'org-confirm-shell-link-function
  1858. 'safe-local-variable
  1859. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1860. (defcustom org-confirm-shell-link-not-regexp ""
  1861. "A regexp to skip confirmation for shell links."
  1862. :group 'org-link-follow
  1863. :version "24.1"
  1864. :type 'regexp)
  1865. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1866. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1867. Elisp links can be dangerous: just think about a link
  1868. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1869. This link would show up in your Org document as \"Google Search\",
  1870. but really it would remove your entire home directory.
  1871. Therefore we advise against setting this variable to nil.
  1872. Just change it to `y-or-n-p' if you want to confirm with a
  1873. single keystroke rather than having to type \"yes\"."
  1874. :group 'org-link-follow
  1875. :type '(choice
  1876. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1877. (const :tag "with y-or-n (faster)" y-or-n-p)
  1878. (const :tag "no confirmation (dangerous)" nil)))
  1879. (put 'org-confirm-shell-link-function
  1880. 'safe-local-variable
  1881. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1882. (defcustom org-confirm-elisp-link-not-regexp ""
  1883. "A regexp to skip confirmation for Elisp links."
  1884. :group 'org-link-follow
  1885. :version "24.1"
  1886. :type 'regexp)
  1887. (defconst org-file-apps-defaults-gnu
  1888. '((remote . emacs)
  1889. (system . mailcap)
  1890. (t . mailcap))
  1891. "Default file applications on a UNIX or GNU/Linux system.
  1892. See `org-file-apps'.")
  1893. (defconst org-file-apps-defaults-macosx
  1894. '((remote . emacs)
  1895. (system . "open %s")
  1896. ("ps.gz" . "gv %s")
  1897. ("eps.gz" . "gv %s")
  1898. ("dvi" . "xdvi %s")
  1899. ("fig" . "xfig %s")
  1900. (t . "open %s"))
  1901. "Default file applications on a macOS system.
  1902. The system \"open\" is known as a default, but we use X11 applications
  1903. for some files for which the OS does not have a good default.
  1904. See `org-file-apps'.")
  1905. (defconst org-file-apps-defaults-windowsnt
  1906. (list '(remote . emacs)
  1907. (cons 'system (lambda (file _path)
  1908. (with-no-warnings (w32-shell-execute "open" file))))
  1909. (cons t (lambda (file _path)
  1910. (with-no-warnings (w32-shell-execute "open" file)))))
  1911. "Default file applications on a Windows NT system.
  1912. The system \"open\" is used for most files.
  1913. See `org-file-apps'.")
  1914. (defcustom org-file-apps
  1915. '((auto-mode . emacs)
  1916. ("\\.mm\\'" . default)
  1917. ("\\.x?html?\\'" . default)
  1918. ("\\.pdf\\'" . default))
  1919. "External applications for opening `file:path' items in a document.
  1920. \\<org-mode-map>\
  1921. Org mode uses system defaults for different file types, but
  1922. you can use this variable to set the application for a given file
  1923. extension. The entries in this list are cons cells where the car identifies
  1924. files and the cdr the corresponding command.
  1925. Possible values for the file identifier are:
  1926. \"string\" A string as a file identifier can be interpreted in different
  1927. ways, depending on its contents:
  1928. - Alphanumeric characters only:
  1929. Match links with this file extension.
  1930. Example: (\"pdf\" . \"evince %s\")
  1931. to open PDFs with evince.
  1932. - Regular expression: Match links where the
  1933. filename matches the regexp. If you want to
  1934. use groups here, use shy groups.
  1935. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1936. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1937. to open *.html and *.xhtml with firefox.
  1938. - Regular expression which contains (non-shy) groups:
  1939. Match links where the whole link, including \"::\", and
  1940. anything after that, matches the regexp.
  1941. In a custom command string, %1, %2, etc. are replaced with
  1942. the parts of the link that were matched by the groups.
  1943. For backwards compatibility, if a command string is given
  1944. that does not use any of the group matches, this case is
  1945. handled identically to the second one (i.e. match against
  1946. file name only).
  1947. In a custom function, you can access the group matches with
  1948. (match-string n link).
  1949. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1950. \"evince -p %1 %s\")
  1951. to open [[file:document.pdf::5]] with evince at page 5.
  1952. `directory' Matches a directory
  1953. `remote' Matches a remote file, accessible through tramp or efs.
  1954. Remote files most likely should be visited through Emacs
  1955. because external applications cannot handle such paths.
  1956. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1957. so all files Emacs knows how to handle. Using this with
  1958. command `emacs' will open most files in Emacs. Beware that this
  1959. will also open html files inside Emacs, unless you add
  1960. (\"html\" . default) to the list as well.
  1961. `system' The system command to open files, like `open' on Windows
  1962. and macOS, and mailcap under GNU/Linux. This is the command
  1963. that will be selected if you call `org-open-at-point' with a
  1964. double prefix argument (`\\[universal-argument] \
  1965. \\[universal-argument] \\[org-open-at-point]').
  1966. t Default for files not matched by any of the other options.
  1967. Possible values for the command are:
  1968. `emacs' The file will be visited by the current Emacs process.
  1969. `default' Use the default application for this file type, which is the
  1970. association for t in the list, most likely in the system-specific
  1971. part. This can be used to overrule an unwanted setting in the
  1972. system-specific variable.
  1973. `system' Use the system command for opening files, like \"open\".
  1974. This command is specified by the entry whose car is `system'.
  1975. Most likely, the system-specific version of this variable
  1976. does define this command, but you can overrule/replace it
  1977. here.
  1978. `mailcap' Use command specified in the mailcaps.
  1979. string A command to be executed by a shell; %s will be replaced
  1980. by the path to the file.
  1981. function A Lisp function, which will be called with two arguments:
  1982. the file path and the original link string, without the
  1983. \"file:\" prefix.
  1984. For more examples, see the system specific constants
  1985. `org-file-apps-defaults-macosx'
  1986. `org-file-apps-defaults-windowsnt'
  1987. `org-file-apps-defaults-gnu'."
  1988. :group 'org-link-follow
  1989. :type '(repeat
  1990. (cons (choice :value ""
  1991. (string :tag "Extension")
  1992. (const :tag "System command to open files" system)
  1993. (const :tag "Default for unrecognized files" t)
  1994. (const :tag "Remote file" remote)
  1995. (const :tag "Links to a directory" directory)
  1996. (const :tag "Any files that have Emacs modes"
  1997. auto-mode))
  1998. (choice :value ""
  1999. (const :tag "Visit with Emacs" emacs)
  2000. (const :tag "Use default" default)
  2001. (const :tag "Use the system command" system)
  2002. (string :tag "Command")
  2003. (function :tag "Function")))))
  2004. (defcustom org-doi-server-url "http://dx.doi.org/"
  2005. "The URL of the DOI server."
  2006. :type 'string
  2007. :version "24.3"
  2008. :group 'org-link-follow)
  2009. (defgroup org-refile nil
  2010. "Options concerning refiling entries in Org mode."
  2011. :tag "Org Refile"
  2012. :group 'org)
  2013. (defcustom org-directory "~/org"
  2014. "Directory with Org files.
  2015. This is just a default location to look for Org files. There is no need
  2016. at all to put your files into this directory. It is used in the
  2017. following situations:
  2018. 1. When a capture template specifies a target file that is not an
  2019. absolute path. The path will then be interpreted relative to
  2020. `org-directory'
  2021. 2. When the value of variable `org-agenda-files' is a single file, any
  2022. relative paths in this file will be taken as relative to
  2023. `org-directory'."
  2024. :group 'org-refile
  2025. :group 'org-capture
  2026. :type 'directory)
  2027. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2028. "Default target for storing notes.
  2029. Used as a fall back file for org-capture.el, for templates that
  2030. do not specify a target file."
  2031. :group 'org-refile
  2032. :group 'org-capture
  2033. :type 'file)
  2034. (defcustom org-reverse-note-order nil
  2035. "Non-nil means store new notes at the beginning of a file or entry.
  2036. When nil, new notes will be filed to the end of a file or entry.
  2037. This can also be a list with cons cells of regular expressions that
  2038. are matched against file names, and values."
  2039. :group 'org-capture
  2040. :group 'org-refile
  2041. :type '(choice
  2042. (const :tag "Reverse always" t)
  2043. (const :tag "Reverse never" nil)
  2044. (repeat :tag "By file name regexp"
  2045. (cons regexp boolean))))
  2046. (defcustom org-log-refile nil
  2047. "Information to record when a task is refiled.
  2048. Possible values are:
  2049. nil Don't add anything
  2050. time Add a time stamp to the task
  2051. note Prompt for a note and add it with template `org-log-note-headings'
  2052. This option can also be set with on a per-file-basis with
  2053. #+STARTUP: nologrefile
  2054. #+STARTUP: logrefile
  2055. #+STARTUP: lognoterefile
  2056. You can have local logging settings for a subtree by setting the LOGGING
  2057. property to one or more of these keywords.
  2058. When bulk-refiling from the agenda, the value `note' is forbidden and
  2059. will temporarily be changed to `time'."
  2060. :group 'org-refile
  2061. :group 'org-progress
  2062. :version "24.1"
  2063. :type '(choice
  2064. (const :tag "No logging" nil)
  2065. (const :tag "Record timestamp" time)
  2066. (const :tag "Record timestamp with note." note)))
  2067. (defcustom org-refile-targets nil
  2068. "Targets for refiling entries with `\\[org-refile]'.
  2069. This is a list of cons cells. Each cell contains:
  2070. - a specification of the files to be considered, either a list of files,
  2071. or a symbol whose function or variable value will be used to retrieve
  2072. a file name or a list of file names. If you use `org-agenda-files' for
  2073. that, all agenda files will be scanned for targets. Nil means consider
  2074. headings in the current buffer.
  2075. - A specification of how to find candidate refile targets. This may be
  2076. any of:
  2077. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2078. This tag has to be present in all target headlines, inheritance will
  2079. not be considered.
  2080. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2081. todo keyword.
  2082. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2083. headlines that are refiling targets.
  2084. - a cons cell (:level . N). Any headline of level N is considered a target.
  2085. Note that, when `org-odd-levels-only' is set, level corresponds to
  2086. order in hierarchy, not to the number of stars.
  2087. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2088. Note that, when `org-odd-levels-only' is set, level corresponds to
  2089. order in hierarchy, not to the number of stars.
  2090. Each element of this list generates a set of possible targets.
  2091. The union of these sets is presented (with completion) to
  2092. the user by `org-refile'.
  2093. You can set the variable `org-refile-target-verify-function' to a function
  2094. to verify each headline found by the simple criteria above.
  2095. When this variable is nil, all top-level headlines in the current buffer
  2096. are used, equivalent to the value `((nil . (:level . 1))'."
  2097. :group 'org-refile
  2098. :type '(repeat
  2099. (cons
  2100. (choice :value org-agenda-files
  2101. (const :tag "All agenda files" org-agenda-files)
  2102. (const :tag "Current buffer" nil)
  2103. (function) (variable) (file))
  2104. (choice :tag "Identify target headline by"
  2105. (cons :tag "Specific tag" (const :value :tag) (string))
  2106. (cons :tag "TODO keyword" (const :value :todo) (string))
  2107. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2108. (cons :tag "Level number" (const :value :level) (integer))
  2109. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2110. (defcustom org-refile-target-verify-function nil
  2111. "Function to verify if the headline at point should be a refile target.
  2112. The function will be called without arguments, with point at the
  2113. beginning of the headline. It should return t and leave point
  2114. where it is if the headline is a valid target for refiling.
  2115. If the target should not be selected, the function must return nil.
  2116. In addition to this, it may move point to a place from where the search
  2117. should be continued. For example, the function may decide that the entire
  2118. subtree of the current entry should be excluded and move point to the end
  2119. of the subtree."
  2120. :group 'org-refile
  2121. :type '(choice
  2122. (const nil)
  2123. (function)))
  2124. (defcustom org-refile-use-cache nil
  2125. "Non-nil means cache refile targets to speed up the process.
  2126. \\<org-mode-map>\
  2127. The cache for a particular file will be updated automatically when
  2128. the buffer has been killed, or when any of the marker used for flagging
  2129. refile targets no longer points at a live buffer.
  2130. If you have added new entries to a buffer that might themselves be targets,
  2131. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2132. if you find that easier, \
  2133. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2134. \\[org-refile]'."
  2135. :group 'org-refile
  2136. :version "24.1"
  2137. :type 'boolean)
  2138. (defcustom org-refile-use-outline-path nil
  2139. "Non-nil means provide refile targets as paths.
  2140. So a level 3 headline will be available as level1/level2/level3.
  2141. When the value is `file', also include the file name (without directory)
  2142. into the path. In this case, you can also stop the completion after
  2143. the file name, to get entries inserted as top level in the file.
  2144. When `full-file-path', include the full file path.
  2145. When `buffer-name', use the buffer name."
  2146. :group 'org-refile
  2147. :type '(choice
  2148. (const :tag "Not" nil)
  2149. (const :tag "Yes" t)
  2150. (const :tag "Start with file name" file)
  2151. (const :tag "Start with full file path" full-file-path)
  2152. (const :tag "Start with buffer name" buffer-name)))
  2153. (defcustom org-outline-path-complete-in-steps t
  2154. "Non-nil means complete the outline path in hierarchical steps.
  2155. When Org uses the refile interface to select an outline path (see
  2156. `org-refile-use-outline-path'), the completion of the path can be
  2157. done in a single go, or it can be done in steps down the headline
  2158. hierarchy. Going in steps is probably the best if you do not use
  2159. a special completion package like `ido' or `icicles'. However,
  2160. when using these packages, going in one step can be very fast,
  2161. while still showing the whole path to the entry."
  2162. :group 'org-refile
  2163. :type 'boolean)
  2164. (defcustom org-refile-allow-creating-parent-nodes nil
  2165. "Non-nil means allow the creation of new nodes as refile targets.
  2166. New nodes are then created by adding \"/new node name\" to the completion
  2167. of an existing node. When the value of this variable is `confirm',
  2168. new node creation must be confirmed by the user (recommended).
  2169. When nil, the completion must match an existing entry.
  2170. Note that, if the new heading is not seen by the criteria
  2171. listed in `org-refile-targets', multiple instances of the same
  2172. heading would be created by trying again to file under the new
  2173. heading."
  2174. :group 'org-refile
  2175. :type '(choice
  2176. (const :tag "Never" nil)
  2177. (const :tag "Always" t)
  2178. (const :tag "Prompt for confirmation" confirm)))
  2179. (defcustom org-refile-active-region-within-subtree nil
  2180. "Non-nil means also refile active region within a subtree.
  2181. By default `org-refile' doesn't allow refiling regions if they
  2182. don't contain a set of subtrees, but it might be convenient to
  2183. do so sometimes: in that case, the first line of the region is
  2184. converted to a headline before refiling."
  2185. :group 'org-refile
  2186. :version "24.1"
  2187. :type 'boolean)
  2188. (defgroup org-todo nil
  2189. "Options concerning TODO items in Org mode."
  2190. :tag "Org TODO"
  2191. :group 'org)
  2192. (defgroup org-progress nil
  2193. "Options concerning Progress logging in Org mode."
  2194. :tag "Org Progress"
  2195. :group 'org-time)
  2196. (defvar org-todo-interpretation-widgets
  2197. '((:tag "Sequence (cycling hits every state)" sequence)
  2198. (:tag "Type (cycling directly to DONE)" type))
  2199. "The available interpretation symbols for customizing `org-todo-keywords'.
  2200. Interested libraries should add to this list.")
  2201. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2202. "List of TODO entry keyword sequences and their interpretation.
  2203. \\<org-mode-map>This is a list of sequences.
  2204. Each sequence starts with a symbol, either `sequence' or `type',
  2205. indicating if the keywords should be interpreted as a sequence of
  2206. action steps, or as different types of TODO items. The first
  2207. keywords are states requiring action - these states will select a headline
  2208. for inclusion into the global TODO list Org produces. If one of the
  2209. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2210. signify that no further action is necessary. If \"|\" is not found,
  2211. the last keyword is treated as the only DONE state of the sequence.
  2212. The command `\\[org-todo]' cycles an entry through these states, and one
  2213. additional state where no keyword is present. For details about this
  2214. cycling, see the manual.
  2215. TODO keywords and interpretation can also be set on a per-file basis with
  2216. the special #+SEQ_TODO and #+TYP_TODO lines.
  2217. Each keyword can optionally specify a character for fast state selection
  2218. \(in combination with the variable `org-use-fast-todo-selection')
  2219. and specifiers for state change logging, using the same syntax that
  2220. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2221. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2222. indicates to record a time stamp each time this state is selected.
  2223. Each keyword may also specify if a timestamp or a note should be
  2224. recorded when entering or leaving the state, by adding additional
  2225. characters in the parenthesis after the keyword. This looks like this:
  2226. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2227. record only the time of the state change. With X and Y being either
  2228. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2229. Y when leaving the state if and only if the *target* state does not
  2230. define X. You may omit any of the fast-selection key or X or /Y,
  2231. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2232. For backward compatibility, this variable may also be just a list
  2233. of keywords. In this case the interpretation (sequence or type) will be
  2234. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2235. :group 'org-todo
  2236. :group 'org-keywords
  2237. :type '(choice
  2238. (repeat :tag "Old syntax, just keywords"
  2239. (string :tag "Keyword"))
  2240. (repeat :tag "New syntax"
  2241. (cons
  2242. (choice
  2243. :tag "Interpretation"
  2244. ;;Quick and dirty way to see
  2245. ;;`org-todo-interpretations'. This takes the
  2246. ;;place of item arguments
  2247. :convert-widget
  2248. (lambda (widget)
  2249. (widget-put widget
  2250. :args (mapcar
  2251. (lambda (x)
  2252. (widget-convert
  2253. (cons 'const x)))
  2254. org-todo-interpretation-widgets))
  2255. widget))
  2256. (repeat
  2257. (string :tag "Keyword"))))))
  2258. (defvar-local org-todo-keywords-1 nil
  2259. "All TODO and DONE keywords active in a buffer.")
  2260. (defvar org-todo-keywords-for-agenda nil)
  2261. (defvar org-done-keywords-for-agenda nil)
  2262. (defvar org-todo-keyword-alist-for-agenda nil)
  2263. (defvar org-tag-alist-for-agenda nil
  2264. "Alist of all tags from all agenda files.")
  2265. (defvar org-tag-groups-alist-for-agenda nil
  2266. "Alist of all groups tags from all current agenda files.")
  2267. (defvar-local org-tag-groups-alist nil)
  2268. (defvar org-agenda-contributing-files nil)
  2269. (defvar-local org-current-tag-alist nil
  2270. "Alist of all tag groups in current buffer.
  2271. This variable takes into consideration `org-tag-alist',
  2272. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2273. (defvar-local org-not-done-keywords nil)
  2274. (defvar-local org-done-keywords nil)
  2275. (defvar-local org-todo-heads nil)
  2276. (defvar-local org-todo-sets nil)
  2277. (defvar-local org-todo-log-states nil)
  2278. (defvar-local org-todo-kwd-alist nil)
  2279. (defvar-local org-todo-key-alist nil)
  2280. (defvar-local org-todo-key-trigger nil)
  2281. (defcustom org-todo-interpretation 'sequence
  2282. "Controls how TODO keywords are interpreted.
  2283. This variable is in principle obsolete and is only used for
  2284. backward compatibility, if the interpretation of todo keywords is
  2285. not given already in `org-todo-keywords'. See that variable for
  2286. more information."
  2287. :group 'org-todo
  2288. :group 'org-keywords
  2289. :type '(choice (const sequence)
  2290. (const type)))
  2291. (defcustom org-use-fast-todo-selection t
  2292. "\\<org-mode-map>\
  2293. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2294. This variable describes if and under what circumstances the cycling
  2295. mechanism for TODO keywords will be replaced by a single-key, direct
  2296. selection scheme.
  2297. When nil, fast selection is never used.
  2298. When the symbol `prefix', it will be used when `org-todo' is called
  2299. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2300. in an Org buffer, and
  2301. `\\[universal-argument] t' in an agenda buffer.
  2302. When t, fast selection is used by default. In this case, the prefix
  2303. argument forces cycling instead.
  2304. In all cases, the special interface is only used if access keys have
  2305. actually been assigned by the user, i.e. if keywords in the configuration
  2306. are followed by a letter in parenthesis, like TODO(t)."
  2307. :group 'org-todo
  2308. :type '(choice
  2309. (const :tag "Never" nil)
  2310. (const :tag "By default" t)
  2311. (const :tag "Only with C-u C-c C-t" prefix)))
  2312. (defcustom org-provide-todo-statistics t
  2313. "Non-nil means update todo statistics after insert and toggle.
  2314. ALL-HEADLINES means update todo statistics by including headlines
  2315. with no TODO keyword as well, counting them as not done.
  2316. A list of TODO keywords means the same, but skip keywords that are
  2317. not in this list.
  2318. When set to a list of two lists, the first list contains keywords
  2319. to consider as TODO keywords, the second list contains keywords
  2320. to consider as DONE keywords.
  2321. When this is set, todo statistics is updated in the parent of the
  2322. current entry each time a todo state is changed."
  2323. :group 'org-todo
  2324. :type '(choice
  2325. (const :tag "Yes, only for TODO entries" t)
  2326. (const :tag "Yes, including all entries" all-headlines)
  2327. (repeat :tag "Yes, for TODOs in this list"
  2328. (string :tag "TODO keyword"))
  2329. (list :tag "Yes, for TODOs and DONEs in these lists"
  2330. (repeat (string :tag "TODO keyword"))
  2331. (repeat (string :tag "DONE keyword")))
  2332. (other :tag "No TODO statistics" nil)))
  2333. (defcustom org-hierarchical-todo-statistics t
  2334. "Non-nil means TODO statistics covers just direct children.
  2335. When nil, all entries in the subtree are considered.
  2336. This has only an effect if `org-provide-todo-statistics' is set.
  2337. To set this to nil for only a single subtree, use a COOKIE_DATA
  2338. property and include the word \"recursive\" into the value."
  2339. :group 'org-todo
  2340. :type 'boolean)
  2341. (defcustom org-after-todo-state-change-hook nil
  2342. "Hook which is run after the state of a TODO item was changed.
  2343. The new state (a string with a TODO keyword, or nil) is available in the
  2344. Lisp variable `org-state'."
  2345. :group 'org-todo
  2346. :type 'hook)
  2347. (defvar org-blocker-hook nil
  2348. "Hook for functions that are allowed to block a state change.
  2349. Functions in this hook should not modify the buffer.
  2350. Each function gets as its single argument a property list,
  2351. see `org-trigger-hook' for more information about this list.
  2352. If any of the functions in this hook returns nil, the state change
  2353. is blocked.")
  2354. (defvar org-trigger-hook nil
  2355. "Hook for functions that are triggered by a state change.
  2356. Each function gets as its single argument a property list with at
  2357. least the following elements:
  2358. (:type type-of-change :position pos-at-entry-start
  2359. :from old-state :to new-state)
  2360. Depending on the type, more properties may be present.
  2361. This mechanism is currently implemented for:
  2362. TODO state changes
  2363. ------------------
  2364. :type todo-state-change
  2365. :from previous state (keyword as a string), or nil, or a symbol
  2366. `todo' or `done', to indicate the general type of state.
  2367. :to new state, like in :from")
  2368. (defcustom org-enforce-todo-dependencies nil
  2369. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2370. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2371. be blocked if any prior sibling is not yet done.
  2372. Finally, if the parent is blocked because of ordered siblings of its own,
  2373. the child will also be blocked."
  2374. :set (lambda (var val)
  2375. (set var val)
  2376. (if val
  2377. (add-hook 'org-blocker-hook
  2378. 'org-block-todo-from-children-or-siblings-or-parent)
  2379. (remove-hook 'org-blocker-hook
  2380. 'org-block-todo-from-children-or-siblings-or-parent)))
  2381. :group 'org-todo
  2382. :type 'boolean)
  2383. (defcustom org-enforce-todo-checkbox-dependencies nil
  2384. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2385. When this is nil, checkboxes have no influence on switching TODO states.
  2386. When non-nil, you first need to check off all check boxes before the TODO
  2387. entry can be switched to DONE.
  2388. This variable needs to be set before org.el is loaded, and you need to
  2389. restart Emacs after a change to make the change effective. The only way
  2390. to change is while Emacs is running is through the customize interface."
  2391. :set (lambda (var val)
  2392. (set var val)
  2393. (if val
  2394. (add-hook 'org-blocker-hook
  2395. 'org-block-todo-from-checkboxes)
  2396. (remove-hook 'org-blocker-hook
  2397. 'org-block-todo-from-checkboxes)))
  2398. :group 'org-todo
  2399. :type 'boolean)
  2400. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2401. "Non-nil means inserting a TODO heading is treated as state change.
  2402. So when the command `\\[org-insert-todo-heading]' is used, state change
  2403. logging will apply if appropriate. When nil, the new TODO item will
  2404. be inserted directly, and no logging will take place."
  2405. :group 'org-todo
  2406. :type 'boolean)
  2407. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2408. "Non-nil means switching TODO states with S-cursor counts as state change.
  2409. This is the default behavior. However, setting this to nil allows a
  2410. convenient way to select a TODO state and bypass any logging associated
  2411. with that."
  2412. :group 'org-todo
  2413. :type 'boolean)
  2414. (defcustom org-todo-state-tags-triggers nil
  2415. "Tag changes that should be triggered by TODO state changes.
  2416. This is a list. Each entry is
  2417. (state-change (tag . flag) .......)
  2418. State-change can be a string with a state, and empty string to indicate the
  2419. state that has no TODO keyword, or it can be one of the symbols `todo'
  2420. or `done', meaning any not-done or done state, respectively."
  2421. :group 'org-todo
  2422. :group 'org-tags
  2423. :type '(repeat
  2424. (cons (choice :tag "When changing to"
  2425. (const :tag "Not-done state" todo)
  2426. (const :tag "Done state" done)
  2427. (string :tag "State"))
  2428. (repeat
  2429. (cons :tag "Tag action"
  2430. (string :tag "Tag")
  2431. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2432. (defcustom org-log-done nil
  2433. "Information to record when a task moves to the DONE state.
  2434. Possible values are:
  2435. nil Don't add anything, just change the keyword
  2436. time Add a time stamp to the task
  2437. note Prompt for a note and add it with template `org-log-note-headings'
  2438. This option can also be set with on a per-file-basis with
  2439. #+STARTUP: nologdone
  2440. #+STARTUP: logdone
  2441. #+STARTUP: lognotedone
  2442. You can have local logging settings for a subtree by setting the LOGGING
  2443. property to one or more of these keywords."
  2444. :group 'org-todo
  2445. :group 'org-progress
  2446. :type '(choice
  2447. (const :tag "No logging" nil)
  2448. (const :tag "Record CLOSED timestamp" time)
  2449. (const :tag "Record CLOSED timestamp with note." note)))
  2450. ;; Normalize old uses of org-log-done.
  2451. (cond
  2452. ((eq org-log-done t) (setq org-log-done 'time))
  2453. ((and (listp org-log-done) (memq 'done org-log-done))
  2454. (setq org-log-done 'note)))
  2455. (defcustom org-log-reschedule nil
  2456. "Information to record when the scheduling date of a tasks is modified.
  2457. Possible values are:
  2458. nil Don't add anything, just change the date
  2459. time Add a time stamp to the task
  2460. note Prompt for a note and add it with template `org-log-note-headings'
  2461. This option can also be set with on a per-file-basis with
  2462. #+STARTUP: nologreschedule
  2463. #+STARTUP: logreschedule
  2464. #+STARTUP: lognotereschedule"
  2465. :group 'org-todo
  2466. :group 'org-progress
  2467. :type '(choice
  2468. (const :tag "No logging" nil)
  2469. (const :tag "Record timestamp" time)
  2470. (const :tag "Record timestamp with note." note)))
  2471. (defcustom org-log-redeadline nil
  2472. "Information to record when the deadline date of a tasks is modified.
  2473. Possible values are:
  2474. nil Don't add anything, just change the date
  2475. time Add a time stamp to the task
  2476. note Prompt for a note and add it with template `org-log-note-headings'
  2477. This option can also be set with on a per-file-basis with
  2478. #+STARTUP: nologredeadline
  2479. #+STARTUP: logredeadline
  2480. #+STARTUP: lognoteredeadline
  2481. You can have local logging settings for a subtree by setting the LOGGING
  2482. property to one or more of these keywords."
  2483. :group 'org-todo
  2484. :group 'org-progress
  2485. :type '(choice
  2486. (const :tag "No logging" nil)
  2487. (const :tag "Record timestamp" time)
  2488. (const :tag "Record timestamp with note." note)))
  2489. (defcustom org-log-note-clock-out nil
  2490. "Non-nil means record a note when clocking out of an item.
  2491. This can also be configured on a per-file basis by adding one of
  2492. the following lines anywhere in the buffer:
  2493. #+STARTUP: lognoteclock-out
  2494. #+STARTUP: nolognoteclock-out"
  2495. :group 'org-todo
  2496. :group 'org-progress
  2497. :type 'boolean)
  2498. (defcustom org-log-done-with-time t
  2499. "Non-nil means the CLOSED time stamp will contain date and time.
  2500. When nil, only the date will be recorded."
  2501. :group 'org-progress
  2502. :type 'boolean)
  2503. (defcustom org-log-note-headings
  2504. '((done . "CLOSING NOTE %t")
  2505. (state . "State %-12s from %-12S %t")
  2506. (note . "Note taken on %t")
  2507. (reschedule . "Rescheduled from %S on %t")
  2508. (delschedule . "Not scheduled, was %S on %t")
  2509. (redeadline . "New deadline from %S on %t")
  2510. (deldeadline . "Removed deadline, was %S on %t")
  2511. (refile . "Refiled on %t")
  2512. (clock-out . ""))
  2513. "Headings for notes added to entries.
  2514. The value is an alist, with the car being a symbol indicating the
  2515. note context, and the cdr is the heading to be used. The heading
  2516. may also be the empty string. The following placeholders can be
  2517. used:
  2518. %t a time stamp.
  2519. %T an active time stamp instead the default inactive one
  2520. %d a short-format time stamp.
  2521. %D an active short-format time stamp.
  2522. %s the new TODO state or time stamp (inactive), in double quotes.
  2523. %S the old TODO state or time stamp (inactive), in double quotes.
  2524. %u the user name.
  2525. %U full user name.
  2526. In fact, it is not a good idea to change the `state' entry,
  2527. because Agenda Log mode depends on the format of these entries."
  2528. :group 'org-todo
  2529. :group 'org-progress
  2530. :type '(list :greedy t
  2531. (cons (const :tag "Heading when closing an item" done) string)
  2532. (cons (const :tag
  2533. "Heading when changing todo state (todo sequence only)"
  2534. state) string)
  2535. (cons (const :tag "Heading when just taking a note" note) string)
  2536. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2537. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2538. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2539. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2540. (cons (const :tag "Heading when refiling" refile) string)
  2541. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2542. (unless (assq 'note org-log-note-headings)
  2543. (push '(note . "%t") org-log-note-headings))
  2544. (defcustom org-log-into-drawer nil
  2545. "Non-nil means insert state change notes and time stamps into a drawer.
  2546. When nil, state changes notes will be inserted after the headline and
  2547. any scheduling and clock lines, but not inside a drawer.
  2548. The value of this variable should be the name of the drawer to use.
  2549. LOGBOOK is proposed as the default drawer for this purpose, you can
  2550. also set this to a string to define the drawer of your choice.
  2551. A value of t is also allowed, representing \"LOGBOOK\".
  2552. A value of t or nil can also be set with on a per-file-basis with
  2553. #+STARTUP: logdrawer
  2554. #+STARTUP: nologdrawer
  2555. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2556. will be ignored.
  2557. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2558. a subtree.
  2559. Do not check directly this variable in a Lisp program. Call
  2560. function `org-log-into-drawer' instead."
  2561. :group 'org-todo
  2562. :group 'org-progress
  2563. :type '(choice
  2564. (const :tag "Not into a drawer" nil)
  2565. (const :tag "LOGBOOK" t)
  2566. (string :tag "Other")))
  2567. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2568. (defun org-log-into-drawer ()
  2569. "Name of the log drawer, as a string, or nil.
  2570. This is the value of `org-log-into-drawer'. However, if the
  2571. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2572. be used instead of the default value."
  2573. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2574. (cond ((equal p "nil") nil)
  2575. ((equal p "t") "LOGBOOK")
  2576. ((stringp p) p)
  2577. (p "LOGBOOK")
  2578. ((stringp org-log-into-drawer) org-log-into-drawer)
  2579. (org-log-into-drawer "LOGBOOK"))))
  2580. (defcustom org-log-state-notes-insert-after-drawers nil
  2581. "Non-nil means insert state change notes after any drawers in entry.
  2582. Only the drawers that *immediately* follow the headline and the
  2583. deadline/scheduled line are skipped.
  2584. When nil, insert notes right after the heading and perhaps the line
  2585. with deadline/scheduling if present.
  2586. This variable will have no effect if `org-log-into-drawer' is
  2587. set."
  2588. :group 'org-todo
  2589. :group 'org-progress
  2590. :type 'boolean)
  2591. (defcustom org-log-states-order-reversed t
  2592. "Non-nil means the latest state note will be directly after heading.
  2593. When nil, the state change notes will be ordered according to time.
  2594. This option can also be set with on a per-file-basis with
  2595. #+STARTUP: logstatesreversed
  2596. #+STARTUP: nologstatesreversed"
  2597. :group 'org-todo
  2598. :group 'org-progress
  2599. :type 'boolean)
  2600. (defcustom org-todo-repeat-to-state nil
  2601. "The TODO state to which a repeater should return the repeating task.
  2602. By default this is the first task in a TODO sequence, or the previous state
  2603. in a TODO_TYP set. But you can specify another task here.
  2604. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2605. :group 'org-todo
  2606. :version "24.1"
  2607. :type '(choice (const :tag "Head of sequence" nil)
  2608. (string :tag "Specific state")))
  2609. (defcustom org-log-repeat 'time
  2610. "Non-nil means record moving through the DONE state when triggering repeat.
  2611. An auto-repeating task is immediately switched back to TODO when
  2612. marked DONE. If you are not logging state changes (by adding \"@\"
  2613. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2614. record a closing note, there will be no record of the task moving
  2615. through DONE. This variable forces taking a note anyway.
  2616. nil Don't force a record
  2617. time Record a time stamp
  2618. note Prompt for a note and add it with template `org-log-note-headings'
  2619. This option can also be set with on a per-file-basis with
  2620. #+STARTUP: nologrepeat
  2621. #+STARTUP: logrepeat
  2622. #+STARTUP: lognoterepeat
  2623. You can have local logging settings for a subtree by setting the LOGGING
  2624. property to one or more of these keywords."
  2625. :group 'org-todo
  2626. :group 'org-progress
  2627. :type '(choice
  2628. (const :tag "Don't force a record" nil)
  2629. (const :tag "Force recording the DONE state" time)
  2630. (const :tag "Force recording a note with the DONE state" note)))
  2631. (defgroup org-priorities nil
  2632. "Priorities in Org mode."
  2633. :tag "Org Priorities"
  2634. :group 'org-todo)
  2635. (defcustom org-enable-priority-commands t
  2636. "Non-nil means priority commands are active.
  2637. When nil, these commands will be disabled, so that you never accidentally
  2638. set a priority."
  2639. :group 'org-priorities
  2640. :type 'boolean)
  2641. (defcustom org-highest-priority ?A
  2642. "The highest priority of TODO items. A character like ?A, ?B etc.
  2643. Must have a smaller ASCII number than `org-lowest-priority'."
  2644. :group 'org-priorities
  2645. :type 'character)
  2646. (defcustom org-lowest-priority ?C
  2647. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2648. Must have a larger ASCII number than `org-highest-priority'."
  2649. :group 'org-priorities
  2650. :type 'character)
  2651. (defcustom org-default-priority ?B
  2652. "The default priority of TODO items.
  2653. This is the priority an item gets if no explicit priority is given.
  2654. When starting to cycle on an empty priority the first step in the cycle
  2655. depends on `org-priority-start-cycle-with-default'. The resulting first
  2656. step priority must not exceed the range from `org-highest-priority' to
  2657. `org-lowest-priority' which means that `org-default-priority' has to be
  2658. in this range exclusive or inclusive the range boundaries. Else the
  2659. first step refuses to set the default and the second will fall back
  2660. to (depending on the command used) the highest or lowest priority."
  2661. :group 'org-priorities
  2662. :type 'character)
  2663. (defcustom org-priority-start-cycle-with-default t
  2664. "Non-nil means start with default priority when starting to cycle.
  2665. When this is nil, the first step in the cycle will be (depending on the
  2666. command used) one higher or lower than the default priority.
  2667. See also `org-default-priority'."
  2668. :group 'org-priorities
  2669. :type 'boolean)
  2670. (defcustom org-get-priority-function nil
  2671. "Function to extract the priority from a string.
  2672. The string is normally the headline. If this is nil Org computes the
  2673. priority from the priority cookie like [#A] in the headline. It returns
  2674. an integer, increasing by 1000 for each priority level.
  2675. The user can set a different function here, which should take a string
  2676. as an argument and return the numeric priority."
  2677. :group 'org-priorities
  2678. :version "24.1"
  2679. :type '(choice
  2680. (const nil)
  2681. (function)))
  2682. (defgroup org-time nil
  2683. "Options concerning time stamps and deadlines in Org mode."
  2684. :tag "Org Time"
  2685. :group 'org)
  2686. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2687. "Number of minutes to round time stamps to.
  2688. \\<org-mode-map>\
  2689. These are two values, the first applies when first creating a time stamp.
  2690. The second applies when changing it with the commands `S-up' and `S-down'.
  2691. When changing the time stamp, this means that it will change in steps
  2692. of N minutes, as given by the second value.
  2693. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2694. numbers should be factors of 60, so for example 5, 10, 15.
  2695. When this is larger than 1, you can still force an exact time stamp by using
  2696. a double prefix argument to a time stamp command like \
  2697. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2698. and by using a prefix arg to `S-up/down' to specify the exact number
  2699. of minutes to shift."
  2700. :group 'org-time
  2701. :get (lambda (var) ; Make sure both elements are there
  2702. (if (integerp (default-value var))
  2703. (list (default-value var) 5)
  2704. (default-value var)))
  2705. :type '(list
  2706. (integer :tag "when inserting times")
  2707. (integer :tag "when modifying times")))
  2708. ;; Normalize old customizations of this variable.
  2709. (when (integerp org-time-stamp-rounding-minutes)
  2710. (setq org-time-stamp-rounding-minutes
  2711. (list org-time-stamp-rounding-minutes
  2712. org-time-stamp-rounding-minutes)))
  2713. (defcustom org-display-custom-times nil
  2714. "Non-nil means overlay custom formats over all time stamps.
  2715. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2716. To turn this on on a per-file basis, insert anywhere in the file:
  2717. #+STARTUP: customtime"
  2718. :group 'org-time
  2719. :set 'set-default
  2720. :type 'sexp)
  2721. (make-variable-buffer-local 'org-display-custom-times)
  2722. (defcustom org-time-stamp-custom-formats
  2723. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2724. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2725. These are overlaid over the default ISO format if the variable
  2726. `org-display-custom-times' is set. Time like %H:%M should be at the
  2727. end of the second format. The custom formats are also honored by export
  2728. commands, if custom time display is turned on at the time of export."
  2729. :group 'org-time
  2730. :type 'sexp)
  2731. (defun org-time-stamp-format (&optional long inactive)
  2732. "Get the right format for a time string."
  2733. (let ((f (if long (cdr org-time-stamp-formats)
  2734. (car org-time-stamp-formats))))
  2735. (if inactive
  2736. (concat "[" (substring f 1 -1) "]")
  2737. f)))
  2738. (defcustom org-deadline-warning-days 14
  2739. "Number of days before expiration during which a deadline becomes active.
  2740. This variable governs the display in sparse trees and in the agenda.
  2741. When 0 or negative, it means use this number (the absolute value of it)
  2742. even if a deadline has a different individual lead time specified.
  2743. Custom commands can set this variable in the options section."
  2744. :group 'org-time
  2745. :group 'org-agenda-daily/weekly
  2746. :type 'integer)
  2747. (defcustom org-scheduled-delay-days 0
  2748. "Number of days before a scheduled item becomes active.
  2749. This variable governs the display in sparse trees and in the agenda.
  2750. The default value (i.e. 0) means: don't delay scheduled item.
  2751. When negative, it means use this number (the absolute value of it)
  2752. even if a scheduled item has a different individual delay time
  2753. specified.
  2754. Custom commands can set this variable in the options section."
  2755. :group 'org-time
  2756. :group 'org-agenda-daily/weekly
  2757. :version "24.4"
  2758. :package-version '(Org . "8.0")
  2759. :type 'integer)
  2760. (defcustom org-read-date-prefer-future t
  2761. "Non-nil means assume future for incomplete date input from user.
  2762. This affects the following situations:
  2763. 1. The user gives a month but not a year.
  2764. For example, if it is April and you enter \"feb 2\", this will be read
  2765. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2766. 2. The user gives a day, but no month.
  2767. For example, if today is the 15th, and you enter \"3\", Org will read
  2768. this as the third of *next* month. However, if you enter \"17\",
  2769. it will be considered as *this* month.
  2770. If you set this variable to the symbol `time', then also the following
  2771. will work:
  2772. 3. If the user gives a time.
  2773. If the time is before now, it will be interpreted as tomorrow.
  2774. Currently none of this works for ISO week specifications.
  2775. When this option is nil, the current day, month and year will always be
  2776. used as defaults.
  2777. See also `org-agenda-jump-prefer-future'."
  2778. :group 'org-time
  2779. :type '(choice
  2780. (const :tag "Never" nil)
  2781. (const :tag "Check month and day" t)
  2782. (const :tag "Check month, day, and time" time)))
  2783. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2784. "Should the agenda jump command prefer the future for incomplete dates?
  2785. The default is to do the same as configured in `org-read-date-prefer-future'.
  2786. But you can also set a deviating value here.
  2787. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2788. :group 'org-agenda
  2789. :group 'org-time
  2790. :version "24.1"
  2791. :type '(choice
  2792. (const :tag "Use org-read-date-prefer-future"
  2793. org-read-date-prefer-future)
  2794. (const :tag "Never" nil)
  2795. (const :tag "Always" t)))
  2796. (defcustom org-read-date-force-compatible-dates t
  2797. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2798. Depending on the system Emacs is running on, certain dates cannot
  2799. be represented with the type used internally to represent time.
  2800. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2801. correctly. Some systems allow for earlier dates, some for later,
  2802. some for both. One way to find out it to insert any date into an
  2803. Org buffer, putting the cursor on the year and hitting S-up and
  2804. S-down to test the range.
  2805. When this variable is set to t, the date/time prompt will not let
  2806. you specify dates outside the 1970-2037 range, so it is certain that
  2807. these dates will work in whatever version of Emacs you are
  2808. running, and also that you can move a file from one Emacs implementation
  2809. to another. WHenever Org is forcing the year for you, it will display
  2810. a message and beep.
  2811. When this variable is nil, Org will check if the date is
  2812. representable in the specific Emacs implementation you are using.
  2813. If not, it will force a year, usually the current year, and beep
  2814. to remind you. Currently this setting is not recommended because
  2815. the likelihood that you will open your Org files in an Emacs that
  2816. has limited date range is not negligible.
  2817. A workaround for this problem is to use diary sexp dates for time
  2818. stamps outside of this range."
  2819. :group 'org-time
  2820. :version "24.1"
  2821. :type 'boolean)
  2822. (defcustom org-read-date-display-live t
  2823. "Non-nil means display current interpretation of date prompt live.
  2824. This display will be in an overlay, in the minibuffer."
  2825. :group 'org-time
  2826. :type 'boolean)
  2827. (defcustom org-read-date-popup-calendar t
  2828. "Non-nil means pop up a calendar when prompting for a date.
  2829. In the calendar, the date can be selected with mouse-1. However, the
  2830. minibuffer will also be active, and you can simply enter the date as well.
  2831. When nil, only the minibuffer will be available."
  2832. :group 'org-time
  2833. :type 'boolean)
  2834. (defvaralias 'org-popup-calendar-for-date-prompt
  2835. 'org-read-date-popup-calendar)
  2836. (defcustom org-extend-today-until 0
  2837. "The hour when your day really ends. Must be an integer.
  2838. This has influence for the following applications:
  2839. - When switching the agenda to \"today\". It it is still earlier than
  2840. the time given here, the day recognized as TODAY is actually yesterday.
  2841. - When a date is read from the user and it is still before the time given
  2842. here, the current date and time will be assumed to be yesterday, 23:59.
  2843. Also, timestamps inserted in capture templates follow this rule.
  2844. IMPORTANT: This is a feature whose implementation is and likely will
  2845. remain incomplete. Really, it is only here because past midnight seems to
  2846. be the favorite working time of John Wiegley :-)"
  2847. :group 'org-time
  2848. :type 'integer)
  2849. (defcustom org-use-effective-time nil
  2850. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2851. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2852. \"effective time\" of any timestamps between midnight and 8am will be
  2853. 23:59 of the previous day."
  2854. :group 'org-time
  2855. :version "24.1"
  2856. :type 'boolean)
  2857. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2858. "When non-nil, use the last clock out time for `org-todo'.
  2859. Note that this option has precedence over the combined use of
  2860. `org-use-effective-time' and `org-extend-today-until'."
  2861. :group 'org-time
  2862. :version "24.4"
  2863. :package-version '(Org . "8.0")
  2864. :type 'boolean)
  2865. (defcustom org-edit-timestamp-down-means-later nil
  2866. "Non-nil means S-down will increase the time in a time stamp.
  2867. When nil, S-up will increase."
  2868. :group 'org-time
  2869. :type 'boolean)
  2870. (defcustom org-calendar-follow-timestamp-change t
  2871. "Non-nil means make the calendar window follow timestamp changes.
  2872. When a timestamp is modified and the calendar window is visible, it will be
  2873. moved to the new date."
  2874. :group 'org-time
  2875. :type 'boolean)
  2876. (defgroup org-tags nil
  2877. "Options concerning tags in Org mode."
  2878. :tag "Org Tags"
  2879. :group 'org)
  2880. (defcustom org-tag-alist nil
  2881. "Default tags available in Org files.
  2882. The value of this variable is an alist. Associations either:
  2883. (TAG)
  2884. (TAG . SELECT)
  2885. (SPECIAL)
  2886. where TAG is a tag as a string, SELECT is character, used to
  2887. select that tag through the fast tag selection interface, and
  2888. SPECIAL is one of the following keywords: `:startgroup',
  2889. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2890. `:newline'. These keywords are used to define a hierarchy of
  2891. tags. See manual for details.
  2892. When this variable is nil, Org mode bases tag input on what is
  2893. already in the buffer. The value can be overridden locally by
  2894. using a TAGS keyword, e.g.,
  2895. #+TAGS: tag1 tag2
  2896. See also `org-tag-persistent-alist' to sidestep this behavior."
  2897. :group 'org-tags
  2898. :type '(repeat
  2899. (choice
  2900. (cons :tag "Tag with key"
  2901. (string :tag "Tag name")
  2902. (character :tag "Access char"))
  2903. (list :tag "Tag" (string :tag "Tag name"))
  2904. (const :tag "Start radio group" (:startgroup))
  2905. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2906. (const :tag "Group tags delimiter" (:grouptags))
  2907. (const :tag "End radio group" (:endgroup))
  2908. (const :tag "End tag group, non distinct" (:endgrouptag))
  2909. (const :tag "New line" (:newline)))))
  2910. (defcustom org-tag-persistent-alist nil
  2911. "Tags always available in Org files.
  2912. The value of this variable is an alist. Associations either:
  2913. (TAG)
  2914. (TAG . SELECT)
  2915. (SPECIAL)
  2916. where TAG is a tag as a string, SELECT is a character, used to
  2917. select that tag through the fast tag selection interface, and
  2918. SPECIAL is one of the following keywords: `:startgroup',
  2919. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2920. `:newline'. These keywords are used to define a hierarchy of
  2921. tags. See manual for details.
  2922. Unlike to `org-tag-alist', tags defined in this variable do not
  2923. depend on a local TAGS keyword. Instead, to disable these tags
  2924. on a per-file basis, insert anywhere in the file:
  2925. #+STARTUP: noptag"
  2926. :group 'org-tags
  2927. :type '(repeat
  2928. (choice
  2929. (cons :tag "Tag with key"
  2930. (string :tag "Tag name")
  2931. (character :tag "Access char"))
  2932. (list :tag "Tag" (string :tag "Tag name"))
  2933. (const :tag "Start radio group" (:startgroup))
  2934. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2935. (const :tag "Group tags delimiter" (:grouptags))
  2936. (const :tag "End radio group" (:endgroup))
  2937. (const :tag "End tag group, non distinct" (:endgrouptag))
  2938. (const :tag "New line" (:newline)))))
  2939. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2940. "If non-nil, always offer completion for all tags of all agenda files.
  2941. Instead of customizing this variable directly, you might want to
  2942. set it locally for capture buffers, because there no list of
  2943. tags in that file can be created dynamically (there are none).
  2944. (add-hook \\='org-capture-mode-hook
  2945. (lambda ()
  2946. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2947. :group 'org-tags
  2948. :version "24.1"
  2949. :type 'boolean)
  2950. (defvar org-file-tags nil
  2951. "List of tags that can be inherited by all entries in the file.
  2952. The tags will be inherited if the variable `org-use-tag-inheritance'
  2953. says they should be.
  2954. This variable is populated from #+FILETAGS lines.")
  2955. (defcustom org-use-fast-tag-selection 'auto
  2956. "Non-nil means use fast tag selection scheme.
  2957. This is a special interface to select and deselect tags with single keys.
  2958. When nil, fast selection is never used.
  2959. When the symbol `auto', fast selection is used if and only if selection
  2960. characters for tags have been configured, either through the variable
  2961. `org-tag-alist' or through a #+TAGS line in the buffer.
  2962. When t, fast selection is always used and selection keys are assigned
  2963. automatically if necessary."
  2964. :group 'org-tags
  2965. :type '(choice
  2966. (const :tag "Always" t)
  2967. (const :tag "Never" nil)
  2968. (const :tag "When selection characters are configured" auto)))
  2969. (defcustom org-fast-tag-selection-single-key nil
  2970. "Non-nil means fast tag selection exits after first change.
  2971. When nil, you have to press RET to exit it.
  2972. During fast tag selection, you can toggle this flag with `C-c'.
  2973. This variable can also have the value `expert'. In this case, the window
  2974. displaying the tags menu is not even shown, until you press C-c again."
  2975. :group 'org-tags
  2976. :type '(choice
  2977. (const :tag "No" nil)
  2978. (const :tag "Yes" t)
  2979. (const :tag "Expert" expert)))
  2980. (defvar org-fast-tag-selection-include-todo nil
  2981. "Non-nil means fast tags selection interface will also offer TODO states.
  2982. This is an undocumented feature, you should not rely on it.")
  2983. (defcustom org-tags-column -77
  2984. "The column to which tags should be indented in a headline.
  2985. If this number is positive, it specifies the column. If it is negative,
  2986. it means that the tags should be flushright to that column. For example,
  2987. -80 works well for a normal 80 character screen.
  2988. When 0, place tags directly after headline text, with only one space in
  2989. between."
  2990. :group 'org-tags
  2991. :type 'integer)
  2992. (defcustom org-auto-align-tags t
  2993. "Non-nil keeps tags aligned when modifying headlines.
  2994. Some operations (i.e. demoting) change the length of a headline and
  2995. therefore shift the tags around. With this option turned on, after
  2996. each such operation the tags are again aligned to `org-tags-column'."
  2997. :group 'org-tags
  2998. :type 'boolean)
  2999. (defcustom org-use-tag-inheritance t
  3000. "Non-nil means tags in levels apply also for sublevels.
  3001. When nil, only the tags directly given in a specific line apply there.
  3002. This may also be a list of tags that should be inherited, or a regexp that
  3003. matches tags that should be inherited. Additional control is possible
  3004. with the variable `org-tags-exclude-from-inheritance' which gives an
  3005. explicit list of tags to be excluded from inheritance, even if the value of
  3006. `org-use-tag-inheritance' would select it for inheritance.
  3007. If this option is t, a match early-on in a tree can lead to a large
  3008. number of matches in the subtree when constructing the agenda or creating
  3009. a sparse tree. If you only want to see the first match in a tree during
  3010. a search, check out the variable `org-tags-match-list-sublevels'."
  3011. :group 'org-tags
  3012. :type '(choice
  3013. (const :tag "Not" nil)
  3014. (const :tag "Always" t)
  3015. (repeat :tag "Specific tags" (string :tag "Tag"))
  3016. (regexp :tag "Tags matched by regexp")))
  3017. (defcustom org-tags-exclude-from-inheritance nil
  3018. "List of tags that should never be inherited.
  3019. This is a way to exclude a few tags from inheritance. For way to do
  3020. the opposite, to actively allow inheritance for selected tags,
  3021. see the variable `org-use-tag-inheritance'."
  3022. :group 'org-tags
  3023. :type '(repeat (string :tag "Tag")))
  3024. (defun org-tag-inherit-p (tag)
  3025. "Check if TAG is one that should be inherited."
  3026. (cond
  3027. ((member tag org-tags-exclude-from-inheritance) nil)
  3028. ((eq org-use-tag-inheritance t) t)
  3029. ((not org-use-tag-inheritance) nil)
  3030. ((stringp org-use-tag-inheritance)
  3031. (string-match org-use-tag-inheritance tag))
  3032. ((listp org-use-tag-inheritance)
  3033. (member tag org-use-tag-inheritance))
  3034. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3035. (defcustom org-tags-match-list-sublevels t
  3036. "Non-nil means list also sublevels of headlines matching a search.
  3037. This variable applies to tags/property searches, and also to stuck
  3038. projects because this search is based on a tags match as well.
  3039. When set to the symbol `indented', sublevels are indented with
  3040. leading dots.
  3041. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3042. the sublevels of a headline matching a tag search often also match
  3043. the same search. Listing all of them can create very long lists.
  3044. Setting this variable to nil causes subtrees of a match to be skipped.
  3045. This variable is semi-obsolete and probably should always be true. It
  3046. is better to limit inheritance to certain tags using the variables
  3047. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3048. :group 'org-tags
  3049. :type '(choice
  3050. (const :tag "No, don't list them" nil)
  3051. (const :tag "Yes, do list them" t)
  3052. (const :tag "List them, indented with leading dots" indented)))
  3053. (defcustom org-tags-sort-function nil
  3054. "When set, tags are sorted using this function as a comparator."
  3055. :group 'org-tags
  3056. :type '(choice
  3057. (const :tag "No sorting" nil)
  3058. (const :tag "Alphabetical" string<)
  3059. (const :tag "Reverse alphabetical" string>)
  3060. (function :tag "Custom function" nil)))
  3061. (defvar org-tags-history nil
  3062. "History of minibuffer reads for tags.")
  3063. (defvar org-last-tags-completion-table nil
  3064. "The last used completion table for tags.")
  3065. (defvar org-after-tags-change-hook nil
  3066. "Hook that is run after the tags in a line have changed.")
  3067. (defgroup org-properties nil
  3068. "Options concerning properties in Org mode."
  3069. :tag "Org Properties"
  3070. :group 'org)
  3071. (defcustom org-property-format "%-10s %s"
  3072. "How property key/value pairs should be formatted by `indent-line'.
  3073. When `indent-line' hits a property definition, it will format the line
  3074. according to this format, mainly to make sure that the values are
  3075. lined-up with respect to each other."
  3076. :group 'org-properties
  3077. :type 'string)
  3078. (defcustom org-properties-postprocess-alist nil
  3079. "Alist of properties and functions to adjust inserted values.
  3080. Elements of this alist must be of the form
  3081. ([string] [function])
  3082. where [string] must be a property name and [function] must be a
  3083. lambda expression: this lambda expression must take one argument,
  3084. the value to adjust, and return the new value as a string.
  3085. For example, this element will allow the property \"Remaining\"
  3086. to be updated wrt the relation between the \"Effort\" property
  3087. and the clock summary:
  3088. ((\"Remaining\" (lambda(value)
  3089. (let ((clocksum (org-clock-sum-current-item))
  3090. (effort (org-duration-to-minutes
  3091. (org-entry-get (point) \"Effort\"))))
  3092. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3093. :group 'org-properties
  3094. :version "24.1"
  3095. :type '(alist :key-type (string :tag "Property")
  3096. :value-type (function :tag "Function")))
  3097. (defcustom org-use-property-inheritance nil
  3098. "Non-nil means properties apply also for sublevels.
  3099. This setting is chiefly used during property searches. Turning it on can
  3100. cause significant overhead when doing a search, which is why it is not
  3101. on by default.
  3102. When nil, only the properties directly given in the current entry count.
  3103. When t, every property is inherited. The value may also be a list of
  3104. properties that should have inheritance, or a regular expression matching
  3105. properties that should be inherited.
  3106. However, note that some special properties use inheritance under special
  3107. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3108. and the properties ending in \"_ALL\" when they are used as descriptor
  3109. for valid values of a property.
  3110. Note for programmers:
  3111. When querying an entry with `org-entry-get', you can control if inheritance
  3112. should be used. By default, `org-entry-get' looks only at the local
  3113. properties. You can request inheritance by setting the inherit argument
  3114. to t (to force inheritance) or to `selective' (to respect the setting
  3115. in this variable)."
  3116. :group 'org-properties
  3117. :type '(choice
  3118. (const :tag "Not" nil)
  3119. (const :tag "Always" t)
  3120. (repeat :tag "Specific properties" (string :tag "Property"))
  3121. (regexp :tag "Properties matched by regexp")))
  3122. (defun org-property-inherit-p (property)
  3123. "Return a non-nil value if PROPERTY should be inherited."
  3124. (cond
  3125. ((eq org-use-property-inheritance t) t)
  3126. ((not org-use-property-inheritance) nil)
  3127. ((stringp org-use-property-inheritance)
  3128. (string-match org-use-property-inheritance property))
  3129. ((listp org-use-property-inheritance)
  3130. (member-ignore-case property org-use-property-inheritance))
  3131. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3132. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3133. "The default column format, if no other format has been defined.
  3134. This variable can be set on the per-file basis by inserting a line
  3135. #+COLUMNS: %25ITEM ....."
  3136. :group 'org-properties
  3137. :type 'string)
  3138. (defcustom org-columns-ellipses ".."
  3139. "The ellipses to be used when a field in column view is truncated.
  3140. When this is the empty string, as many characters as possible are shown,
  3141. but then there will be no visual indication that the field has been truncated.
  3142. When this is a string of length N, the last N characters of a truncated
  3143. field are replaced by this string. If the column is narrower than the
  3144. ellipses string, only part of the ellipses string will be shown."
  3145. :group 'org-properties
  3146. :type 'string)
  3147. (defconst org-global-properties-fixed
  3148. '(("VISIBILITY_ALL" . "folded children content all")
  3149. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3150. "List of property/value pairs that can be inherited by any entry.
  3151. These are fixed values, for the preset properties. The user variable
  3152. that can be used to add to this list is `org-global-properties'.
  3153. The entries in this list are cons cells where the car is a property
  3154. name and cdr is a string with the value. If the value represents
  3155. multiple items like an \"_ALL\" property, separate the items by
  3156. spaces.")
  3157. (defcustom org-global-properties nil
  3158. "List of property/value pairs that can be inherited by any entry.
  3159. This list will be combined with the constant `org-global-properties-fixed'.
  3160. The entries in this list are cons cells where the car is a property
  3161. name and cdr is a string with the value.
  3162. You can set buffer-local values for the same purpose in the variable
  3163. `org-file-properties' this by adding lines like
  3164. #+PROPERTY: NAME VALUE"
  3165. :group 'org-properties
  3166. :type '(repeat
  3167. (cons (string :tag "Property")
  3168. (string :tag "Value"))))
  3169. (defvar-local org-file-properties nil
  3170. "List of property/value pairs that can be inherited by any entry.
  3171. Valid for the current buffer.
  3172. This variable is populated from #+PROPERTY lines.")
  3173. (defgroup org-agenda nil
  3174. "Options concerning agenda views in Org mode."
  3175. :tag "Org Agenda"
  3176. :group 'org)
  3177. (defvar-local org-category nil
  3178. "Variable used by org files to set a category for agenda display.
  3179. Such files should use a file variable to set it, for example
  3180. # -*- mode: org; org-category: \"ELisp\"
  3181. or contain a special line
  3182. #+CATEGORY: ELisp
  3183. If the file does not specify a category, then file's base name
  3184. is used instead.")
  3185. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3186. (defcustom org-agenda-files nil
  3187. "The files to be used for agenda display.
  3188. If an entry is a directory, all files in that directory that are matched
  3189. by `org-agenda-file-regexp' will be part of the file list.
  3190. If the value of the variable is not a list but a single file name, then
  3191. the list of agenda files is actually stored and maintained in that file,
  3192. one agenda file per line. In this file paths can be given relative to
  3193. `org-directory'. Tilde expansion and environment variable substitution
  3194. are also made.
  3195. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3196. and removed with `\\[org-remove-file]'."
  3197. :group 'org-agenda
  3198. :type '(choice
  3199. (repeat :tag "List of files and directories" file)
  3200. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3201. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3202. "Regular expression to match files for `org-agenda-files'.
  3203. If any element in the list in that variable contains a directory instead
  3204. of a normal file, all files in that directory that are matched by this
  3205. regular expression will be included."
  3206. :group 'org-agenda
  3207. :type 'regexp)
  3208. (defcustom org-agenda-text-search-extra-files nil
  3209. "List of extra files to be searched by text search commands.
  3210. These files will be searched in addition to the agenda files by the
  3211. commands `org-search-view' (`\\[org-agenda] s') \
  3212. and `org-occur-in-agenda-files'.
  3213. Note that these files will only be searched for text search commands,
  3214. not for the other agenda views like todo lists, tag searches or the weekly
  3215. agenda. This variable is intended to list notes and possibly archive files
  3216. that should also be searched by these two commands.
  3217. In fact, if the first element in the list is the symbol `agenda-archives',
  3218. then all archive files of all agenda files will be added to the search
  3219. scope."
  3220. :group 'org-agenda
  3221. :type '(set :greedy t
  3222. (const :tag "Agenda Archives" agenda-archives)
  3223. (repeat :inline t (file))))
  3224. (defvaralias 'org-agenda-multi-occur-extra-files
  3225. 'org-agenda-text-search-extra-files)
  3226. (defcustom org-agenda-skip-unavailable-files nil
  3227. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3228. A nil value means to remove them, after a query, from the list."
  3229. :group 'org-agenda
  3230. :type 'boolean)
  3231. (defcustom org-calendar-to-agenda-key [?c]
  3232. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3233. The command `org-calendar-goto-agenda' will be bound to this key. The
  3234. default is the character `c' because then `c' can be used to switch back and
  3235. forth between agenda and calendar."
  3236. :group 'org-agenda
  3237. :type 'sexp)
  3238. (defcustom org-calendar-insert-diary-entry-key [?i]
  3239. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3240. This option is irrelevant until `org-agenda-diary-file' has been configured
  3241. to point to an Org file. When that is the case, the command
  3242. `org-agenda-diary-entry' will be bound to the key given here, by default
  3243. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3244. if you want to continue doing this, you need to change this to a different
  3245. key."
  3246. :group 'org-agenda
  3247. :type 'sexp)
  3248. (defcustom org-agenda-diary-file 'diary-file
  3249. "File to which to add new entries with the `i' key in agenda and calendar.
  3250. When this is the symbol `diary-file', the functionality in the Emacs
  3251. calendar will be used to add entries to the `diary-file'. But when this
  3252. points to a file, `org-agenda-diary-entry' will be used instead."
  3253. :group 'org-agenda
  3254. :type '(choice
  3255. (const :tag "The standard Emacs diary file" diary-file)
  3256. (file :tag "Special Org file diary entries")))
  3257. (eval-after-load "calendar"
  3258. '(progn
  3259. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3260. 'org-calendar-goto-agenda)
  3261. (add-hook 'calendar-mode-hook
  3262. (lambda ()
  3263. (unless (eq org-agenda-diary-file 'diary-file)
  3264. (define-key calendar-mode-map
  3265. org-calendar-insert-diary-entry-key
  3266. 'org-agenda-diary-entry))))))
  3267. (defgroup org-latex nil
  3268. "Options for embedding LaTeX code into Org mode."
  3269. :tag "Org LaTeX"
  3270. :group 'org)
  3271. (defcustom org-format-latex-options
  3272. '(:foreground default :background default :scale 1.0
  3273. :html-foreground "Black" :html-background "Transparent"
  3274. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3275. "Options for creating images from LaTeX fragments.
  3276. This is a property list with the following properties:
  3277. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3278. `default' means use the foreground of the default face.
  3279. `auto' means use the foreground from the text face.
  3280. :background the background color, or \"Transparent\".
  3281. `default' means use the background of the default face.
  3282. `auto' means use the background from the text face.
  3283. :scale a scaling factor for the size of the images, to get more pixels
  3284. :html-foreground, :html-background, :html-scale
  3285. the same numbers for HTML export.
  3286. :matchers a list indicating which matchers should be used to
  3287. find LaTeX fragments. Valid members of this list are:
  3288. \"begin\" find environments
  3289. \"$1\" find single characters surrounded by $.$
  3290. \"$\" find math expressions surrounded by $...$
  3291. \"$$\" find math expressions surrounded by $$....$$
  3292. \"\\(\" find math expressions surrounded by \\(...\\)
  3293. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3294. :group 'org-latex
  3295. :type 'plist)
  3296. (defcustom org-format-latex-signal-error t
  3297. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3298. When nil, just push out a message."
  3299. :group 'org-latex
  3300. :version "24.1"
  3301. :type 'boolean)
  3302. (defcustom org-latex-to-mathml-jar-file nil
  3303. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3304. Use this to specify additional executable file say a jar file.
  3305. When using MathToWeb as the converter, specify the full-path to
  3306. your mathtoweb.jar file."
  3307. :group 'org-latex
  3308. :version "24.1"
  3309. :type '(choice
  3310. (const :tag "None" nil)
  3311. (file :tag "JAR file" :must-match t)))
  3312. (defcustom org-latex-to-mathml-convert-command nil
  3313. "Command to convert LaTeX fragments to MathML.
  3314. Replace format-specifiers in the command as noted below and use
  3315. `shell-command' to convert LaTeX to MathML.
  3316. %j: Executable file in fully expanded form as specified by
  3317. `org-latex-to-mathml-jar-file'.
  3318. %I: Input LaTeX file in fully expanded form.
  3319. %i: The latex fragment to be converted.
  3320. %o: Output MathML file.
  3321. This command is used by `org-create-math-formula'.
  3322. When using MathToWeb as the converter, set this option to
  3323. \"java -jar %j -unicode -force -df %o %I\".
  3324. When using LaTeXML set this option to
  3325. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3326. :group 'org-latex
  3327. :version "24.1"
  3328. :type '(choice
  3329. (const :tag "None" nil)
  3330. (string :tag "\nShell command")))
  3331. (defcustom org-preview-latex-default-process 'dvipng
  3332. "The default process to convert LaTeX fragments to image files.
  3333. All available processes and theirs documents can be found in
  3334. `org-preview-latex-process-alist', which see."
  3335. :group 'org-latex
  3336. :version "26.1"
  3337. :package-version '(Org . "9.0")
  3338. :type 'symbol)
  3339. (defcustom org-preview-latex-process-alist
  3340. '((dvipng
  3341. :programs ("latex" "dvipng")
  3342. :description "dvi > png"
  3343. :message "you need to install the programs: latex and dvipng."
  3344. :image-input-type "dvi"
  3345. :image-output-type "png"
  3346. :image-size-adjust (1.0 . 1.0)
  3347. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3348. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3349. (dvisvgm
  3350. :programs ("latex" "dvisvgm")
  3351. :description "dvi > svg"
  3352. :message "you need to install the programs: latex and dvisvgm."
  3353. :use-xcolor t
  3354. :image-input-type "dvi"
  3355. :image-output-type "svg"
  3356. :image-size-adjust (1.7 . 1.5)
  3357. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3358. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3359. (imagemagick
  3360. :programs ("latex" "convert")
  3361. :description "pdf > png"
  3362. :message "you need to install the programs: latex and imagemagick."
  3363. :use-xcolor t
  3364. :image-input-type "pdf"
  3365. :image-output-type "png"
  3366. :image-size-adjust (1.0 . 1.0)
  3367. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3368. :image-converter
  3369. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3370. "Definitions of external processes for LaTeX previewing.
  3371. Org mode can use some external commands to generate TeX snippet's images for
  3372. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3373. `org-create-formula-image' how to call them.
  3374. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3375. PROPERTIES accepts the following attributes:
  3376. :programs list of strings, required programs.
  3377. :description string, describe the process.
  3378. :message string, message it when required programs cannot be found.
  3379. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3380. :image-output-type string, output file type of image converter (e.g., \"png\").
  3381. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3382. deal with background and foreground color of image.
  3383. Otherwise, dvipng style background and foreground color
  3384. format are generated. You may then refer to them in
  3385. command options with \"%F\" and \"%B\".
  3386. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3387. image size showed in buffer and the cdr element is for
  3388. HTML file. This option is only useful for process
  3389. developers, users should use variable
  3390. `org-format-latex-options' instead.
  3391. :post-clean list of strings, files matched are to be cleaned up once
  3392. the image is generated. When nil, the files with \".dvi\",
  3393. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3394. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3395. be cleaned up.
  3396. :latex-header list of strings, the LaTeX header of the snippet file.
  3397. When nil, the fallback value is used instead, which is
  3398. controlled by `org-format-latex-header',
  3399. `org-latex-default-packages-alist' and
  3400. `org-latex-packages-alist', which see.
  3401. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3402. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3403. replaced with values defined below.
  3404. :image-converter list of image converter commands strings. Each of them is
  3405. given to the shell and supports any of the following
  3406. place-holders defined below.
  3407. Place-holders used by `:image-converter' and `:latex-compiler':
  3408. %f input file name
  3409. %b base name of input file
  3410. %o base directory of input file
  3411. %O absolute output file name
  3412. Place-holders only used by `:image-converter':
  3413. %F foreground of image
  3414. %B background of image
  3415. %D dpi, which is used to adjust image size by some processing commands.
  3416. %S the image size scale ratio, which is used to adjust image size by some
  3417. processing commands."
  3418. :group 'org-latex
  3419. :version "26.1"
  3420. :package-version '(Org . "9.0")
  3421. :type '(alist :tag "LaTeX to image backends"
  3422. :value-type (plist)))
  3423. (defcustom org-preview-latex-image-directory "ltximg/"
  3424. "Path to store latex preview images.
  3425. A relative path here creates many directories relative to the
  3426. processed org files paths. An absolute path puts all preview
  3427. images at the same place."
  3428. :group 'org-latex
  3429. :version "26.1"
  3430. :package-version '(Org . "9.0")
  3431. :type 'string)
  3432. (defun org-format-latex-mathml-available-p ()
  3433. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3434. (save-match-data
  3435. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3436. org-latex-to-mathml-convert-command)
  3437. (let ((executable (car (split-string
  3438. org-latex-to-mathml-convert-command))))
  3439. (when (executable-find executable)
  3440. (if (string-match
  3441. "%j" org-latex-to-mathml-convert-command)
  3442. (file-readable-p org-latex-to-mathml-jar-file)
  3443. t))))))
  3444. (defcustom org-format-latex-header "\\documentclass{article}
  3445. \\usepackage[usenames]{color}
  3446. \[PACKAGES]
  3447. \[DEFAULT-PACKAGES]
  3448. \\pagestyle{empty} % do not remove
  3449. % The settings below are copied from fullpage.sty
  3450. \\setlength{\\textwidth}{\\paperwidth}
  3451. \\addtolength{\\textwidth}{-3cm}
  3452. \\setlength{\\oddsidemargin}{1.5cm}
  3453. \\addtolength{\\oddsidemargin}{-2.54cm}
  3454. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3455. \\setlength{\\textheight}{\\paperheight}
  3456. \\addtolength{\\textheight}{-\\headheight}
  3457. \\addtolength{\\textheight}{-\\headsep}
  3458. \\addtolength{\\textheight}{-\\footskip}
  3459. \\addtolength{\\textheight}{-3cm}
  3460. \\setlength{\\topmargin}{1.5cm}
  3461. \\addtolength{\\topmargin}{-2.54cm}"
  3462. "The document header used for processing LaTeX fragments.
  3463. It is imperative that this header make sure that no page number
  3464. appears on the page. The package defined in the variables
  3465. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3466. will either replace the placeholder \"[PACKAGES]\" in this
  3467. header, or they will be appended."
  3468. :group 'org-latex
  3469. :type 'string)
  3470. (defun org-set-packages-alist (var val)
  3471. "Set the packages alist and make sure it has 3 elements per entry."
  3472. (set var (mapcar (lambda (x)
  3473. (if (and (consp x) (= (length x) 2))
  3474. (list (car x) (nth 1 x) t)
  3475. x))
  3476. val)))
  3477. (defun org-get-packages-alist (var)
  3478. "Get the packages alist and make sure it has 3 elements per entry."
  3479. (mapcar (lambda (x)
  3480. (if (and (consp x) (= (length x) 2))
  3481. (list (car x) (nth 1 x) t)
  3482. x))
  3483. (default-value var)))
  3484. (defcustom org-latex-default-packages-alist
  3485. '(("AUTO" "inputenc" t ("pdflatex"))
  3486. ("T1" "fontenc" t ("pdflatex"))
  3487. ("" "graphicx" t)
  3488. ("" "grffile" t)
  3489. ("" "longtable" nil)
  3490. ("" "wrapfig" nil)
  3491. ("" "rotating" nil)
  3492. ("normalem" "ulem" t)
  3493. ("" "amsmath" t)
  3494. ("" "textcomp" t)
  3495. ("" "amssymb" t)
  3496. ("" "capt-of" nil)
  3497. ("" "hyperref" nil))
  3498. "Alist of default packages to be inserted in the header.
  3499. Change this only if one of the packages here causes an
  3500. incompatibility with another package you are using.
  3501. The packages in this list are needed by one part or another of
  3502. Org mode to function properly:
  3503. - inputenc, fontenc: for basic font and character selection
  3504. - graphicx: for including images
  3505. - grffile: allow periods and spaces in graphics file names
  3506. - longtable: For multipage tables
  3507. - wrapfig: for figure placement
  3508. - rotating: for sideways figures and tables
  3509. - ulem: for underline and strike-through
  3510. - amsmath: for subscript and superscript and math environments
  3511. - textcomp, amssymb: for various symbols used
  3512. for interpreting the entities in `org-entities'. You can skip
  3513. some of these packages if you don't use any of their symbols.
  3514. - capt-of: for captions outside of floats
  3515. - hyperref: for cross references
  3516. Therefore you should not modify this variable unless you know
  3517. what you are doing. The one reason to change it anyway is that
  3518. you might be loading some other package that conflicts with one
  3519. of the default packages. Each element is either a cell or
  3520. a string.
  3521. A cell is of the format
  3522. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3523. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3524. when compiling LaTeX snippets into images for inclusion into
  3525. non-LaTeX output. COMPILERS is a list of compilers that should
  3526. include the package, see `org-latex-compiler'. If the document
  3527. compiler is not in the list, and the list is non-nil, the package
  3528. will not be inserted in the final document.
  3529. A string will be inserted as-is in the header of the document."
  3530. :group 'org-latex
  3531. :group 'org-export-latex
  3532. :set 'org-set-packages-alist
  3533. :get 'org-get-packages-alist
  3534. :version "26.1"
  3535. :package-version '(Org . "8.3")
  3536. :type '(repeat
  3537. (choice
  3538. (list :tag "options/package pair"
  3539. (string :tag "options")
  3540. (string :tag "package")
  3541. (boolean :tag "Snippet"))
  3542. (string :tag "A line of LaTeX"))))
  3543. (defcustom org-latex-packages-alist nil
  3544. "Alist of packages to be inserted in every LaTeX header.
  3545. These will be inserted after `org-latex-default-packages-alist'.
  3546. Each element is either a cell or a string.
  3547. A cell is of the format:
  3548. (\"options\" \"package\" SNIPPET-FLAG)
  3549. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3550. needed when turning LaTeX snippets into images for inclusion into
  3551. non-LaTeX output.
  3552. A string will be inserted as-is in the header of the document.
  3553. Make sure that you only list packages here which:
  3554. - you want in every file;
  3555. - do not conflict with the setup in `org-format-latex-header';
  3556. - do not conflict with the default packages in
  3557. `org-latex-default-packages-alist'."
  3558. :group 'org-latex
  3559. :group 'org-export-latex
  3560. :set 'org-set-packages-alist
  3561. :get 'org-get-packages-alist
  3562. :type '(repeat
  3563. (choice
  3564. (list :tag "options/package pair"
  3565. (string :tag "options")
  3566. (string :tag "package")
  3567. (boolean :tag "Snippet"))
  3568. (string :tag "A line of LaTeX"))))
  3569. (defgroup org-appearance nil
  3570. "Settings for Org mode appearance."
  3571. :tag "Org Appearance"
  3572. :group 'org)
  3573. (defcustom org-level-color-stars-only nil
  3574. "Non-nil means fontify only the stars in each headline.
  3575. When nil, the entire headline is fontified.
  3576. Changing it requires restart of `font-lock-mode' to become effective
  3577. also in regions already fontified."
  3578. :group 'org-appearance
  3579. :type 'boolean)
  3580. (defcustom org-hide-leading-stars nil
  3581. "Non-nil means hide the first N-1 stars in a headline.
  3582. This works by using the face `org-hide' for these stars. This
  3583. face is white for a light background, and black for a dark
  3584. background. You may have to customize the face `org-hide' to
  3585. make this work.
  3586. Changing it requires restart of `font-lock-mode' to become effective
  3587. also in regions already fontified.
  3588. You may also set this on a per-file basis by adding one of the following
  3589. lines to the buffer:
  3590. #+STARTUP: hidestars
  3591. #+STARTUP: showstars"
  3592. :group 'org-appearance
  3593. :type 'boolean)
  3594. (defcustom org-hidden-keywords nil
  3595. "List of symbols corresponding to keywords to be hidden the org buffer.
  3596. For example, a value \\='(title) for this list will make the document's title
  3597. appear in the buffer without the initial #+TITLE: keyword."
  3598. :group 'org-appearance
  3599. :version "24.1"
  3600. :type '(set (const :tag "#+AUTHOR" author)
  3601. (const :tag "#+DATE" date)
  3602. (const :tag "#+EMAIL" email)
  3603. (const :tag "#+TITLE" title)))
  3604. (defcustom org-custom-properties nil
  3605. "List of properties (as strings) with a special meaning.
  3606. The default use of these custom properties is to let the user
  3607. hide them with `org-toggle-custom-properties-visibility'."
  3608. :group 'org-properties
  3609. :group 'org-appearance
  3610. :version "24.3"
  3611. :type '(repeat (string :tag "Property Name")))
  3612. (defcustom org-fontify-done-headline nil
  3613. "Non-nil means change the face of a headline if it is marked DONE.
  3614. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3615. When this is non-nil, the headline after the keyword is set to the
  3616. `org-headline-done' as an additional indication."
  3617. :group 'org-appearance
  3618. :type 'boolean)
  3619. (defcustom org-fontify-emphasized-text t
  3620. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3621. Changing this variable requires a restart of Emacs to take effect."
  3622. :group 'org-appearance
  3623. :type 'boolean)
  3624. (defcustom org-fontify-whole-heading-line nil
  3625. "Non-nil means fontify the whole line for headings.
  3626. This is useful when setting a background color for the
  3627. org-level-* faces."
  3628. :group 'org-appearance
  3629. :type 'boolean)
  3630. (defcustom org-highlight-latex-and-related nil
  3631. "Non-nil means highlight LaTeX related syntax in the buffer.
  3632. When non nil, the value should be a list containing any of the
  3633. following symbols:
  3634. `latex' Highlight LaTeX snippets and environments.
  3635. `script' Highlight subscript and superscript.
  3636. `entities' Highlight entities."
  3637. :group 'org-appearance
  3638. :version "24.4"
  3639. :package-version '(Org . "8.0")
  3640. :type '(choice
  3641. (const :tag "No highlighting" nil)
  3642. (set :greedy t :tag "Highlight"
  3643. (const :tag "LaTeX snippets and environments" latex)
  3644. (const :tag "Subscript and superscript" script)
  3645. (const :tag "Entities" entities))))
  3646. (defcustom org-hide-emphasis-markers nil
  3647. "Non-nil mean font-lock should hide the emphasis marker characters."
  3648. :group 'org-appearance
  3649. :type 'boolean)
  3650. (defcustom org-hide-macro-markers nil
  3651. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3652. :group 'org-appearance
  3653. :type 'boolean)
  3654. (defcustom org-pretty-entities nil
  3655. "Non-nil means show entities as UTF8 characters.
  3656. When nil, the \\name form remains in the buffer."
  3657. :group 'org-appearance
  3658. :version "24.1"
  3659. :type 'boolean)
  3660. (defcustom org-pretty-entities-include-sub-superscripts t
  3661. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3662. :group 'org-appearance
  3663. :version "24.1"
  3664. :type 'boolean)
  3665. (defvar org-emph-re nil
  3666. "Regular expression for matching emphasis.
  3667. After a match, the match groups contain these elements:
  3668. 0 The match of the full regular expression, including the characters
  3669. before and after the proper match
  3670. 1 The character before the proper match, or empty at beginning of line
  3671. 2 The proper match, including the leading and trailing markers
  3672. 3 The leading marker like * or /, indicating the type of highlighting
  3673. 4 The text between the emphasis markers, not including the markers
  3674. 5 The character after the match, empty at the end of a line")
  3675. (defvar org-verbatim-re nil
  3676. "Regular expression for matching verbatim text.")
  3677. (defvar org-emphasis-regexp-components) ; defined just below
  3678. (defvar org-emphasis-alist) ; defined just below
  3679. (defun org-set-emph-re (var val)
  3680. "Set variable and compute the emphasis regular expression."
  3681. (set var val)
  3682. (when (and (boundp 'org-emphasis-alist)
  3683. (boundp 'org-emphasis-regexp-components)
  3684. org-emphasis-alist org-emphasis-regexp-components)
  3685. (pcase-let*
  3686. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3687. (body (if (<= nl 0) body
  3688. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3689. (template
  3690. (format (concat "\\([%s]\\|^\\)" ;before markers
  3691. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3692. "\\([%s]\\|$\\)") ;after markers
  3693. pre border border body border post)))
  3694. (setq org-emph-re (format template "*/_+"))
  3695. (setq org-verbatim-re (format template "=~")))))
  3696. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3697. ;; set this option proved cumbersome. See this message/thread:
  3698. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3699. (defvar org-emphasis-regexp-components
  3700. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3701. "Components used to build the regular expression for emphasis.
  3702. This is a list with five entries. Terminology: In an emphasis string
  3703. like \" *strong word* \", we call the initial space PREMATCH, the final
  3704. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3705. and \"trong wor\" is the body. The different components in this variable
  3706. specify what is allowed/forbidden in each part:
  3707. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3708. post Chars allowed as postmatch. End of line will be allowed too.
  3709. border The chars *forbidden* as border characters.
  3710. body-regexp A regexp like \".\" to match a body character. Don't use
  3711. non-shy groups here, and don't allow newline here.
  3712. newline The maximum number of newlines allowed in an emphasis exp.
  3713. You need to reload Org or to restart Emacs after setting this.")
  3714. (defcustom org-emphasis-alist
  3715. '(("*" bold)
  3716. ("/" italic)
  3717. ("_" underline)
  3718. ("=" org-verbatim verbatim)
  3719. ("~" org-code verbatim)
  3720. ("+" (:strike-through t)))
  3721. "Alist of characters and faces to emphasize text.
  3722. Text starting and ending with a special character will be emphasized,
  3723. for example *bold*, _underlined_ and /italic/. This variable sets the
  3724. marker characters and the face to be used by font-lock for highlighting
  3725. in Org buffers.
  3726. You need to reload Org or to restart Emacs after customizing this."
  3727. :group 'org-appearance
  3728. :set 'org-set-emph-re
  3729. :version "24.4"
  3730. :package-version '(Org . "8.0")
  3731. :type '(repeat
  3732. (list
  3733. (string :tag "Marker character")
  3734. (choice
  3735. (face :tag "Font-lock-face")
  3736. (plist :tag "Face property list"))
  3737. (option (const verbatim)))))
  3738. (defvar org-protecting-blocks '("src" "example" "export")
  3739. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3740. This is needed for font-lock setup.")
  3741. ;;; Functions and variables from their packages
  3742. ;; Declared here to avoid compiler warnings
  3743. (defvar mark-active)
  3744. ;; Various packages
  3745. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3746. (declare-function calendar-forward-day "cal-move" (arg))
  3747. (declare-function calendar-goto-date "cal-move" (date))
  3748. (declare-function calendar-goto-today "cal-move" ())
  3749. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3750. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3751. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3752. (declare-function cdlatex-tab "ext:cdlatex" ())
  3753. (declare-function dired-get-filename
  3754. "dired"
  3755. (&optional localp no-error-if-not-filep))
  3756. (declare-function iswitchb-read-buffer
  3757. "iswitchb"
  3758. (prompt &optional
  3759. default require-match _predicate start matches-set))
  3760. (declare-function org-agenda-change-all-lines
  3761. "org-agenda"
  3762. (newhead hdmarker &optional fixface just-this))
  3763. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3764. "org-agenda"
  3765. (&optional end))
  3766. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3767. (declare-function org-agenda-format-item
  3768. "org-agenda"
  3769. (extra txt &optional level category tags dotime
  3770. remove-re habitp))
  3771. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3772. (declare-function org-agenda-save-markers-for-cut-and-paste
  3773. "org-agenda"
  3774. (beg end))
  3775. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3776. (declare-function org-agenda-skip "org-agenda" ())
  3777. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3778. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3779. (declare-function org-indent-mode "org-indent" (&optional arg))
  3780. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3781. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3782. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3783. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3784. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3785. (declare-function parse-time-string "parse-time" (string))
  3786. (defvar align-mode-rules-list)
  3787. (defvar calc-embedded-close-formula)
  3788. (defvar calc-embedded-open-formula)
  3789. (defvar calc-embedded-open-mode)
  3790. (defvar font-lock-unfontify-region-function)
  3791. (defvar iswitchb-temp-buflist)
  3792. (defvar org-agenda-tags-todo-honor-ignore-options)
  3793. (defvar remember-data-file)
  3794. (defvar texmathp-why)
  3795. ;;;###autoload
  3796. (defun turn-on-orgtbl ()
  3797. "Unconditionally turn on `orgtbl-mode'."
  3798. (require 'org-table)
  3799. (orgtbl-mode 1))
  3800. (defun org-at-table-p (&optional table-type)
  3801. "Non-nil if the cursor is inside an Org table.
  3802. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3803. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3804. (or (not (derived-mode-p 'org-mode))
  3805. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3806. (and e (or table-type
  3807. (eq 'org (org-element-property :type e))))))))
  3808. (defun org-at-table.el-p ()
  3809. "Non-nil when point is at a table.el table."
  3810. (and (org-match-line "[ \t]*[|+]")
  3811. (let ((element (org-element-at-point)))
  3812. (and (eq (org-element-type element) 'table)
  3813. (eq (org-element-property :type element) 'table.el)))))
  3814. (defun org-at-table-hline-p ()
  3815. "Non-nil when point is inside a hline in a table.
  3816. Assume point is already in a table."
  3817. (org-match-line org-table-hline-regexp))
  3818. (defun org-table-map-tables (function &optional quietly)
  3819. "Apply FUNCTION to the start of all tables in the buffer."
  3820. (org-with-wide-buffer
  3821. (goto-char (point-min))
  3822. (while (re-search-forward org-table-any-line-regexp nil t)
  3823. (unless quietly
  3824. (message "Mapping tables: %d%%"
  3825. (floor (* 100.0 (point)) (buffer-size))))
  3826. (beginning-of-line 1)
  3827. (when (and (looking-at org-table-line-regexp)
  3828. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3829. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3830. (save-excursion (funcall function))
  3831. (or (looking-at org-table-line-regexp)
  3832. (forward-char 1)))
  3833. (re-search-forward org-table-any-border-regexp nil 1)))
  3834. (unless quietly (message "Mapping tables: done")))
  3835. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3836. (declare-function org-clock-update-mode-line "org-clock" ())
  3837. (declare-function org-resolve-clocks "org-clock"
  3838. (&optional also-non-dangling-p prompt last-valid))
  3839. (defun org-at-TBLFM-p (&optional pos)
  3840. "Non-nil when point (or POS) is in #+TBLFM line."
  3841. (save-excursion
  3842. (goto-char (or pos (point)))
  3843. (beginning-of-line)
  3844. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3845. (eq (org-element-type (org-element-at-point)) 'table))))
  3846. (defvar org-clock-start-time)
  3847. (defvar org-clock-marker (make-marker)
  3848. "Marker recording the last clock-in.")
  3849. (defvar org-clock-hd-marker (make-marker)
  3850. "Marker recording the last clock-in, but the headline position.")
  3851. (defvar org-clock-heading ""
  3852. "The heading of the current clock entry.")
  3853. (defun org-clock-is-active ()
  3854. "Return the buffer where the clock is currently running.
  3855. Return nil if no clock is running."
  3856. (marker-buffer org-clock-marker))
  3857. (defun org-check-running-clock ()
  3858. "Check if the current buffer contains the running clock.
  3859. If yes, offer to stop it and to save the buffer with the changes."
  3860. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3861. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3862. (buffer-name))))
  3863. (org-clock-out)
  3864. (when (y-or-n-p "Save changed buffer?")
  3865. (save-buffer))))
  3866. (defun org-clocktable-try-shift (dir n)
  3867. "Check if this line starts a clock table, if yes, shift the time block."
  3868. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3869. (org-clocktable-shift dir n)))
  3870. ;;;###autoload
  3871. (defun org-clock-persistence-insinuate ()
  3872. "Set up hooks for clock persistence."
  3873. (require 'org-clock)
  3874. (add-hook 'org-mode-hook 'org-clock-load)
  3875. (add-hook 'kill-emacs-hook 'org-clock-save))
  3876. (defgroup org-archive nil
  3877. "Options concerning archiving in Org mode."
  3878. :tag "Org Archive"
  3879. :group 'org-structure)
  3880. (defcustom org-archive-location "%s_archive::"
  3881. "The location where subtrees should be archived.
  3882. The value of this variable is a string, consisting of two parts,
  3883. separated by a double-colon. The first part is a filename and
  3884. the second part is a headline.
  3885. When the filename is omitted, archiving happens in the same file.
  3886. %s in the filename will be replaced by the current file
  3887. name (without the directory part). Archiving to a different file
  3888. is useful to keep archived entries from contributing to the
  3889. Org Agenda.
  3890. The archived entries will be filed as subtrees of the specified
  3891. headline. When the headline is omitted, the subtrees are simply
  3892. filed away at the end of the file, as top-level entries. Also in
  3893. the heading you can use %s to represent the file name, this can be
  3894. useful when using the same archive for a number of different files.
  3895. Here are a few examples:
  3896. \"%s_archive::\"
  3897. If the current file is Projects.org, archive in file
  3898. Projects.org_archive, as top-level trees. This is the default.
  3899. \"::* Archived Tasks\"
  3900. Archive in the current file, under the top-level headline
  3901. \"* Archived Tasks\".
  3902. \"~/org/archive.org::\"
  3903. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3904. \"~/org/archive.org::* From %s\"
  3905. Archive in file ~/org/archive.org (absolute path), under headlines
  3906. \"From FILENAME\" where file name is the current file name.
  3907. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3908. The \"datetree/\" string is special, signifying to archive
  3909. items to the datetree. Items are placed in either the CLOSED
  3910. date of the item, or the current date if there is no CLOSED date.
  3911. The heading will be a subentry to the current date. There doesn't
  3912. need to be a heading, but there always needs to be a slash after
  3913. datetree. For example, to store archived items directly in the
  3914. datetree, use \"~/org/datetree.org::datetree/\".
  3915. \"basement::** Finished Tasks\"
  3916. Archive in file ./basement (relative path), as level 3 trees
  3917. below the level 2 heading \"** Finished Tasks\".
  3918. You may set this option on a per-file basis by adding to the buffer a
  3919. line like
  3920. #+ARCHIVE: basement::** Finished Tasks
  3921. You may also define it locally for a subtree by setting an ARCHIVE property
  3922. in the entry. If such a property is found in an entry, or anywhere up
  3923. the hierarchy, it will be used."
  3924. :group 'org-archive
  3925. :type 'string)
  3926. (defcustom org-agenda-skip-archived-trees t
  3927. "Non-nil means the agenda will skip any items located in archived trees.
  3928. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3929. variable is no longer recommended, you should leave it at the value t.
  3930. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3931. :group 'org-archive
  3932. :group 'org-agenda-skip
  3933. :type 'boolean)
  3934. (defcustom org-columns-skip-archived-trees t
  3935. "Non-nil means ignore archived trees when creating column view."
  3936. :group 'org-archive
  3937. :group 'org-properties
  3938. :type 'boolean)
  3939. (defcustom org-cycle-open-archived-trees nil
  3940. "Non-nil means `org-cycle' will open archived trees.
  3941. An archived tree is a tree marked with the tag ARCHIVE.
  3942. When nil, archived trees will stay folded. You can still open them with
  3943. normal outline commands like `show-all', but not with the cycling commands."
  3944. :group 'org-archive
  3945. :group 'org-cycle
  3946. :type 'boolean)
  3947. (defcustom org-sparse-tree-open-archived-trees nil
  3948. "Non-nil means sparse tree construction shows matches in archived trees.
  3949. When nil, matches in these trees are highlighted, but the trees are kept in
  3950. collapsed state."
  3951. :group 'org-archive
  3952. :group 'org-sparse-trees
  3953. :type 'boolean)
  3954. (defcustom org-sparse-tree-default-date-type nil
  3955. "The default date type when building a sparse tree.
  3956. When this is nil, a date is a scheduled or a deadline timestamp.
  3957. Otherwise, these types are allowed:
  3958. all: all timestamps
  3959. active: only active timestamps (<...>)
  3960. inactive: only inactive timestamps ([...])
  3961. scheduled: only scheduled timestamps
  3962. deadline: only deadline timestamps"
  3963. :type '(choice (const :tag "Scheduled or deadline" nil)
  3964. (const :tag "All timestamps" all)
  3965. (const :tag "Only active timestamps" active)
  3966. (const :tag "Only inactive timestamps" inactive)
  3967. (const :tag "Only scheduled timestamps" scheduled)
  3968. (const :tag "Only deadline timestamps" deadline)
  3969. (const :tag "Only closed timestamps" closed))
  3970. :version "26.1"
  3971. :package-version '(Org . "8.3")
  3972. :group 'org-sparse-trees)
  3973. (defun org-cycle-hide-archived-subtrees (state)
  3974. "Re-hide all archived subtrees after a visibility state change.
  3975. STATE should be one of the symbols listed in the docstring of
  3976. `org-cycle-hook'."
  3977. (when (and (not org-cycle-open-archived-trees)
  3978. (not (memq state '(overview folded))))
  3979. (save-excursion
  3980. (let* ((globalp (memq state '(contents all)))
  3981. (beg (if globalp (point-min) (point)))
  3982. (end (if globalp (point-max) (org-end-of-subtree t))))
  3983. (org-hide-archived-subtrees beg end)
  3984. (goto-char beg)
  3985. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3986. (message "%s" (substitute-command-keys
  3987. "Subtree is archived and stays closed. Use \
  3988. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3989. (defun org-force-cycle-archived ()
  3990. "Cycle subtree even if it is archived."
  3991. (interactive)
  3992. (setq this-command 'org-cycle)
  3993. (let ((org-cycle-open-archived-trees t))
  3994. (call-interactively 'org-cycle)))
  3995. (defun org-hide-archived-subtrees (beg end)
  3996. "Re-hide all archived subtrees after a visibility state change."
  3997. (org-with-wide-buffer
  3998. (let ((case-fold-search nil)
  3999. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4000. (goto-char beg)
  4001. ;; Include headline point is currently on.
  4002. (beginning-of-line)
  4003. (while (and (< (point) end) (re-search-forward re end t))
  4004. (when (member org-archive-tag (org-get-tags))
  4005. (org-flag-subtree t)
  4006. (org-end-of-subtree t))))))
  4007. (declare-function outline-end-of-heading "outline" ())
  4008. (declare-function outline-flag-region "outline" (from to flag))
  4009. (defun org-flag-subtree (flag)
  4010. (save-excursion
  4011. (org-back-to-heading t)
  4012. (outline-end-of-heading)
  4013. (outline-flag-region (point)
  4014. (progn (org-end-of-subtree t) (point))
  4015. flag)))
  4016. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4017. ;; Declare Column View Code
  4018. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4019. (declare-function org-columns-compute "org-colview" (property))
  4020. ;; Declare ID code
  4021. (declare-function org-id-store-link "org-id")
  4022. (declare-function org-id-locations-load "org-id")
  4023. (declare-function org-id-locations-save "org-id")
  4024. (defvar org-id-track-globally)
  4025. ;;; Variables for pre-computed regular expressions, all buffer local
  4026. (defvar-local org-todo-regexp nil
  4027. "Matches any of the TODO state keywords.
  4028. Since TODO keywords are case-sensitive, `case-fold-search' is
  4029. expected to be bound to nil when matching against this regexp.")
  4030. (defvar-local org-not-done-regexp nil
  4031. "Matches any of the TODO state keywords except the last one.
  4032. Since TODO keywords are case-sensitive, `case-fold-search' is
  4033. expected to be bound to nil when matching against this regexp.")
  4034. (defvar-local org-not-done-heading-regexp nil
  4035. "Matches a TODO headline that is not done.
  4036. Since TODO keywords are case-sensitive, `case-fold-search' is
  4037. expected to be bound to nil when matching against this regexp.")
  4038. (defvar-local org-todo-line-regexp nil
  4039. "Matches a headline and puts TODO state into group 2 if present.
  4040. Since TODO keywords are case-sensitive, `case-fold-search' is
  4041. expected to be bound to nil when matching against this regexp.")
  4042. (defvar-local org-complex-heading-regexp nil
  4043. "Matches a headline and puts everything into groups:
  4044. group 1: Stars
  4045. group 2: The TODO keyword, maybe
  4046. group 3: Priority cookie
  4047. group 4: True headline
  4048. group 5: Tags
  4049. Since TODO keywords are case-sensitive, `case-fold-search' is
  4050. expected to be bound to nil when matching against this regexp.")
  4051. (defvar-local org-complex-heading-regexp-format nil
  4052. "Printf format to make regexp to match an exact headline.
  4053. This regexp will match the headline of any node which has the
  4054. exact headline text that is put into the format, but may have any
  4055. TODO state, priority and tags.")
  4056. (defvar-local org-todo-line-tags-regexp nil
  4057. "Matches a headline and puts TODO state into group 2 if present.
  4058. Also put tags into group 4 if tags are present.")
  4059. (defconst org-plain-time-of-day-regexp
  4060. (concat
  4061. "\\(\\<[012]?[0-9]"
  4062. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4063. "\\(--?"
  4064. "\\(\\<[012]?[0-9]"
  4065. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4066. "\\)?")
  4067. "Regular expression to match a plain time or time range.
  4068. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4069. groups carry important information:
  4070. 0 the full match
  4071. 1 the first time, range or not
  4072. 8 the second time, if it is a range.")
  4073. (defconst org-plain-time-extension-regexp
  4074. (concat
  4075. "\\(\\<[012]?[0-9]"
  4076. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4077. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4078. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4079. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4080. groups carry important information:
  4081. 0 the full match
  4082. 7 hours of duration
  4083. 9 minutes of duration")
  4084. (defconst org-stamp-time-of-day-regexp
  4085. (concat
  4086. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4087. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4088. "\\(--?"
  4089. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4090. "Regular expression to match a timestamp time or time range.
  4091. After a match, the following groups carry important information:
  4092. 0 the full match
  4093. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4094. 2 the first time, range or not
  4095. 4 the second time, if it is a range.")
  4096. (defconst org-startup-options
  4097. '(("fold" org-startup-folded t)
  4098. ("overview" org-startup-folded t)
  4099. ("nofold" org-startup-folded nil)
  4100. ("showall" org-startup-folded nil)
  4101. ("showeverything" org-startup-folded showeverything)
  4102. ("content" org-startup-folded content)
  4103. ("indent" org-startup-indented t)
  4104. ("noindent" org-startup-indented nil)
  4105. ("hidestars" org-hide-leading-stars t)
  4106. ("showstars" org-hide-leading-stars nil)
  4107. ("odd" org-odd-levels-only t)
  4108. ("oddeven" org-odd-levels-only nil)
  4109. ("align" org-startup-align-all-tables t)
  4110. ("noalign" org-startup-align-all-tables nil)
  4111. ("shrink" org-startup-shrink-all-tables t)
  4112. ("inlineimages" org-startup-with-inline-images t)
  4113. ("noinlineimages" org-startup-with-inline-images nil)
  4114. ("latexpreview" org-startup-with-latex-preview t)
  4115. ("nolatexpreview" org-startup-with-latex-preview nil)
  4116. ("customtime" org-display-custom-times t)
  4117. ("logdone" org-log-done time)
  4118. ("lognotedone" org-log-done note)
  4119. ("nologdone" org-log-done nil)
  4120. ("lognoteclock-out" org-log-note-clock-out t)
  4121. ("nolognoteclock-out" org-log-note-clock-out nil)
  4122. ("logrepeat" org-log-repeat state)
  4123. ("lognoterepeat" org-log-repeat note)
  4124. ("logdrawer" org-log-into-drawer t)
  4125. ("nologdrawer" org-log-into-drawer nil)
  4126. ("logstatesreversed" org-log-states-order-reversed t)
  4127. ("nologstatesreversed" org-log-states-order-reversed nil)
  4128. ("nologrepeat" org-log-repeat nil)
  4129. ("logreschedule" org-log-reschedule time)
  4130. ("lognotereschedule" org-log-reschedule note)
  4131. ("nologreschedule" org-log-reschedule nil)
  4132. ("logredeadline" org-log-redeadline time)
  4133. ("lognoteredeadline" org-log-redeadline note)
  4134. ("nologredeadline" org-log-redeadline nil)
  4135. ("logrefile" org-log-refile time)
  4136. ("lognoterefile" org-log-refile note)
  4137. ("nologrefile" org-log-refile nil)
  4138. ("fninline" org-footnote-define-inline t)
  4139. ("nofninline" org-footnote-define-inline nil)
  4140. ("fnlocal" org-footnote-section nil)
  4141. ("fnauto" org-footnote-auto-label t)
  4142. ("fnprompt" org-footnote-auto-label nil)
  4143. ("fnconfirm" org-footnote-auto-label confirm)
  4144. ("fnplain" org-footnote-auto-label plain)
  4145. ("fnadjust" org-footnote-auto-adjust t)
  4146. ("nofnadjust" org-footnote-auto-adjust nil)
  4147. ("constcgs" constants-unit-system cgs)
  4148. ("constSI" constants-unit-system SI)
  4149. ("noptag" org-tag-persistent-alist nil)
  4150. ("hideblocks" org-hide-block-startup t)
  4151. ("nohideblocks" org-hide-block-startup nil)
  4152. ("beamer" org-startup-with-beamer-mode t)
  4153. ("entitiespretty" org-pretty-entities t)
  4154. ("entitiesplain" org-pretty-entities nil))
  4155. "Variable associated with STARTUP options for org-mode.
  4156. Each element is a list of three items: the startup options (as written
  4157. in the #+STARTUP line), the corresponding variable, and the value to set
  4158. this variable to if the option is found. An optional forth element PUSH
  4159. means to push this value onto the list in the variable.")
  4160. (defcustom org-group-tags t
  4161. "When non-nil (the default), use group tags.
  4162. This can be turned on/off through `org-toggle-tags-groups'."
  4163. :group 'org-tags
  4164. :group 'org-startup
  4165. :type 'boolean)
  4166. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4167. (defun org-toggle-tags-groups ()
  4168. "Toggle support for group tags.
  4169. Support for group tags is controlled by the option
  4170. `org-group-tags', which is non-nil by default."
  4171. (interactive)
  4172. (setq org-group-tags (not org-group-tags))
  4173. (cond ((and (derived-mode-p 'org-agenda-mode)
  4174. org-group-tags)
  4175. (org-agenda-redo))
  4176. ((derived-mode-p 'org-mode)
  4177. (let ((org-inhibit-startup t)) (org-mode))))
  4178. (message "Groups tags support has been turned %s"
  4179. (if org-group-tags "on" "off")))
  4180. (defun org-set-regexps-and-options (&optional tags-only)
  4181. "Precompute regular expressions used in the current buffer.
  4182. When optional argument TAGS-ONLY is non-nil, only compute tags
  4183. related expressions."
  4184. (when (derived-mode-p 'org-mode)
  4185. (let ((alist (org--setup-collect-keywords
  4186. (org-make-options-regexp
  4187. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4188. (and (not tags-only)
  4189. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4190. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4191. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4192. ;; Startup options. Get this early since it does change
  4193. ;; behavior for other options (e.g., tags).
  4194. (let ((startup (cdr (assq 'startup alist))))
  4195. (dolist (option startup)
  4196. (let ((entry (assoc-string option org-startup-options t)))
  4197. (when entry
  4198. (let ((var (nth 1 entry))
  4199. (val (nth 2 entry)))
  4200. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4201. (unless (listp (symbol-value var))
  4202. (set (make-local-variable var) nil))
  4203. (add-to-list var val)))))))
  4204. (setq-local org-file-tags
  4205. (mapcar #'org-add-prop-inherited
  4206. (cdr (assq 'filetags alist))))
  4207. (setq org-current-tag-alist
  4208. (append org-tag-persistent-alist
  4209. (let ((tags (cdr (assq 'tags alist))))
  4210. (if tags (org-tag-string-to-alist tags)
  4211. org-tag-alist))))
  4212. (setq org-tag-groups-alist
  4213. (org-tag-alist-to-groups org-current-tag-alist))
  4214. (unless tags-only
  4215. ;; File properties.
  4216. (setq-local org-file-properties (cdr (assq 'property alist)))
  4217. ;; Archive location.
  4218. (let ((archive (cdr (assq 'archive alist))))
  4219. (when archive (setq-local org-archive-location archive)))
  4220. ;; Category.
  4221. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4222. (when cat
  4223. (setq-local org-category (intern cat))
  4224. (setq-local org-file-properties
  4225. (org--update-property-plist
  4226. "CATEGORY" cat org-file-properties))))
  4227. ;; Columns.
  4228. (let ((column (cdr (assq 'columns alist))))
  4229. (when column (setq-local org-columns-default-format column)))
  4230. ;; Constants.
  4231. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4232. ;; Link abbreviations.
  4233. (let ((links (cdr (assq 'link alist))))
  4234. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4235. ;; Priorities.
  4236. (let ((priorities (cdr (assq 'priorities alist))))
  4237. (when priorities
  4238. (setq-local org-highest-priority (nth 0 priorities))
  4239. (setq-local org-lowest-priority (nth 1 priorities))
  4240. (setq-local org-default-priority (nth 2 priorities))))
  4241. ;; Scripts.
  4242. (let ((scripts (assq 'scripts alist)))
  4243. (when scripts
  4244. (setq-local org-use-sub-superscripts (cdr scripts))))
  4245. ;; TODO keywords.
  4246. (setq-local org-todo-kwd-alist nil)
  4247. (setq-local org-todo-key-alist nil)
  4248. (setq-local org-todo-key-trigger nil)
  4249. (setq-local org-todo-keywords-1 nil)
  4250. (setq-local org-done-keywords nil)
  4251. (setq-local org-todo-heads nil)
  4252. (setq-local org-todo-sets nil)
  4253. (setq-local org-todo-log-states nil)
  4254. (let ((todo-sequences
  4255. (or (nreverse (cdr (assq 'todo alist)))
  4256. (let ((d (default-value 'org-todo-keywords)))
  4257. (if (not (stringp (car d))) d
  4258. ;; XXX: Backward compatibility code.
  4259. (list (cons org-todo-interpretation d)))))))
  4260. (dolist (sequence todo-sequences)
  4261. (let* ((sequence (or (run-hook-with-args-until-success
  4262. 'org-todo-setup-filter-hook sequence)
  4263. sequence))
  4264. (sequence-type (car sequence))
  4265. (keywords (cdr sequence))
  4266. (sep (member "|" keywords))
  4267. names alist)
  4268. (dolist (k (remove "|" keywords))
  4269. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4270. k)
  4271. (error "Invalid TODO keyword %s" k))
  4272. (let ((name (match-string 1 k))
  4273. (key (match-string 2 k))
  4274. (log (org-extract-log-state-settings k)))
  4275. (push name names)
  4276. (push (cons name (and key (string-to-char key))) alist)
  4277. (when log (push log org-todo-log-states))))
  4278. (let* ((names (nreverse names))
  4279. (done (if sep (org-remove-keyword-keys (cdr sep))
  4280. (last names)))
  4281. (head (car names))
  4282. (tail (list sequence-type head (car done) (org-last done))))
  4283. (add-to-list 'org-todo-heads head 'append)
  4284. (push names org-todo-sets)
  4285. (setq org-done-keywords (append org-done-keywords done nil))
  4286. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4287. (setq org-todo-key-alist
  4288. (append org-todo-key-alist
  4289. (and alist
  4290. (append '((:startgroup))
  4291. (nreverse alist)
  4292. '((:endgroup))))))
  4293. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4294. (setq org-todo-sets (nreverse org-todo-sets)
  4295. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4296. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4297. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4298. ;; Compute the regular expressions and other local variables.
  4299. ;; Using `org-outline-regexp-bol' would complicate them much,
  4300. ;; because of the fixed white space at the end of that string.
  4301. (unless org-done-keywords
  4302. (setq org-done-keywords
  4303. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4304. (setq org-not-done-keywords
  4305. (org-delete-all org-done-keywords
  4306. (copy-sequence org-todo-keywords-1))
  4307. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4308. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4309. org-not-done-heading-regexp
  4310. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4311. org-todo-line-regexp
  4312. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4313. org-complex-heading-regexp
  4314. (concat "^\\(\\*+\\)"
  4315. "\\(?: +" org-todo-regexp "\\)?"
  4316. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4317. "\\(?: +\\(.*?\\)\\)??"
  4318. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4319. "[ \t]*$")
  4320. org-complex-heading-regexp-format
  4321. (concat "^\\(\\*+\\)"
  4322. "\\(?: +" org-todo-regexp "\\)?"
  4323. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4324. "\\(?: +"
  4325. ;; Stats cookies can be stuck to body.
  4326. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4327. "\\(%s\\)"
  4328. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4329. "\\)"
  4330. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4331. "[ \t]*$")
  4332. org-todo-line-tags-regexp
  4333. (concat "^\\(\\*+\\)"
  4334. "\\(?: +" org-todo-regexp "\\)?"
  4335. "\\(?: +\\(.*?\\)\\)??"
  4336. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4337. "[ \t]*$"))
  4338. (org-compute-latex-and-related-regexp)))))
  4339. (defun org--setup-collect-keywords (regexp &optional files alist)
  4340. "Return setup keywords values as an alist.
  4341. REGEXP matches a subset of setup keywords. FILES is a list of
  4342. file names already visited. It is used to avoid circular setup
  4343. files. ALIST, when non-nil, is the alist computed so far.
  4344. Return value contains the following keys: `archive', `category',
  4345. `columns', `constants', `filetags', `link', `priorities',
  4346. `property', `scripts', `startup', `tags' and `todo'."
  4347. (org-with-wide-buffer
  4348. (goto-char (point-min))
  4349. (let ((case-fold-search t))
  4350. (while (re-search-forward regexp nil t)
  4351. (let ((element (org-element-at-point)))
  4352. (when (eq (org-element-type element) 'keyword)
  4353. (let ((key (org-element-property :key element))
  4354. (value (org-element-property :value element)))
  4355. (cond
  4356. ((equal key "ARCHIVE")
  4357. (when (org-string-nw-p value)
  4358. (push (cons 'archive value) alist)))
  4359. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4360. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4361. ((equal key "CONSTANTS")
  4362. (let* ((constants (assq 'constants alist))
  4363. (store (cdr constants)))
  4364. (dolist (pair (split-string value))
  4365. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4366. pair)
  4367. (let* ((name (match-string 1 pair))
  4368. (value (match-string 2 pair))
  4369. (old (assoc name store)))
  4370. (if old (setcdr old value)
  4371. (push (cons name value) store)))))
  4372. (if constants (setcdr constants store)
  4373. (push (cons 'constants store) alist))))
  4374. ((equal key "FILETAGS")
  4375. (when (org-string-nw-p value)
  4376. (let ((old (assq 'filetags alist))
  4377. (new (apply #'nconc
  4378. (mapcar (lambda (x) (org-split-string x ":"))
  4379. (split-string value)))))
  4380. (if old (setcdr old (append new (cdr old)))
  4381. (push (cons 'filetags new) alist)))))
  4382. ((equal key "LINK")
  4383. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4384. (let ((links (assq 'link alist))
  4385. (pair (cons (match-string-no-properties 1 value)
  4386. (match-string-no-properties 2 value))))
  4387. (if links (push pair (cdr links))
  4388. (push (list 'link pair) alist)))))
  4389. ((equal key "OPTIONS")
  4390. (when (and (org-string-nw-p value)
  4391. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4392. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4393. ((equal key "PRIORITIES")
  4394. (push (cons 'priorities
  4395. (let ((prio (split-string value)))
  4396. (if (< (length prio) 3) '(?A ?C ?B)
  4397. (mapcar #'string-to-char prio))))
  4398. alist))
  4399. ((equal key "PROPERTY")
  4400. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4401. (let* ((property (assq 'property alist))
  4402. (value (org--update-property-plist
  4403. (match-string-no-properties 1 value)
  4404. (match-string-no-properties 2 value)
  4405. (cdr property))))
  4406. (if property (setcdr property value)
  4407. (push (cons 'property value) alist)))))
  4408. ((equal key "STARTUP")
  4409. (let ((startup (assq 'startup alist)))
  4410. (if startup
  4411. (setcdr startup
  4412. (append (cdr startup) (split-string value)))
  4413. (push (cons 'startup (split-string value)) alist))))
  4414. ((equal key "TAGS")
  4415. (let ((tag-cell (assq 'tags alist)))
  4416. (if tag-cell
  4417. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4418. (push (cons 'tags value) alist))))
  4419. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4420. (let ((todo (assq 'todo alist))
  4421. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4422. (split-string value))))
  4423. (if todo (push value (cdr todo))
  4424. (push (list 'todo value) alist))))
  4425. ((equal key "SETUPFILE")
  4426. (unless buffer-read-only ; Do not check in Gnus messages.
  4427. (let ((f (and (org-string-nw-p value)
  4428. (expand-file-name
  4429. (org-unbracket-string "\"" "\"" value)))))
  4430. (when (and f (file-readable-p f) (not (member f files)))
  4431. (with-temp-buffer
  4432. (setq default-directory (file-name-directory f))
  4433. (insert-file-contents f)
  4434. (setq alist
  4435. ;; Fake Org mode to benefit from cache
  4436. ;; without recurring needlessly.
  4437. (let ((major-mode 'org-mode))
  4438. (org--setup-collect-keywords
  4439. regexp (cons f files) alist)))))))))))))))
  4440. alist)
  4441. (defun org-tag-string-to-alist (s)
  4442. "Return tag alist associated to string S.
  4443. S is a value for TAGS keyword or produced with
  4444. `org-tag-alist-to-string'. Return value is an alist suitable for
  4445. `org-tag-alist' or `org-tag-persistent-alist'."
  4446. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4447. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4448. "\\|{.+?}\\)" ; regular expression
  4449. "\\(?:(\\(.\\))\\)?\\'"))
  4450. alist group-flag)
  4451. (dolist (tokens lines (cdr (nreverse alist)))
  4452. (push '(:newline) alist)
  4453. (while tokens
  4454. (let ((token (pop tokens)))
  4455. (pcase token
  4456. ("{"
  4457. (push '(:startgroup) alist)
  4458. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4459. ("}"
  4460. (push '(:endgroup) alist)
  4461. (setq group-flag nil))
  4462. ("["
  4463. (push '(:startgrouptag) alist)
  4464. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4465. ("]"
  4466. (push '(:endgrouptag) alist)
  4467. (setq group-flag nil))
  4468. (":"
  4469. (push '(:grouptags) alist))
  4470. ((guard (string-match tag-re token))
  4471. (let ((tag (match-string 1 token))
  4472. (key (and (match-beginning 2)
  4473. (string-to-char (match-string 2 token)))))
  4474. ;; Push all tags in groups, no matter if they already
  4475. ;; appear somewhere else in the list.
  4476. (when (or group-flag (not (assoc tag alist)))
  4477. (push (cons tag key) alist))))))))))
  4478. (defun org-tag-alist-to-string (alist &optional skip-key)
  4479. "Return tag string associated to ALIST.
  4480. ALIST is an alist, as defined in `org-tag-alist' or
  4481. `org-tag-persistent-alist', or produced with
  4482. `org-tag-string-to-alist'.
  4483. Return value is a string suitable as a value for \"TAGS\"
  4484. keyword.
  4485. When optional argument SKIP-KEY is non-nil, skip selection keys
  4486. next to tags."
  4487. (mapconcat (lambda (token)
  4488. (pcase token
  4489. (`(:startgroup) "{")
  4490. (`(:endgroup) "}")
  4491. (`(:startgrouptag) "[")
  4492. (`(:endgrouptag) "]")
  4493. (`(:grouptags) ":")
  4494. (`(:newline) "\\n")
  4495. ((and
  4496. (guard (not skip-key))
  4497. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4498. (format "%s(%c)" tag key))
  4499. (`(,(and tag (pred stringp)) . ,_) tag)
  4500. (_ (user-error "Invalid tag token: %S" token))))
  4501. alist
  4502. " "))
  4503. (defun org-tag-alist-to-groups (alist)
  4504. "Return group alist from tag ALIST.
  4505. ALIST is an alist, as defined in `org-tag-alist' or
  4506. `org-tag-persistent-alist', or produced with
  4507. `org-tag-string-to-alist'. Return value is an alist following
  4508. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4509. a string, summarizing TAGS, as a list of strings."
  4510. (let (groups group-status current-group)
  4511. (dolist (token alist (nreverse groups))
  4512. (pcase token
  4513. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4514. (`(,(or :endgroup :endgrouptag))
  4515. (when (eq group-status 'append)
  4516. (push (nreverse current-group) groups))
  4517. (setq group-status nil))
  4518. (`(:grouptags) (setq group-status 'append))
  4519. ((and `(,tag . ,_) (guard group-status))
  4520. (if (eq group-status 'append) (push tag current-group)
  4521. (setq current-group (list tag))))
  4522. (_ nil)))))
  4523. (defvar org--file-cache (make-hash-table :test #'equal)
  4524. "Hash table to store contents of files referenced via a URL.
  4525. This is the cache of file URLs read using `org-file-contents'.")
  4526. (defun org-reset-file-cache ()
  4527. "Reset the cache of files downloaded by `org-file-contents'."
  4528. (clrhash org--file-cache))
  4529. (defun org-file-url-p (file)
  4530. "Non-nil if FILE is a URL."
  4531. (require 'ffap)
  4532. (string-match-p ffap-url-regexp file))
  4533. (defun org-file-contents (file &optional noerror nocache)
  4534. "Return the contents of FILE, as a string.
  4535. FILE can be a file name or URL.
  4536. If FILE is a URL, download the contents. If the URL contents are
  4537. already cached in the `org--file-cache' hash table, the download step
  4538. is skipped.
  4539. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4540. from file or URL.
  4541. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4542. is available. This option applies only if FILE is a URL."
  4543. (let* ((is-url (org-file-url-p file))
  4544. (cache (and is-url
  4545. (not nocache)
  4546. (gethash file org--file-cache))))
  4547. (cond
  4548. (cache)
  4549. (is-url
  4550. (with-current-buffer (url-retrieve-synchronously file)
  4551. (goto-char (point-min))
  4552. ;; Move point to after the url-retrieve header.
  4553. (search-forward "\n\n" nil :move)
  4554. ;; Search for the success code only in the url-retrieve header.
  4555. (if (save-excursion
  4556. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4557. ;; Update the cache `org--file-cache' and return contents.
  4558. (puthash file
  4559. (buffer-substring-no-properties (point) (point-max))
  4560. org--file-cache)
  4561. (funcall (if noerror #'message #'user-error)
  4562. "Unable to fetch file from %S"
  4563. file))))
  4564. (t
  4565. (with-temp-buffer
  4566. (condition-case nil
  4567. (progn
  4568. (insert-file-contents file)
  4569. (buffer-string))
  4570. (file-error
  4571. (funcall (if noerror #'message #'user-error)
  4572. "Unable to read file %S"
  4573. file))))))))
  4574. (defun org-extract-log-state-settings (x)
  4575. "Extract the log state setting from a TODO keyword string.
  4576. This will extract info from a string like \"WAIT(w@/!)\"."
  4577. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4578. (let ((kw (match-string 1 x))
  4579. (log1 (and (match-end 3) (match-string 3 x)))
  4580. (log2 (and (match-end 4) (match-string 4 x))))
  4581. (and (or log1 log2)
  4582. (list kw
  4583. (and log1 (if (equal log1 "!") 'time 'note))
  4584. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4585. (defun org-remove-keyword-keys (list)
  4586. "Remove a pair of parenthesis at the end of each string in LIST."
  4587. (mapcar (lambda (x)
  4588. (if (string-match "(.*)$" x)
  4589. (substring x 0 (match-beginning 0))
  4590. x))
  4591. list))
  4592. (defun org-assign-fast-keys (alist)
  4593. "Assign fast keys to a keyword-key alist.
  4594. Respect keys that are already there."
  4595. (let (new e (alt ?0))
  4596. (while (setq e (pop alist))
  4597. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4598. (cdr e)) ;; Key already assigned.
  4599. (push e new)
  4600. (let ((clist (string-to-list (downcase (car e))))
  4601. (used (append new alist)))
  4602. (when (= (car clist) ?@)
  4603. (pop clist))
  4604. (while (and clist (rassoc (car clist) used))
  4605. (pop clist))
  4606. (unless clist
  4607. (while (rassoc alt used)
  4608. (cl-incf alt)))
  4609. (push (cons (car e) (or (car clist) alt)) new))))
  4610. (nreverse new)))
  4611. ;;; Some variables used in various places
  4612. (defvar org-window-configuration nil
  4613. "Used in various places to store a window configuration.")
  4614. (defvar org-selected-window nil
  4615. "Used in various places to store a window configuration.")
  4616. (defvar org-finish-function nil
  4617. "Function to be called when `C-c C-c' is used.
  4618. This is for getting out of special buffers like capture.")
  4619. (defvar org-last-state)
  4620. ;; Defined somewhere in this file, but used before definition.
  4621. (defvar org-entities) ;; defined in org-entities.el
  4622. (defvar org-struct-menu)
  4623. (defvar org-org-menu)
  4624. (defvar org-tbl-menu)
  4625. ;;;; Define the Org mode
  4626. ;; We use a before-change function to check if a table might need
  4627. ;; an update.
  4628. (defvar org-table-may-need-update t
  4629. "Indicates that a table might need an update.
  4630. This variable is set by `org-before-change-function'.
  4631. `org-table-align' sets it back to nil.")
  4632. (defun org-before-change-function (_beg _end)
  4633. "Every change indicates that a table might need an update."
  4634. (setq org-table-may-need-update t))
  4635. (defvar org-mode-map)
  4636. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4637. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4638. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4639. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4640. (defvar org-table-buffer-is-an nil)
  4641. (defvar bidi-paragraph-direction)
  4642. (defvar buffer-face-mode-face)
  4643. (require 'outline)
  4644. ;; Other stuff we need.
  4645. (require 'time-date)
  4646. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4647. (require 'easymenu)
  4648. (autoload 'easy-menu-add "easymenu")
  4649. (require 'overlay)
  4650. ;; (require 'org-macs) moved higher up in the file before it is first used
  4651. (require 'org-entities)
  4652. ;; (require 'org-compat) moved higher up in the file before it is first used
  4653. (require 'org-faces)
  4654. (require 'org-list)
  4655. (require 'org-pcomplete)
  4656. (require 'org-src)
  4657. (require 'org-footnote)
  4658. (require 'org-macro)
  4659. ;; babel
  4660. (require 'ob)
  4661. ;;;###autoload
  4662. (define-derived-mode org-mode outline-mode "Org"
  4663. "Outline-based notes management and organizer, alias
  4664. \"Carsten's outline-mode for keeping track of everything.\"
  4665. Org mode develops organizational tasks around a NOTES file which
  4666. contains information about projects as plain text. Org mode is
  4667. implemented on top of Outline mode, which is ideal to keep the content
  4668. of large files well structured. It supports ToDo items, deadlines and
  4669. time stamps, which magically appear in the diary listing of the Emacs
  4670. calendar. Tables are easily created with a built-in table editor.
  4671. Plain text URL-like links connect to websites, emails (VM), Usenet
  4672. messages (Gnus), BBDB entries, and any files related to the project.
  4673. For printing and sharing of notes, an Org file (or a part of it)
  4674. can be exported as a structured ASCII or HTML file.
  4675. The following commands are available:
  4676. \\{org-mode-map}"
  4677. ;; Get rid of Outline menus, they are not needed
  4678. ;; Need to do this here because define-derived-mode sets up
  4679. ;; the keymap so late. Still, it is a waste to call this each time
  4680. ;; we switch another buffer into Org mode.
  4681. (define-key org-mode-map [menu-bar headings] 'undefined)
  4682. (define-key org-mode-map [menu-bar hide] 'undefined)
  4683. (define-key org-mode-map [menu-bar show] 'undefined)
  4684. (org-load-modules-maybe)
  4685. (org-install-agenda-files-menu)
  4686. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4687. (add-to-invisibility-spec '(org-hide-block . t))
  4688. (setq-local outline-regexp org-outline-regexp)
  4689. (setq-local outline-level 'org-outline-level)
  4690. (setq bidi-paragraph-direction 'left-to-right)
  4691. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4692. (unless org-display-table
  4693. (setq org-display-table (make-display-table)))
  4694. (set-display-table-slot
  4695. org-display-table 4
  4696. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4697. org-ellipsis)))
  4698. (setq buffer-display-table org-display-table))
  4699. (org-set-regexps-and-options)
  4700. (org-set-font-lock-defaults)
  4701. (when (and org-tag-faces (not org-tags-special-faces-re))
  4702. ;; tag faces set outside customize.... force initialization.
  4703. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4704. ;; Calc embedded
  4705. (setq-local calc-embedded-open-mode "# ")
  4706. ;; Modify a few syntax entries
  4707. (modify-syntax-entry ?@ "w")
  4708. (modify-syntax-entry ?\" "\"")
  4709. (modify-syntax-entry ?\\ "_")
  4710. (modify-syntax-entry ?~ "_")
  4711. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4712. ;; Activate before-change-function
  4713. (setq-local org-table-may-need-update t)
  4714. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4715. ;; Check for running clock before killing a buffer
  4716. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4717. ;; Initialize macros templates.
  4718. (org-macro-initialize-templates)
  4719. ;; Initialize radio targets.
  4720. (org-update-radio-target-regexp)
  4721. ;; Indentation.
  4722. (setq-local indent-line-function 'org-indent-line)
  4723. (setq-local indent-region-function 'org-indent-region)
  4724. ;; Filling and auto-filling.
  4725. (org-setup-filling)
  4726. ;; Comments.
  4727. (org-setup-comments-handling)
  4728. ;; Initialize cache.
  4729. (org-element-cache-reset)
  4730. ;; Beginning/end of defun
  4731. (setq-local beginning-of-defun-function 'org-backward-element)
  4732. (setq-local end-of-defun-function
  4733. (lambda ()
  4734. (if (not (org-at-heading-p))
  4735. (org-forward-element)
  4736. (org-forward-element)
  4737. (forward-char -1))))
  4738. ;; Next error for sparse trees
  4739. (setq-local next-error-function 'org-occur-next-match)
  4740. ;; Make sure dependence stuff works reliably, even for users who set it
  4741. ;; too late :-(
  4742. (if org-enforce-todo-dependencies
  4743. (add-hook 'org-blocker-hook
  4744. 'org-block-todo-from-children-or-siblings-or-parent)
  4745. (remove-hook 'org-blocker-hook
  4746. 'org-block-todo-from-children-or-siblings-or-parent))
  4747. (if org-enforce-todo-checkbox-dependencies
  4748. (add-hook 'org-blocker-hook
  4749. 'org-block-todo-from-checkboxes)
  4750. (remove-hook 'org-blocker-hook
  4751. 'org-block-todo-from-checkboxes))
  4752. ;; Align options lines
  4753. (setq-local
  4754. align-mode-rules-list
  4755. '((org-in-buffer-settings
  4756. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4757. (modes . '(org-mode)))))
  4758. ;; Imenu
  4759. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4760. ;; Make isearch reveal context
  4761. (setq-local outline-isearch-open-invisible-function
  4762. (lambda (&rest _) (org-show-context 'isearch)))
  4763. ;; Setup the pcomplete hooks
  4764. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4765. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4766. (setq-local pcomplete-default-completion-function 'ignore)
  4767. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4768. (setq-local pcomplete-termination-string "")
  4769. (setq-local buffer-face-mode-face 'org-default)
  4770. ;; If empty file that did not turn on Org mode automatically, make
  4771. ;; it to.
  4772. (when (and org-insert-mode-line-in-empty-file
  4773. (called-interactively-p 'any)
  4774. (= (point-min) (point-max)))
  4775. (insert "# -*- mode: org -*-\n\n"))
  4776. (unless org-inhibit-startup
  4777. (org-unmodified
  4778. (when org-startup-with-beamer-mode (org-beamer-mode))
  4779. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4780. (org-table-map-tables
  4781. (cond ((and org-startup-align-all-tables
  4782. org-startup-shrink-all-tables)
  4783. (lambda () (org-table-align) (org-table-shrink)))
  4784. (org-startup-align-all-tables #'org-table-align)
  4785. (t #'org-table-shrink))
  4786. t))
  4787. (when org-startup-with-inline-images (org-display-inline-images))
  4788. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4789. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4790. (when org-startup-truncated (setq truncate-lines t))
  4791. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4792. (org-refresh-effort-properties)))
  4793. ;; Try to set `org-hide' face correctly.
  4794. (let ((foreground (org-find-invisible-foreground)))
  4795. (when foreground
  4796. (set-face-foreground 'org-hide foreground))))
  4797. ;; Update `customize-package-emacs-version-alist'
  4798. (add-to-list 'customize-package-emacs-version-alist
  4799. '(Org ("8.0" . "24.4")
  4800. ("8.1" . "24.4")
  4801. ("8.2" . "24.4")
  4802. ("8.2.7" . "24.4")
  4803. ("8.3" . "26.1")
  4804. ("9.0" . "26.1")
  4805. ("9.1" . "26.1")
  4806. ("9.2" . "27.1")))
  4807. (defvar org-mode-transpose-word-syntax-table
  4808. (let ((st (make-syntax-table text-mode-syntax-table)))
  4809. (dolist (c org-emphasis-alist st)
  4810. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4811. (when (fboundp 'abbrev-table-put)
  4812. (abbrev-table-put org-mode-abbrev-table
  4813. :parents (list text-mode-abbrev-table)))
  4814. (defun org-find-invisible-foreground ()
  4815. (let ((candidates (remove
  4816. "unspecified-bg"
  4817. (nconc
  4818. (list (face-background 'default)
  4819. (face-background 'org-default))
  4820. (mapcar
  4821. (lambda (alist)
  4822. (when (boundp alist)
  4823. (cdr (assq 'background-color (symbol-value alist)))))
  4824. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4825. (list (face-foreground 'org-hide))))))
  4826. (car (remove nil candidates))))
  4827. (defun org-current-time (&optional rounding-minutes past)
  4828. "Current time, possibly rounded to ROUNDING-MINUTES.
  4829. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4830. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4831. the rounding returns a past time."
  4832. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4833. (car org-time-stamp-rounding-minutes)))
  4834. (time (decode-time)) res)
  4835. (if (< r 1)
  4836. (current-time)
  4837. (setq res
  4838. (apply 'encode-time
  4839. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4840. (nthcdr 2 time))))
  4841. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4842. (seconds-to-time (- (float-time res) (* r 60)))
  4843. res))))
  4844. (defun org-today ()
  4845. "Return today date, considering `org-extend-today-until'."
  4846. (time-to-days
  4847. (time-subtract (current-time)
  4848. (list 0 (* 3600 org-extend-today-until) 0))))
  4849. ;;;; Font-Lock stuff, including the activators
  4850. (defvar org-mouse-map (make-sparse-keymap))
  4851. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4852. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4853. (when org-mouse-1-follows-link
  4854. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4855. (when org-tab-follows-link
  4856. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4857. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4858. (require 'font-lock)
  4859. (defconst org-non-link-chars "]\t\n\r<>")
  4860. (defvar org-link-types-re nil
  4861. "Matches a link that has a url-like prefix like \"http:\"")
  4862. (defvar org-link-re-with-space nil
  4863. "Matches a link with spaces, optional angular brackets around it.")
  4864. (defvar org-link-re-with-space2 nil
  4865. "Matches a link with spaces, optional angular brackets around it.")
  4866. (defvar org-link-re-with-space3 nil
  4867. "Matches a link with spaces, only for internal part in bracket links.")
  4868. (defvar org-angle-link-re nil
  4869. "Matches link with angular brackets, spaces are allowed.")
  4870. (defvar org-plain-link-re nil
  4871. "Matches plain link, without spaces.")
  4872. (defvar org-bracket-link-regexp nil
  4873. "Matches a link in double brackets.")
  4874. (defvar org-bracket-link-analytic-regexp nil
  4875. "Regular expression used to analyze links.
  4876. Here is what the match groups contain after a match:
  4877. 1: http:
  4878. 2: http
  4879. 3: path
  4880. 4: [desc]
  4881. 5: desc")
  4882. (defvar org-bracket-link-analytic-regexp++ nil
  4883. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4884. (defvar org-any-link-re nil
  4885. "Regular expression matching any link.")
  4886. (defconst org-match-sexp-depth 3
  4887. "Number of stacked braces for sub/superscript matching.")
  4888. (defun org-create-multibrace-regexp (left right n)
  4889. "Create a regular expression which will match a balanced sexp.
  4890. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4891. as single character strings.
  4892. The regexp returned will match the entire expression including the
  4893. delimiters. It will also define a single group which contains the
  4894. match except for the outermost delimiters. The maximum depth of
  4895. stacked delimiters is N. Escaping delimiters is not possible."
  4896. (let* ((nothing (concat "[^" left right "]*?"))
  4897. (or "\\|")
  4898. (re nothing)
  4899. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4900. (while (> n 1)
  4901. (setq n (1- n)
  4902. re (concat re or next)
  4903. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4904. (concat left "\\(" re "\\)" right)))
  4905. (defconst org-match-substring-regexp
  4906. (concat
  4907. "\\(\\S-\\)\\([_^]\\)\\("
  4908. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4909. "\\|"
  4910. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4911. "\\|"
  4912. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4913. "The regular expression matching a sub- or superscript.")
  4914. (defconst org-match-substring-with-braces-regexp
  4915. (concat
  4916. "\\(\\S-\\)\\([_^]\\)"
  4917. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4918. "The regular expression matching a sub- or superscript, forcing braces.")
  4919. (defun org-make-link-regexps ()
  4920. "Update the link regular expressions.
  4921. This should be called after the variable `org-link-parameters' has changed."
  4922. (let ((types-re (regexp-opt (org-link-types) t)))
  4923. (setq org-link-types-re
  4924. (concat "\\`" types-re ":")
  4925. org-link-re-with-space
  4926. (concat "<?" types-re ":"
  4927. "\\([^" org-non-link-chars " ]"
  4928. "[^" org-non-link-chars "]*"
  4929. "[^" org-non-link-chars " ]\\)>?")
  4930. org-link-re-with-space2
  4931. (concat "<?" types-re ":"
  4932. "\\([^" org-non-link-chars " ]"
  4933. "[^\t\n\r]*"
  4934. "[^" org-non-link-chars " ]\\)>?")
  4935. org-link-re-with-space3
  4936. (concat "<?" types-re ":"
  4937. "\\([^" org-non-link-chars " ]"
  4938. "[^\t\n\r]*\\)")
  4939. org-angle-link-re
  4940. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4941. types-re)
  4942. org-plain-link-re
  4943. (concat
  4944. "\\<" types-re ":"
  4945. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4946. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4947. org-bracket-link-regexp
  4948. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4949. org-bracket-link-analytic-regexp
  4950. (concat
  4951. "\\[\\["
  4952. "\\(" types-re ":\\)?"
  4953. "\\([^]]+\\)"
  4954. "\\]"
  4955. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4956. "\\]")
  4957. org-bracket-link-analytic-regexp++
  4958. (concat
  4959. "\\[\\["
  4960. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4961. "\\([^]]+\\)"
  4962. "\\]"
  4963. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4964. "\\]")
  4965. org-any-link-re
  4966. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4967. org-angle-link-re "\\)\\|\\("
  4968. org-plain-link-re "\\)"))))
  4969. (org-make-link-regexps)
  4970. (defvar org-emph-face nil)
  4971. (defun org-do-emphasis-faces (limit)
  4972. "Run through the buffer and emphasize strings."
  4973. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4974. (car org-emphasis-regexp-components))))
  4975. (catch :exit
  4976. (while (re-search-forward quick-re limit t)
  4977. (let* ((marker (match-string 2))
  4978. (verbatim? (member marker '("~" "="))))
  4979. (when (save-excursion
  4980. (goto-char (match-beginning 0))
  4981. (and
  4982. ;; Do not match table hlines.
  4983. (not (and (equal marker "+")
  4984. (org-match-line
  4985. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4986. ;; Match full emphasis markup regexp.
  4987. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4988. ;; Do not span over paragraph boundaries.
  4989. (not (string-match-p org-element-paragraph-separate
  4990. (match-string 0)))
  4991. ;; Do not span over cells in table rows.
  4992. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4993. (string-match-p "|" (match-string 4))))))
  4994. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4995. (font-lock-prepend-text-property
  4996. (match-beginning 2) (match-end 2) 'face face)
  4997. (when verbatim?
  4998. (org-remove-flyspell-overlays-in
  4999. (match-beginning 0) (match-end 0)))
  5000. (add-text-properties (match-beginning 2) (match-end 2)
  5001. '(font-lock-multiline t org-emphasis t))
  5002. (when org-hide-emphasis-markers
  5003. (add-text-properties (match-end 4) (match-beginning 5)
  5004. '(invisible org-link))
  5005. (add-text-properties (match-beginning 3) (match-end 3)
  5006. '(invisible org-link)))
  5007. (throw :exit t))))))))
  5008. (defun org-emphasize (&optional char)
  5009. "Insert or change an emphasis, i.e. a font like bold or italic.
  5010. If there is an active region, change that region to a new emphasis.
  5011. If there is no region, just insert the marker characters and position
  5012. the cursor between them.
  5013. CHAR should be the marker character. If it is a space, it means to
  5014. remove the emphasis of the selected region.
  5015. If CHAR is not given (for example in an interactive call) it will be
  5016. prompted for."
  5017. (interactive)
  5018. (let ((erc org-emphasis-regexp-components)
  5019. (string "") beg end move s)
  5020. (if (org-region-active-p)
  5021. (setq beg (region-beginning)
  5022. end (region-end)
  5023. string (buffer-substring beg end))
  5024. (setq move t))
  5025. (unless char
  5026. (message "Emphasis marker or tag: [%s]"
  5027. (mapconcat #'car org-emphasis-alist ""))
  5028. (setq char (read-char-exclusive)))
  5029. (if (equal char ?\s)
  5030. (setq s ""
  5031. move nil)
  5032. (unless (assoc (char-to-string char) org-emphasis-alist)
  5033. (user-error "No such emphasis marker: \"%c\"" char))
  5034. (setq s (char-to-string char)))
  5035. (while (and (> (length string) 1)
  5036. (equal (substring string 0 1) (substring string -1))
  5037. (assoc (substring string 0 1) org-emphasis-alist))
  5038. (setq string (substring string 1 -1)))
  5039. (setq string (concat s string s))
  5040. (when beg (delete-region beg end))
  5041. (unless (or (bolp)
  5042. (string-match (concat "[" (nth 0 erc) "\n]")
  5043. (char-to-string (char-before (point)))))
  5044. (insert " "))
  5045. (unless (or (eobp)
  5046. (string-match (concat "[" (nth 1 erc) "\n]")
  5047. (char-to-string (char-after (point)))))
  5048. (insert " ") (backward-char 1))
  5049. (insert string)
  5050. (and move (backward-char 1))))
  5051. (defconst org-nonsticky-props
  5052. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5053. (defsubst org-rear-nonsticky-at (pos)
  5054. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5055. (defun org-activate-links (limit)
  5056. "Add link properties to links.
  5057. This includes angle, plain, and bracket links."
  5058. (catch :exit
  5059. (while (re-search-forward org-any-link-re limit t)
  5060. (let* ((start (match-beginning 0))
  5061. (end (match-end 0))
  5062. (style (cond ((eq ?< (char-after start)) 'angle)
  5063. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5064. (t 'plain))))
  5065. (when (and (memq style org-highlight-links)
  5066. ;; Do not confuse plain links with tags.
  5067. (not (and (eq style 'plain)
  5068. (let ((face (get-text-property
  5069. (max (1- start) (point-min)) 'face)))
  5070. (if (consp face) (memq 'org-tag face)
  5071. (eq 'org-tag face))))))
  5072. (let* ((link-object (save-excursion
  5073. (goto-char start)
  5074. (save-match-data (org-element-link-parser))))
  5075. (link (org-element-property :raw-link link-object))
  5076. (type (org-element-property :type link-object))
  5077. (path (org-element-property :path link-object))
  5078. (properties ;for link's visible part
  5079. (list
  5080. 'face (pcase (org-link-get-parameter type :face)
  5081. ((and (pred functionp) face) (funcall face path))
  5082. ((and (pred facep) face) face)
  5083. ((and (pred consp) face) face) ;anonymous
  5084. (_ 'org-link))
  5085. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5086. 'highlight)
  5087. 'keymap (or (org-link-get-parameter type :keymap)
  5088. org-mouse-map)
  5089. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5090. ((and (pred stringp) echo) echo)
  5091. ((and (pred functionp) echo) echo)
  5092. (_ (concat "LINK: " link)))
  5093. 'htmlize-link (pcase (org-link-get-parameter type
  5094. :htmlize-link)
  5095. ((and (pred functionp) f) (funcall f))
  5096. (_ `(:uri ,link)))
  5097. 'font-lock-multiline t)))
  5098. (org-remove-flyspell-overlays-in start end)
  5099. (org-rear-nonsticky-at end)
  5100. (if (not (eq 'bracket style))
  5101. (add-text-properties start end properties)
  5102. ;; Handle invisible parts in bracket links.
  5103. (remove-text-properties start end '(invisible nil))
  5104. (let ((hidden
  5105. (append `(invisible
  5106. ,(or (org-link-get-parameter type :display)
  5107. 'org-link))
  5108. properties))
  5109. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5110. (visible-end (or (match-end 4) (match-end 2))))
  5111. (add-text-properties start visible-start hidden)
  5112. (add-text-properties visible-start visible-end properties)
  5113. (add-text-properties visible-end end hidden)
  5114. (org-rear-nonsticky-at visible-start)
  5115. (org-rear-nonsticky-at visible-end)))
  5116. (let ((f (org-link-get-parameter type :activate-func)))
  5117. (when (functionp f)
  5118. (funcall f start end path (eq style 'bracket))))
  5119. (throw :exit t))))) ;signal success
  5120. nil))
  5121. (defun org-activate-code (limit)
  5122. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5123. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5124. (remove-text-properties (match-beginning 0) (match-end 0)
  5125. '(display t invisible t intangible t))
  5126. t))
  5127. (defcustom org-src-fontify-natively t
  5128. "When non-nil, fontify code in code blocks.
  5129. See also the `org-block' face."
  5130. :type 'boolean
  5131. :version "26.1"
  5132. :package-version '(Org . "8.3")
  5133. :group 'org-appearance
  5134. :group 'org-babel)
  5135. (defcustom org-allow-promoting-top-level-subtree nil
  5136. "When non-nil, allow promoting a top level subtree.
  5137. The leading star of the top level headline will be replaced
  5138. by a #."
  5139. :type 'boolean
  5140. :version "24.1"
  5141. :group 'org-appearance)
  5142. (defun org-fontify-meta-lines-and-blocks (limit)
  5143. (condition-case nil
  5144. (org-fontify-meta-lines-and-blocks-1 limit)
  5145. (error (message "org-mode fontification error in %S at %d"
  5146. (current-buffer)
  5147. (line-number-at-pos)))))
  5148. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5149. "Fontify #+ lines and blocks."
  5150. (let ((case-fold-search t))
  5151. (when (re-search-forward
  5152. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5153. limit t)
  5154. (let ((beg (match-beginning 0))
  5155. (block-start (match-end 0))
  5156. (block-end nil)
  5157. (lang (match-string 7))
  5158. (beg1 (line-beginning-position 2))
  5159. (dc1 (downcase (match-string 2)))
  5160. (dc3 (downcase (match-string 3)))
  5161. end end1 quoting block-type)
  5162. (cond
  5163. ((and (match-end 4) (equal dc3 "+begin"))
  5164. ;; Truly a block
  5165. (setq block-type (downcase (match-string 5))
  5166. quoting (member block-type org-protecting-blocks))
  5167. (when (re-search-forward
  5168. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5169. nil t) ;; on purpose, we look further than LIMIT
  5170. (setq end (min (point-max) (match-end 0))
  5171. end1 (min (point-max) (1- (match-beginning 0))))
  5172. (setq block-end (match-beginning 0))
  5173. (when quoting
  5174. (org-remove-flyspell-overlays-in beg1 end1)
  5175. (remove-text-properties beg end
  5176. '(display t invisible t intangible t)))
  5177. (add-text-properties
  5178. beg end '(font-lock-fontified t font-lock-multiline t))
  5179. (add-text-properties beg beg1 '(face org-meta-line))
  5180. (org-remove-flyspell-overlays-in beg beg1)
  5181. (add-text-properties ; For end_src
  5182. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5183. (org-remove-flyspell-overlays-in end1 end)
  5184. (cond
  5185. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5186. (org-src-font-lock-fontify-block lang block-start block-end)
  5187. (add-text-properties beg1 block-end '(src-block t)))
  5188. (quoting
  5189. (add-text-properties beg1 (min (point-max) (1+ end1))
  5190. (list 'face
  5191. (list :inherit
  5192. (let ((face-name
  5193. (intern (format "org-block-%s" lang))))
  5194. (append (and (facep face-name) (list face-name))
  5195. '(org-block))))))) ; end of source block
  5196. ((not org-fontify-quote-and-verse-blocks))
  5197. ((string= block-type "quote")
  5198. (add-face-text-property
  5199. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5200. ((string= block-type "verse")
  5201. (add-face-text-property
  5202. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5203. (add-text-properties beg beg1 '(face org-block-begin-line))
  5204. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5205. '(face org-block-end-line))
  5206. t))
  5207. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5208. (org-remove-flyspell-overlays-in
  5209. (match-beginning 0)
  5210. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5211. (add-text-properties
  5212. beg (match-end 3)
  5213. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5214. '(font-lock-fontified t invisible t)
  5215. '(font-lock-fontified t face org-document-info-keyword)))
  5216. (add-text-properties
  5217. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5218. (if (string-equal dc1 "+title:")
  5219. '(font-lock-fontified t face org-document-title)
  5220. '(font-lock-fontified t face org-document-info))))
  5221. ((string-prefix-p "+caption" dc1)
  5222. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5223. (remove-text-properties (match-beginning 0) (match-end 0)
  5224. '(display t invisible t intangible t))
  5225. ;; Handle short captions.
  5226. (save-excursion
  5227. (beginning-of-line)
  5228. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5229. (add-text-properties (line-beginning-position) (match-end 1)
  5230. '(font-lock-fontified t face org-meta-line))
  5231. (add-text-properties (match-end 0) (line-end-position)
  5232. '(font-lock-fontified t face org-block))
  5233. t)
  5234. ((member dc3 '(" " ""))
  5235. (org-remove-flyspell-overlays-in beg (match-end 0))
  5236. (add-text-properties
  5237. beg (match-end 0)
  5238. '(font-lock-fontified t face font-lock-comment-face)))
  5239. (t ;; just any other in-buffer setting, but not indented
  5240. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5241. (remove-text-properties (match-beginning 0) (match-end 0)
  5242. '(display t invisible t intangible t))
  5243. (add-text-properties beg (match-end 0)
  5244. '(font-lock-fontified t face org-meta-line))
  5245. t))))))
  5246. (defun org-fontify-drawers (limit)
  5247. "Fontify drawers."
  5248. (when (re-search-forward org-drawer-regexp limit t)
  5249. (add-text-properties
  5250. (match-beginning 0) (match-end 0)
  5251. '(font-lock-fontified t face org-special-keyword))
  5252. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5253. t))
  5254. (defun org-fontify-macros (limit)
  5255. "Fontify macros."
  5256. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5257. (add-text-properties
  5258. (match-beginning 0) (match-end 0)
  5259. '(font-lock-fontified t face org-macro))
  5260. (when org-hide-macro-markers
  5261. (add-text-properties (match-end 2) (match-beginning 2)
  5262. '(invisible t))
  5263. (add-text-properties (match-beginning 1) (match-end 1)
  5264. '(invisible t)))
  5265. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5266. t))
  5267. (defun org-activate-footnote-links (limit)
  5268. "Add text properties for footnotes."
  5269. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5270. (when fn
  5271. (let* ((beg (nth 1 fn))
  5272. (end (nth 2 fn))
  5273. (label (car fn))
  5274. (referencep (/= (line-beginning-position) beg)))
  5275. (when (and referencep (nth 3 fn))
  5276. (save-excursion
  5277. (goto-char beg)
  5278. (search-forward (or label "fn:"))
  5279. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5280. (add-text-properties beg end
  5281. (list 'mouse-face 'highlight
  5282. 'keymap org-mouse-map
  5283. 'help-echo
  5284. (if referencep "Footnote reference"
  5285. "Footnote definition")
  5286. 'font-lock-fontified t
  5287. 'font-lock-multiline t
  5288. 'face 'org-footnote))))))
  5289. (defun org-activate-dates (limit)
  5290. "Add text properties for dates."
  5291. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5292. (not (equal (char-before (match-beginning 0)) 91)))
  5293. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5294. (add-text-properties (match-beginning 0) (match-end 0)
  5295. (list 'mouse-face 'highlight
  5296. 'keymap org-mouse-map))
  5297. (org-rear-nonsticky-at (match-end 0))
  5298. (when org-display-custom-times
  5299. ;; If it's a date range, activate custom time for second date.
  5300. (when (match-end 3)
  5301. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5302. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5303. t))
  5304. (defvar-local org-target-link-regexp nil
  5305. "Regular expression matching radio targets in plain text.")
  5306. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5307. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5308. border border border))
  5309. "Regular expression matching a link target.")
  5310. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5311. "Regular expression matching a radio target.")
  5312. (defconst org-any-target-regexp
  5313. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5314. "Regular expression matching any target.")
  5315. (defun org-activate-target-links (limit)
  5316. "Add text properties for target matches."
  5317. (when org-target-link-regexp
  5318. (let ((case-fold-search t))
  5319. (when (re-search-forward org-target-link-regexp limit t)
  5320. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5321. (add-text-properties (match-beginning 1) (match-end 1)
  5322. (list 'mouse-face 'highlight
  5323. 'keymap org-mouse-map
  5324. 'help-echo "Radio target link"
  5325. 'org-linked-text t))
  5326. (org-rear-nonsticky-at (match-end 1))
  5327. t))))
  5328. (defun org-update-radio-target-regexp ()
  5329. "Find all radio targets in this file and update the regular expression.
  5330. Also refresh fontification if needed."
  5331. (interactive)
  5332. (let ((old-regexp org-target-link-regexp)
  5333. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5334. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5335. (targets
  5336. (org-with-wide-buffer
  5337. (goto-char (point-min))
  5338. (let (rtn)
  5339. (while (re-search-forward org-radio-target-regexp nil t)
  5340. ;; Make sure point is really within the object.
  5341. (backward-char)
  5342. (let ((obj (org-element-context)))
  5343. (when (eq (org-element-type obj) 'radio-target)
  5344. (cl-pushnew (org-element-property :value obj) rtn
  5345. :test #'equal))))
  5346. rtn))))
  5347. (setq org-target-link-regexp
  5348. (and targets
  5349. (concat before-re
  5350. (mapconcat
  5351. (lambda (x)
  5352. (replace-regexp-in-string
  5353. " +" "\\s-+" (regexp-quote x) t t))
  5354. targets
  5355. "\\|")
  5356. after-re)))
  5357. (unless (equal old-regexp org-target-link-regexp)
  5358. ;; Clean-up cache.
  5359. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5360. ((not org-target-link-regexp) old-regexp)
  5361. (t
  5362. (concat before-re
  5363. (mapconcat
  5364. (lambda (re)
  5365. (substring re (length before-re)
  5366. (- (length after-re))))
  5367. (list old-regexp org-target-link-regexp)
  5368. "\\|")
  5369. after-re)))))
  5370. (org-with-wide-buffer
  5371. (goto-char (point-min))
  5372. (while (re-search-forward regexp nil t)
  5373. (org-element-cache-refresh (match-beginning 1)))))
  5374. ;; Re fontify buffer.
  5375. (when (memq 'radio org-highlight-links)
  5376. (org-restart-font-lock)))))
  5377. (defvar org-latex-and-related-regexp nil
  5378. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5379. (defun org-compute-latex-and-related-regexp ()
  5380. "Compute regular expression for LaTeX, entities and sub/superscript.
  5381. Result depends on variable `org-highlight-latex-and-related'."
  5382. (setq-local
  5383. org-latex-and-related-regexp
  5384. (let* ((re-sub
  5385. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5386. ((eq org-use-sub-superscripts '{})
  5387. (list org-match-substring-with-braces-regexp))
  5388. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5389. (re-latex
  5390. (when (memq 'latex org-highlight-latex-and-related)
  5391. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5392. (delq nil
  5393. (mapcar (lambda (x)
  5394. (and (member (car x) matchers) (nth 1 x)))
  5395. org-latex-regexps)))))
  5396. (re-entities
  5397. (when (memq 'entities org-highlight-latex-and-related)
  5398. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5399. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5400. (defun org-do-latex-and-related (limit)
  5401. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5402. LIMIT bounds the search for syntax to highlight. Stop at first
  5403. highlighted object, if any. Return t if some highlighting was
  5404. done, nil otherwise."
  5405. (when (org-string-nw-p org-latex-and-related-regexp)
  5406. (catch 'found
  5407. (while (re-search-forward org-latex-and-related-regexp limit t)
  5408. (unless
  5409. (cl-some
  5410. (lambda (f)
  5411. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5412. (save-excursion
  5413. (goto-char (1+ (match-beginning 0)))
  5414. (face-at-point nil t)))
  5415. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5416. '(?_ ?^))
  5417. 1
  5418. 0)))
  5419. (font-lock-prepend-text-property
  5420. (+ offset (match-beginning 0)) (match-end 0)
  5421. 'face 'org-latex-and-related)
  5422. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5423. '(font-lock-multiline t)))
  5424. (throw 'found t)))
  5425. nil)))
  5426. (defun org-restart-font-lock ()
  5427. "Restart `font-lock-mode', to force refontification."
  5428. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5429. (font-lock-mode -1)
  5430. (font-lock-mode 1)))
  5431. (defun org-activate-tags (limit)
  5432. (when (re-search-forward
  5433. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5434. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5435. (add-text-properties (match-beginning 1) (match-end 1)
  5436. (list 'mouse-face 'highlight
  5437. 'keymap org-mouse-map))
  5438. (org-rear-nonsticky-at (match-end 1))
  5439. t))
  5440. (defun org-outline-level ()
  5441. "Compute the outline level of the heading at point.
  5442. If this is called at a normal headline, the level is the number
  5443. of stars. Use `org-reduced-level' to remove the effect of
  5444. `org-odd-levels'. Unlike to `org-current-level', this function
  5445. takes into consideration inlinetasks."
  5446. (org-with-wide-buffer
  5447. (end-of-line)
  5448. (if (re-search-backward org-outline-regexp-bol nil t)
  5449. (1- (- (match-end 0) (match-beginning 0)))
  5450. 0)))
  5451. (defvar org-font-lock-keywords nil)
  5452. (defsubst org-re-property (property &optional literal allow-null value)
  5453. "Return a regexp matching a PROPERTY line.
  5454. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5455. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5456. non-nil, match properties even without a value.
  5457. Match group 3 is set to the value when it exists. If there is no
  5458. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5459. With optional argument VALUE, match only property lines with
  5460. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5461. unless LITERAL is non-nil."
  5462. (concat
  5463. "^\\(?4:[ \t]*\\)"
  5464. (format "\\(?1::\\(?2:%s\\):\\)"
  5465. (if literal property (regexp-quote property)))
  5466. (cond (value
  5467. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5468. (if literal value (regexp-quote value))))
  5469. (allow-null
  5470. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5471. (t
  5472. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5473. (defconst org-property-re
  5474. (org-re-property "\\S-+" 'literal t)
  5475. "Regular expression matching a property line.
  5476. There are four matching groups:
  5477. 1: :PROPKEY: including the leading and trailing colon,
  5478. 2: PROPKEY without the leading and trailing colon,
  5479. 3: PROPVAL without leading or trailing spaces,
  5480. 4: the indentation of the current line,
  5481. 5: trailing whitespace.")
  5482. (defvar org-font-lock-hook nil
  5483. "Functions to be called for special font lock stuff.")
  5484. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5485. (defvar org-font-lock-set-keywords-hook nil
  5486. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5487. This is called after `org-font-lock-extra-keywords' is defined, but before
  5488. it is installed to be used by font lock. This can be useful if something
  5489. needs to be inserted at a specific position in the font-lock sequence.")
  5490. (defun org-font-lock-hook (limit)
  5491. "Run `org-font-lock-hook' within LIMIT."
  5492. (run-hook-with-args 'org-font-lock-hook limit))
  5493. (defun org-set-font-lock-defaults ()
  5494. "Set font lock defaults for the current buffer."
  5495. (let* ((em org-fontify-emphasized-text)
  5496. (lk org-highlight-links)
  5497. (org-font-lock-extra-keywords
  5498. (list
  5499. ;; Call the hook
  5500. '(org-font-lock-hook)
  5501. ;; Headlines
  5502. `(,(if org-fontify-whole-heading-line
  5503. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5504. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5505. (1 (org-get-level-face 1))
  5506. (2 (org-get-level-face 2))
  5507. (3 (org-get-level-face 3)))
  5508. ;; Table lines
  5509. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5510. (1 'org-table t))
  5511. ;; Table internals
  5512. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5513. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5514. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5515. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5516. ;; Drawers
  5517. '(org-fontify-drawers)
  5518. ;; Properties
  5519. (list org-property-re
  5520. '(1 'org-special-keyword t)
  5521. '(3 'org-property-value t))
  5522. ;; Link related fontification.
  5523. '(org-activate-links)
  5524. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5525. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5526. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5527. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5528. ;; Targets.
  5529. (list org-any-target-regexp '(0 'org-target t))
  5530. ;; Diary sexps.
  5531. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5532. ;; Macro
  5533. '(org-fontify-macros)
  5534. ;; TODO keyword
  5535. (list (format org-heading-keyword-regexp-format
  5536. org-todo-regexp)
  5537. '(2 (org-get-todo-face 2) t))
  5538. ;; DONE
  5539. (if org-fontify-done-headline
  5540. (list (format org-heading-keyword-regexp-format
  5541. (concat
  5542. "\\(?:"
  5543. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5544. "\\)"))
  5545. '(2 'org-headline-done t))
  5546. nil)
  5547. ;; Priorities
  5548. '(org-font-lock-add-priority-faces)
  5549. ;; Tags
  5550. '(org-font-lock-add-tag-faces)
  5551. ;; Tags groups
  5552. (when (and org-group-tags org-tag-groups-alist)
  5553. (list (concat org-outline-regexp-bol ".+\\(:"
  5554. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5555. ":\\).*$")
  5556. '(1 'org-tag-group prepend)))
  5557. ;; Special keywords
  5558. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5559. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5560. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5561. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5562. ;; Emphasis
  5563. (when em '(org-do-emphasis-faces))
  5564. ;; Checkboxes
  5565. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5566. 1 'org-checkbox prepend)
  5567. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5568. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5569. (0 (org-get-checkbox-statistics-face) t)))
  5570. ;; Description list items
  5571. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5572. 1 'org-list-dt prepend)
  5573. ;; ARCHIVEd headings
  5574. (list (concat
  5575. org-outline-regexp-bol
  5576. "\\(.*:" org-archive-tag ":.*\\)")
  5577. '(1 'org-archived prepend))
  5578. ;; Specials
  5579. '(org-do-latex-and-related)
  5580. '(org-fontify-entities)
  5581. '(org-raise-scripts)
  5582. ;; Code
  5583. '(org-activate-code (1 'org-code t))
  5584. ;; COMMENT
  5585. (list (format
  5586. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5587. org-todo-regexp
  5588. org-comment-string)
  5589. '(9 'org-special-keyword t))
  5590. ;; Blocks and meta lines
  5591. '(org-fontify-meta-lines-and-blocks))))
  5592. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5593. (run-hooks 'org-font-lock-set-keywords-hook)
  5594. ;; Now set the full font-lock-keywords
  5595. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5596. (setq-local font-lock-defaults
  5597. '(org-font-lock-keywords t nil nil backward-paragraph))
  5598. (kill-local-variable 'font-lock-keywords)
  5599. nil))
  5600. (defun org-toggle-pretty-entities ()
  5601. "Toggle the composition display of entities as UTF8 characters."
  5602. (interactive)
  5603. (setq-local org-pretty-entities (not org-pretty-entities))
  5604. (org-restart-font-lock)
  5605. (if org-pretty-entities
  5606. (message "Entities are now displayed as UTF8 characters")
  5607. (save-restriction
  5608. (widen)
  5609. (decompose-region (point-min) (point-max))
  5610. (message "Entities are now displayed as plain text"))))
  5611. (defvar-local org-custom-properties-overlays nil
  5612. "List of overlays used for custom properties.")
  5613. (defun org-toggle-custom-properties-visibility ()
  5614. "Display or hide properties in `org-custom-properties'."
  5615. (interactive)
  5616. (if org-custom-properties-overlays
  5617. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5618. (setq org-custom-properties-overlays nil))
  5619. (when org-custom-properties
  5620. (org-with-wide-buffer
  5621. (goto-char (point-min))
  5622. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5623. (while (re-search-forward regexp nil t)
  5624. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5625. (when (and end (< (point) end))
  5626. ;; Hide first custom property in current drawer.
  5627. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5628. (overlay-put o 'invisible t)
  5629. (overlay-put o 'org-custom-property t)
  5630. (push o org-custom-properties-overlays))
  5631. ;; Hide additional custom properties in the same drawer.
  5632. (while (re-search-forward regexp end t)
  5633. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5634. (overlay-put o 'invisible t)
  5635. (overlay-put o 'org-custom-property t)
  5636. (push o org-custom-properties-overlays)))))
  5637. ;; Each entry is limited to a single property drawer.
  5638. (outline-next-heading)))))))
  5639. (defun org-fontify-entities (limit)
  5640. "Find an entity to fontify."
  5641. (let (ee)
  5642. (when org-pretty-entities
  5643. (catch 'match
  5644. ;; "\_ "-family is left out on purpose. Only the first one,
  5645. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5646. ;; confusing when adding a second white space character.
  5647. (while (re-search-forward
  5648. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5649. limit t)
  5650. (when (and (not (org-at-comment-p))
  5651. (setq ee (org-entity-get (match-string 1)))
  5652. (= (length (nth 6 ee)) 1))
  5653. (let* ((end (if (equal (match-string 2) "{}")
  5654. (match-end 2)
  5655. (match-end 1))))
  5656. (add-text-properties
  5657. (match-beginning 0) end
  5658. (list 'font-lock-fontified t))
  5659. (compose-region (match-beginning 0) end
  5660. (nth 6 ee) nil)
  5661. (backward-char 1)
  5662. (throw 'match t))))
  5663. nil))))
  5664. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5665. "Fontify string S like in Org mode."
  5666. (with-temp-buffer
  5667. (insert s)
  5668. (let ((org-odd-levels-only odd-levels))
  5669. (org-mode)
  5670. (org-font-lock-ensure)
  5671. (buffer-string))))
  5672. (defvar org-m nil)
  5673. (defvar org-l nil)
  5674. (defvar org-f nil)
  5675. (defun org-get-level-face (n)
  5676. "Get the right face for match N in font-lock matching of headlines."
  5677. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5678. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5679. (if org-cycle-level-faces
  5680. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5681. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5682. (cond
  5683. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5684. ((eq n 2) org-f)
  5685. (t (unless org-level-color-stars-only org-f))))
  5686. (defun org-face-from-face-or-color (context inherit face-or-color)
  5687. "Create a face list that inherits INHERIT, but sets the foreground color.
  5688. When FACE-OR-COLOR is not a string, just return it."
  5689. (if (stringp face-or-color)
  5690. (list :inherit inherit
  5691. (cdr (assoc context org-faces-easy-properties))
  5692. face-or-color)
  5693. face-or-color))
  5694. (defun org-get-todo-face (kwd)
  5695. "Get the right face for a TODO keyword KWD.
  5696. If KWD is a number, get the corresponding match group."
  5697. (when (numberp kwd) (setq kwd (match-string kwd)))
  5698. (or (org-face-from-face-or-color
  5699. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5700. (and (member kwd org-done-keywords) 'org-done)
  5701. 'org-todo))
  5702. (defun org-get-priority-face (priority)
  5703. "Get the right face for PRIORITY.
  5704. PRIORITY is a character."
  5705. (or (org-face-from-face-or-color
  5706. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5707. 'org-priority))
  5708. (defun org-get-tag-face (tag)
  5709. "Get the right face for TAG.
  5710. If TAG is a number, get the corresponding match group."
  5711. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5712. (or (org-face-from-face-or-color
  5713. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5714. 'org-tag)))
  5715. (defun org-font-lock-add-priority-faces (limit)
  5716. "Add the special priority faces."
  5717. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5718. (add-text-properties
  5719. (match-beginning 1) (match-end 1)
  5720. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5721. 'font-lock-fontified t))))
  5722. (defun org-font-lock-add-tag-faces (limit)
  5723. "Add the special tag faces."
  5724. (when (and org-tag-faces org-tags-special-faces-re)
  5725. (while (re-search-forward org-tags-special-faces-re limit t)
  5726. (add-text-properties (match-beginning 1) (match-end 1)
  5727. (list 'face (org-get-tag-face 1)
  5728. 'font-lock-fontified t))
  5729. (backward-char 1))))
  5730. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5731. "Remove fontification and activation overlays from links."
  5732. (font-lock-default-unfontify-region beg end)
  5733. (let* ((buffer-undo-list t)
  5734. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5735. (inhibit-modification-hooks t)
  5736. deactivate-mark buffer-file-name buffer-file-truename)
  5737. (decompose-region beg end)
  5738. (remove-text-properties beg end
  5739. '(mouse-face t keymap t org-linked-text t
  5740. invisible t intangible t
  5741. org-emphasis t))
  5742. (org-remove-font-lock-display-properties beg end)))
  5743. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5744. ((raise 0.3) (height 0.7))
  5745. ((raise -0.5))
  5746. ((raise 0.5)))
  5747. "Display properties for showing superscripts and subscripts.")
  5748. (defun org-remove-font-lock-display-properties (beg end)
  5749. "Remove specific display properties that have been added by font lock.
  5750. The will remove the raise properties that are used to show superscripts
  5751. and subscripts."
  5752. (let (next prop)
  5753. (while (< beg end)
  5754. (setq next (next-single-property-change beg 'display nil end)
  5755. prop (get-text-property beg 'display))
  5756. (when (member prop org-script-display)
  5757. (put-text-property beg next 'display nil))
  5758. (setq beg next))))
  5759. (defun org-raise-scripts (limit)
  5760. "Add raise properties to sub/superscripts."
  5761. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5762. (re-search-forward
  5763. (if (eq org-use-sub-superscripts t)
  5764. org-match-substring-regexp
  5765. org-match-substring-with-braces-regexp)
  5766. limit t))
  5767. (let* ((pos (point)) table-p comment-p
  5768. (mpos (match-beginning 3))
  5769. (emph-p (get-text-property mpos 'org-emphasis))
  5770. (link-p (get-text-property mpos 'mouse-face))
  5771. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5772. (goto-char (point-at-bol))
  5773. (setq table-p (looking-at-p org-table-dataline-regexp)
  5774. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5775. (goto-char pos)
  5776. ;; Handle a_b^c
  5777. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5778. (unless (or comment-p emph-p link-p keyw-p)
  5779. (put-text-property (match-beginning 3) (match-end 0)
  5780. 'display
  5781. (if (equal (char-after (match-beginning 2)) ?^)
  5782. (nth (if table-p 3 1) org-script-display)
  5783. (nth (if table-p 2 0) org-script-display)))
  5784. (add-text-properties (match-beginning 2) (match-end 2)
  5785. (list 'invisible t))
  5786. (when (and (eq (char-after (match-beginning 3)) ?{)
  5787. (eq (char-before (match-end 3)) ?}))
  5788. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5789. (list 'invisible t))
  5790. (add-text-properties (1- (match-end 3)) (match-end 3)
  5791. (list 'invisible t))))
  5792. t)))
  5793. ;;;; Visibility cycling, including org-goto and indirect buffer
  5794. ;;; Cycling
  5795. (defvar-local org-cycle-global-status nil)
  5796. (put 'org-cycle-global-status 'org-state t)
  5797. (defvar-local org-cycle-subtree-status nil)
  5798. (put 'org-cycle-subtree-status 'org-state t)
  5799. (defvar org-inlinetask-min-level)
  5800. (defun org-unlogged-message (&rest args)
  5801. "Display a message, but avoid logging it in the *Messages* buffer."
  5802. (let ((message-log-max nil))
  5803. (apply 'message args)))
  5804. ;;;###autoload
  5805. (defun org-cycle (&optional arg)
  5806. "TAB-action and visibility cycling for Org mode.
  5807. This is the command invoked in Org mode by the `TAB' key. Its main
  5808. purpose is outline visibility cycling, but it also invokes other actions
  5809. in special contexts.
  5810. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5811. the entire
  5812. buffer through 3 states (global cycling)
  5813. 1. OVERVIEW: Show only top-level headlines.
  5814. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5815. 3. SHOW ALL: Show everything.
  5816. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5817. switch to the startup visibility,
  5818. determined by the variable `org-startup-folded', and by any VISIBILITY
  5819. properties in the buffer.
  5820. With a `\\[universal-argument] \\[universal-argument] \
  5821. \\[universal-argument]' prefix argument, show the entire buffer, including
  5822. any drawers.
  5823. When inside a table, re-align the table and move to the next field.
  5824. When point is at the beginning of a headline, rotate the subtree started
  5825. by this line through 3 different states (local cycling)
  5826. 1. FOLDED: Only the main headline is shown.
  5827. 2. CHILDREN: The main headline and the direct children are shown.
  5828. From this state, you can move to one of the children
  5829. and zoom in further.
  5830. 3. SUBTREE: Show the entire subtree, including body text.
  5831. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5832. When point is at the beginning of an empty headline and the variable
  5833. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5834. of the headline by demoting and promoting it to likely levels. This
  5835. speeds up creation document structure by pressing `TAB' once or several
  5836. times right after creating a new headline.
  5837. When there is a numeric prefix, go up to a heading with level ARG, do
  5838. a `show-subtree' and return to the previous cursor position. If ARG
  5839. is negative, go up that many levels.
  5840. When point is not at the beginning of a headline, execute the global
  5841. binding for `TAB', which is re-indenting the line. See the option
  5842. `org-cycle-emulate-tab' for details.
  5843. As a special case, if point is at the beginning of the buffer and there is
  5844. no headline in line 1, this function will act as if called with prefix arg
  5845. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5846. prefix arg, but only
  5847. if the variable `org-cycle-global-at-bob' is t."
  5848. (interactive "P")
  5849. (org-load-modules-maybe)
  5850. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5851. (and org-cycle-level-after-item/entry-creation
  5852. (or (org-cycle-level)
  5853. (org-cycle-item-indentation))))
  5854. (let* ((limit-level
  5855. (or org-cycle-max-level
  5856. (and (boundp 'org-inlinetask-min-level)
  5857. org-inlinetask-min-level
  5858. (1- org-inlinetask-min-level))))
  5859. (nstars (and limit-level
  5860. (if org-odd-levels-only
  5861. (and limit-level (1- (* limit-level 2)))
  5862. limit-level)))
  5863. (org-outline-regexp
  5864. (if (not (derived-mode-p 'org-mode))
  5865. outline-regexp
  5866. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5867. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5868. (not (looking-at org-outline-regexp))))
  5869. (org-cycle-hook
  5870. (if bob-special
  5871. (delq 'org-optimize-window-after-visibility-change
  5872. (copy-sequence org-cycle-hook))
  5873. org-cycle-hook))
  5874. (pos (point)))
  5875. (cond
  5876. ((equal arg '(16))
  5877. (setq last-command 'dummy)
  5878. (org-set-startup-visibility)
  5879. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5880. ((equal arg '(64))
  5881. (outline-show-all)
  5882. (org-unlogged-message "Entire buffer visible, including drawers"))
  5883. ((equal arg '(4)) (org-cycle-internal-global))
  5884. ;; Try hiding block at point.
  5885. ((org-hide-block-toggle-maybe))
  5886. ;; Try cdlatex TAB completion
  5887. ((org-try-cdlatex-tab))
  5888. ;; Table: enter it or move to the next field.
  5889. ((org-at-table-p 'any)
  5890. (if (org-at-table.el-p)
  5891. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5892. Use `\\[org-edit-special]' to edit table.el tables"))
  5893. (if arg (org-table-edit-field t)
  5894. (org-table-justify-field-maybe)
  5895. (call-interactively 'org-table-next-field))))
  5896. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5897. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5898. (bob-special (org-cycle-internal-global))
  5899. ;; Drawers: delegate to `org-flag-drawer'.
  5900. ((save-excursion
  5901. (beginning-of-line 1)
  5902. (looking-at org-drawer-regexp))
  5903. (org-flag-drawer ; toggle block visibility
  5904. (not (get-char-property (match-end 0) 'invisible))))
  5905. ;; Show-subtree, ARG levels up from here.
  5906. ((integerp arg)
  5907. (save-excursion
  5908. (org-back-to-heading)
  5909. (outline-up-heading (if (< arg 0) (- arg)
  5910. (- (funcall outline-level) arg)))
  5911. (org-show-subtree)))
  5912. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5913. ((and (featurep 'org-inlinetask)
  5914. (org-inlinetask-at-task-p)
  5915. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5916. (org-inlinetask-toggle-visibility))
  5917. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5918. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5919. (save-excursion (move-beginning-of-line 1)
  5920. (looking-at org-outline-regexp)))
  5921. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5922. (org-cycle-internal-local))
  5923. ;; From there: TAB emulation and template completion.
  5924. (buffer-read-only (org-back-to-heading))
  5925. ((run-hook-with-args-until-success
  5926. 'org-tab-after-check-for-cycling-hook))
  5927. ((run-hook-with-args-until-success
  5928. 'org-tab-before-tab-emulation-hook))
  5929. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5930. (or (not (bolp))
  5931. (not (looking-at org-outline-regexp))))
  5932. (call-interactively (global-key-binding "\t")))
  5933. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5934. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5935. (or (and (eq org-cycle-emulate-tab 'white)
  5936. (= (match-end 0) (point-at-eol)))
  5937. (and (eq org-cycle-emulate-tab 'whitestart)
  5938. (>= (match-end 0) pos))))
  5939. t
  5940. (eq org-cycle-emulate-tab t))
  5941. (call-interactively (global-key-binding "\t")))
  5942. (t (save-excursion
  5943. (org-back-to-heading)
  5944. (org-cycle)))))))
  5945. (defun org-cycle-internal-global ()
  5946. "Do the global cycling action."
  5947. ;; Hack to avoid display of messages for .org attachments in Gnus
  5948. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5949. (cond
  5950. ((and (eq last-command this-command)
  5951. (eq org-cycle-global-status 'overview))
  5952. ;; We just created the overview - now do table of contents
  5953. ;; This can be slow in very large buffers, so indicate action
  5954. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5955. (unless ga (org-unlogged-message "CONTENTS..."))
  5956. (org-content)
  5957. (unless ga (org-unlogged-message "CONTENTS...done"))
  5958. (setq org-cycle-global-status 'contents)
  5959. (run-hook-with-args 'org-cycle-hook 'contents))
  5960. ((and (eq last-command this-command)
  5961. (eq org-cycle-global-status 'contents))
  5962. ;; We just showed the table of contents - now show everything
  5963. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5964. (outline-show-all)
  5965. (unless ga (org-unlogged-message "SHOW ALL"))
  5966. (setq org-cycle-global-status 'all)
  5967. (run-hook-with-args 'org-cycle-hook 'all))
  5968. (t
  5969. ;; Default action: go to overview
  5970. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5971. (org-overview)
  5972. (unless ga (org-unlogged-message "OVERVIEW"))
  5973. (setq org-cycle-global-status 'overview)
  5974. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5975. (defvar org-called-with-limited-levels nil
  5976. "Non-nil when `org-with-limited-levels' is currently active.")
  5977. (defun org-cycle-internal-local ()
  5978. "Do the local cycling action."
  5979. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5980. ;; First, determine end of headline (EOH), end of subtree or item
  5981. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5982. (save-excursion
  5983. (if (org-at-item-p)
  5984. (progn
  5985. (beginning-of-line)
  5986. (setq struct (org-list-struct))
  5987. (setq eoh (point-at-eol))
  5988. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5989. (setq has-children (org-list-has-child-p (point) struct)))
  5990. (org-back-to-heading)
  5991. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5992. (setq eos (save-excursion (org-end-of-subtree t t)
  5993. (when (bolp) (backward-char)) (point)))
  5994. (setq has-children
  5995. (or (save-excursion
  5996. (let ((level (funcall outline-level)))
  5997. (outline-next-heading)
  5998. (and (org-at-heading-p t)
  5999. (> (funcall outline-level) level))))
  6000. (save-excursion
  6001. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6002. ;; Determine end invisible part of buffer (EOL)
  6003. (beginning-of-line 2)
  6004. (while (and (not (eobp)) ;This is like `next-line'.
  6005. (get-char-property (1- (point)) 'invisible))
  6006. (goto-char (next-single-char-property-change (point) 'invisible))
  6007. (and (eolp) (beginning-of-line 2)))
  6008. (setq eol (point)))
  6009. ;; Find out what to do next and set `this-command'
  6010. (cond
  6011. ((= eos eoh)
  6012. ;; Nothing is hidden behind this heading
  6013. (unless (org-before-first-heading-p)
  6014. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6015. (org-unlogged-message "EMPTY ENTRY")
  6016. (setq org-cycle-subtree-status nil)
  6017. (save-excursion
  6018. (goto-char eos)
  6019. (outline-next-heading)
  6020. (when (org-invisible-p) (org-flag-heading nil))))
  6021. ((and (or (>= eol eos)
  6022. (not (string-match "\\S-" (buffer-substring eol eos))))
  6023. (or has-children
  6024. (not (setq children-skipped
  6025. org-cycle-skip-children-state-if-no-children))))
  6026. ;; Entire subtree is hidden in one line: children view
  6027. (unless (org-before-first-heading-p)
  6028. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6029. (if (org-at-item-p)
  6030. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6031. (org-show-entry)
  6032. (org-with-limited-levels (org-show-children))
  6033. ;; FIXME: This slows down the func way too much.
  6034. ;; How keep drawers hidden in subtree anyway?
  6035. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6036. ;; (org-cycle-hide-drawers 'subtree))
  6037. ;; Fold every list in subtree to top-level items.
  6038. (when (eq org-cycle-include-plain-lists 'integrate)
  6039. (save-excursion
  6040. (org-back-to-heading)
  6041. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6042. (beginning-of-line 1)
  6043. (let* ((struct (org-list-struct))
  6044. (prevs (org-list-prevs-alist struct))
  6045. (end (org-list-get-bottom-point struct)))
  6046. (dolist (e (org-list-get-all-items (point) struct prevs))
  6047. (org-list-set-item-visibility e struct 'folded))
  6048. (goto-char (if (< end eos) end eos)))))))
  6049. (org-unlogged-message "CHILDREN")
  6050. (save-excursion
  6051. (goto-char eos)
  6052. (outline-next-heading)
  6053. (when (org-invisible-p) (org-flag-heading nil)))
  6054. (setq org-cycle-subtree-status 'children)
  6055. (unless (org-before-first-heading-p)
  6056. (run-hook-with-args 'org-cycle-hook 'children)))
  6057. ((or children-skipped
  6058. (and (eq last-command this-command)
  6059. (eq org-cycle-subtree-status 'children)))
  6060. ;; We just showed the children, or no children are there,
  6061. ;; now show everything.
  6062. (unless (org-before-first-heading-p)
  6063. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6064. (outline-flag-region eoh eos nil)
  6065. (org-unlogged-message
  6066. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6067. (setq org-cycle-subtree-status 'subtree)
  6068. (unless (org-before-first-heading-p)
  6069. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6070. (t
  6071. ;; Default action: hide the subtree.
  6072. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6073. (outline-flag-region eoh eos t)
  6074. (org-unlogged-message "FOLDED")
  6075. (setq org-cycle-subtree-status 'folded)
  6076. (unless (org-before-first-heading-p)
  6077. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6078. ;;;###autoload
  6079. (defun org-global-cycle (&optional arg)
  6080. "Cycle the global visibility. For details see `org-cycle'.
  6081. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6082. With a numeric prefix, show all headlines up to that level."
  6083. (interactive "P")
  6084. (let ((org-cycle-include-plain-lists
  6085. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6086. (cond
  6087. ((integerp arg)
  6088. (outline-show-all)
  6089. (outline-hide-sublevels arg)
  6090. (setq org-cycle-global-status 'contents))
  6091. ((equal arg '(4))
  6092. (org-set-startup-visibility)
  6093. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6094. (t
  6095. (org-cycle '(4))))))
  6096. (defun org-set-startup-visibility ()
  6097. "Set the visibility required by startup options and properties."
  6098. (cond
  6099. ((eq org-startup-folded t)
  6100. (org-overview))
  6101. ((eq org-startup-folded 'content)
  6102. (org-content))
  6103. ((or (eq org-startup-folded 'showeverything)
  6104. (eq org-startup-folded nil))
  6105. (outline-show-all)))
  6106. (unless (eq org-startup-folded 'showeverything)
  6107. (when org-hide-block-startup (org-hide-block-all))
  6108. (org-set-visibility-according-to-property 'no-cleanup)
  6109. (org-cycle-hide-archived-subtrees 'all)
  6110. (org-cycle-hide-drawers 'all)
  6111. (org-cycle-show-empty-lines t)))
  6112. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6113. "Switch subtree visibilities according to :VISIBILITY: property."
  6114. (interactive)
  6115. (org-with-wide-buffer
  6116. (goto-char (point-min))
  6117. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6118. (if (not (org-at-property-p)) (outline-next-heading)
  6119. (let ((state (match-string 3)))
  6120. (save-excursion
  6121. (org-back-to-heading t)
  6122. (outline-hide-subtree)
  6123. (org-reveal)
  6124. (cond
  6125. ((equal state "folded")
  6126. (outline-hide-subtree))
  6127. ((equal state "children")
  6128. (org-show-hidden-entry)
  6129. (org-show-children))
  6130. ((equal state "content")
  6131. (save-excursion
  6132. (save-restriction
  6133. (org-narrow-to-subtree)
  6134. (org-content))))
  6135. ((member state '("all" "showall"))
  6136. (outline-show-subtree)))))))
  6137. (unless no-cleanup
  6138. (org-cycle-hide-archived-subtrees 'all)
  6139. (org-cycle-hide-drawers 'all)
  6140. (org-cycle-show-empty-lines 'all))))
  6141. ;; This function uses outline-regexp instead of the more fundamental
  6142. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6143. ;; buffers, where outline-regexp is needed.
  6144. (defun org-overview ()
  6145. "Switch to overview mode, showing only top-level headlines.
  6146. This shows all headlines with a level equal or greater than the level
  6147. of the first headline in the buffer. This is important, because if the
  6148. first headline is not level one, then (hide-sublevels 1) gives confusing
  6149. results."
  6150. (interactive)
  6151. (save-excursion
  6152. (let ((level
  6153. (save-excursion
  6154. (goto-char (point-min))
  6155. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6156. (goto-char (match-beginning 0))
  6157. (funcall outline-level)))))
  6158. (and level (outline-hide-sublevels level)))))
  6159. (defun org-content (&optional arg)
  6160. "Show all headlines in the buffer, like a table of contents.
  6161. With numerical argument N, show content up to level N."
  6162. (interactive "P")
  6163. (org-overview)
  6164. (save-excursion
  6165. ;; Visit all headings and show their offspring
  6166. (and (integerp arg) (org-overview))
  6167. (goto-char (point-max))
  6168. (catch 'exit
  6169. (while (and (progn (condition-case nil
  6170. (outline-previous-visible-heading 1)
  6171. (error (goto-char (point-min))))
  6172. t)
  6173. (looking-at org-outline-regexp))
  6174. (if (integerp arg)
  6175. (org-show-children (1- arg))
  6176. (outline-show-branches))
  6177. (when (bobp) (throw 'exit nil))))))
  6178. (defun org-optimize-window-after-visibility-change (state)
  6179. "Adjust the window after a change in outline visibility.
  6180. This function is the default value of the hook `org-cycle-hook'."
  6181. (when (get-buffer-window (current-buffer))
  6182. (cond
  6183. ((eq state 'content) nil)
  6184. ((eq state 'all) nil)
  6185. ((eq state 'folded) nil)
  6186. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6187. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6188. (defun org-remove-empty-overlays-at (pos)
  6189. "Remove outline overlays that do not contain non-white stuff."
  6190. (dolist (o (overlays-at pos))
  6191. (and (eq 'outline (overlay-get o 'invisible))
  6192. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6193. (overlay-end o))))
  6194. (delete-overlay o))))
  6195. (defun org-clean-visibility-after-subtree-move ()
  6196. "Fix visibility issues after moving a subtree."
  6197. ;; First, find a reasonable region to look at:
  6198. ;; Start two siblings above, end three below
  6199. (let* ((beg (save-excursion
  6200. (and (org-get-last-sibling)
  6201. (org-get-last-sibling))
  6202. (point)))
  6203. (end (save-excursion
  6204. (and (org-get-next-sibling)
  6205. (org-get-next-sibling)
  6206. (org-get-next-sibling))
  6207. (if (org-at-heading-p)
  6208. (point-at-eol)
  6209. (point))))
  6210. (level (looking-at "\\*+"))
  6211. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6212. (save-excursion
  6213. (save-restriction
  6214. (narrow-to-region beg end)
  6215. (when re
  6216. ;; Properly fold already folded siblings
  6217. (goto-char (point-min))
  6218. (while (re-search-forward re nil t)
  6219. (when (and (not (org-invisible-p))
  6220. (save-excursion
  6221. (goto-char (point-at-eol)) (org-invisible-p)))
  6222. (outline-hide-entry))))
  6223. (org-cycle-show-empty-lines 'overview)
  6224. (org-cycle-hide-drawers 'overview)))))
  6225. (defun org-cycle-show-empty-lines (state)
  6226. "Show empty lines above all visible headlines.
  6227. The region to be covered depends on STATE when called through
  6228. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6229. entire buffer covered. Note that an empty line is only shown if there
  6230. are at least `org-cycle-separator-lines' empty lines before the headline."
  6231. (when (/= org-cycle-separator-lines 0)
  6232. (save-excursion
  6233. (let* ((n (abs org-cycle-separator-lines))
  6234. (re (cond
  6235. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6236. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6237. (t (let ((ns (number-to-string (- n 2))))
  6238. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6239. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6240. beg end)
  6241. (cond
  6242. ((memq state '(overview contents t))
  6243. (setq beg (point-min) end (point-max)))
  6244. ((memq state '(children folded))
  6245. (setq beg (point)
  6246. end (progn (org-end-of-subtree t t)
  6247. (line-beginning-position 2)))))
  6248. (when beg
  6249. (goto-char beg)
  6250. (while (re-search-forward re end t)
  6251. (unless (get-char-property (match-end 1) 'invisible)
  6252. (let ((e (match-end 1))
  6253. (b (if (>= org-cycle-separator-lines 0)
  6254. (match-beginning 1)
  6255. (save-excursion
  6256. (goto-char (match-beginning 0))
  6257. (skip-chars-backward " \t\n")
  6258. (line-end-position)))))
  6259. (outline-flag-region b e nil))))))))
  6260. ;; Never hide empty lines at the end of the file.
  6261. (save-excursion
  6262. (goto-char (point-max))
  6263. (outline-previous-heading)
  6264. (outline-end-of-heading)
  6265. (when (and (looking-at "[ \t\n]+")
  6266. (= (match-end 0) (point-max)))
  6267. (outline-flag-region (point) (match-end 0) nil))))
  6268. (defun org-show-empty-lines-in-parent ()
  6269. "Move to the parent and re-show empty lines before visible headlines."
  6270. (save-excursion
  6271. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6272. (org-cycle-show-empty-lines context))))
  6273. (defun org-files-list ()
  6274. "Return `org-agenda-files' list, plus all open Org files.
  6275. This is useful for operations that need to scan all of a user's
  6276. open and agenda-wise Org files."
  6277. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6278. (dolist (buf (buffer-list))
  6279. (with-current-buffer buf
  6280. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6281. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6282. files))
  6283. (defsubst org-entry-beginning-position ()
  6284. "Return the beginning position of the current entry."
  6285. (save-excursion (org-back-to-heading t) (point)))
  6286. (defsubst org-entry-end-position ()
  6287. "Return the end position of the current entry."
  6288. (save-excursion (outline-next-heading) (point)))
  6289. (defun org-cycle-hide-drawers (state &optional exceptions)
  6290. "Re-hide all drawers after a visibility state change.
  6291. STATE should be one of the symbols listed in the docstring of
  6292. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6293. a list of strings specifying which drawers should not be hidden."
  6294. (when (and (derived-mode-p 'org-mode)
  6295. (not (memq state '(overview folded contents))))
  6296. (save-excursion
  6297. (let* ((globalp (eq state 'all))
  6298. (beg (if globalp (point-min) (point)))
  6299. (end (if globalp (point-max)
  6300. (if (eq state 'children)
  6301. (save-excursion (outline-next-heading) (point))
  6302. (org-end-of-subtree t)))))
  6303. (goto-char beg)
  6304. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6305. (unless (member-ignore-case (match-string 1) exceptions)
  6306. (let ((drawer (org-element-at-point)))
  6307. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6308. (org-flag-drawer t drawer)
  6309. ;; Make sure to skip drawer entirely or we might flag
  6310. ;; it another time when matching its ending line with
  6311. ;; `org-drawer-regexp'.
  6312. (goto-char (org-element-property :end drawer))))))))))
  6313. (defun org-flag-drawer (flag &optional element)
  6314. "When FLAG is non-nil, hide the drawer we are at.
  6315. Otherwise make it visible. When optional argument ELEMENT is
  6316. a parsed drawer, as returned by `org-element-at-point', hide or
  6317. show that drawer instead."
  6318. (let ((drawer (or element
  6319. (and (save-excursion
  6320. (beginning-of-line)
  6321. (looking-at-p org-drawer-regexp))
  6322. (org-element-at-point)))))
  6323. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6324. (let ((post (org-element-property :post-affiliated drawer)))
  6325. (save-excursion
  6326. (outline-flag-region
  6327. (progn (goto-char post) (line-end-position))
  6328. (progn (goto-char (org-element-property :end drawer))
  6329. (skip-chars-backward " \r\t\n")
  6330. (line-end-position))
  6331. flag))
  6332. ;; When the drawer is hidden away, make sure point lies in
  6333. ;; a visible part of the buffer.
  6334. (when (and flag (> (line-beginning-position) post))
  6335. (goto-char post))))))
  6336. (defun org-subtree-end-visible-p ()
  6337. "Is the end of the current subtree visible?"
  6338. (pos-visible-in-window-p
  6339. (save-excursion (org-end-of-subtree t) (point))))
  6340. (defun org-first-headline-recenter ()
  6341. "Move cursor to the first headline and recenter the headline."
  6342. (let ((window (get-buffer-window)))
  6343. (when window
  6344. (goto-char (point-min))
  6345. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6346. (set-window-start window (line-beginning-position))))))
  6347. ;;; Saving and restoring visibility
  6348. (defun org-outline-overlay-data (&optional use-markers)
  6349. "Return a list of the locations of all outline overlays.
  6350. These are overlays with the `invisible' property value `outline'.
  6351. The return value is a list of cons cells, with start and stop
  6352. positions for each overlay.
  6353. If USE-MARKERS is set, return the positions as markers."
  6354. (let (beg end)
  6355. (org-with-wide-buffer
  6356. (delq nil
  6357. (mapcar (lambda (o)
  6358. (when (eq (overlay-get o 'invisible) 'outline)
  6359. (setq beg (overlay-start o)
  6360. end (overlay-end o))
  6361. (and beg end (> end beg)
  6362. (if use-markers
  6363. (cons (copy-marker beg)
  6364. (copy-marker end t))
  6365. (cons beg end)))))
  6366. (overlays-in (point-min) (point-max)))))))
  6367. (defun org-set-outline-overlay-data (data)
  6368. "Create visibility overlays for all positions in DATA.
  6369. DATA should have been made by `org-outline-overlay-data'."
  6370. (org-with-wide-buffer
  6371. (outline-show-all)
  6372. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6373. ;;; Folding of blocks
  6374. (defvar-local org-hide-block-overlays nil
  6375. "Overlays hiding blocks.")
  6376. (defun org-block-map (function &optional start end)
  6377. "Call FUNCTION at the head of all source blocks in the current buffer.
  6378. Optional arguments START and END can be used to limit the range."
  6379. (let ((start (or start (point-min)))
  6380. (end (or end (point-max))))
  6381. (save-excursion
  6382. (goto-char start)
  6383. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6384. (save-excursion
  6385. (save-match-data
  6386. (goto-char (match-beginning 0))
  6387. (funcall function)))))))
  6388. (defun org-hide-block-toggle-all ()
  6389. "Toggle the visibility of all blocks in the current buffer."
  6390. (org-block-map 'org-hide-block-toggle))
  6391. (defun org-hide-block-all ()
  6392. "Fold all blocks in the current buffer."
  6393. (interactive)
  6394. (org-show-block-all)
  6395. (org-block-map 'org-hide-block-toggle-maybe))
  6396. (defun org-show-block-all ()
  6397. "Unfold all blocks in the current buffer."
  6398. (interactive)
  6399. (mapc #'delete-overlay org-hide-block-overlays)
  6400. (setq org-hide-block-overlays nil))
  6401. (defun org-hide-block-toggle-maybe ()
  6402. "Toggle visibility of block at point.
  6403. Unlike to `org-hide-block-toggle', this function does not throw
  6404. an error. Return a non-nil value when toggling is successful."
  6405. (interactive)
  6406. (ignore-errors (org-hide-block-toggle)))
  6407. (defun org-hide-block-toggle (&optional force)
  6408. "Toggle the visibility of the current block.
  6409. When optional argument FORCE is `off', make block visible. If it
  6410. is non-nil, hide it unconditionally. Throw an error when not at
  6411. a block. Return a non-nil value when toggling is successful."
  6412. (interactive)
  6413. (let ((element (org-element-at-point)))
  6414. (unless (memq (org-element-type element)
  6415. '(center-block comment-block dynamic-block example-block
  6416. export-block quote-block special-block
  6417. src-block verse-block))
  6418. (user-error "Not at a block"))
  6419. (let* ((start (save-excursion
  6420. (goto-char (org-element-property :post-affiliated element))
  6421. (line-end-position)))
  6422. (end (save-excursion
  6423. (goto-char (org-element-property :end element))
  6424. (skip-chars-backward " \r\t\n")
  6425. (line-end-position)))
  6426. (overlays (overlays-at start)))
  6427. (cond
  6428. ;; Do nothing when not before or at the block opening line or
  6429. ;; at the block closing line.
  6430. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6431. ((and (not (eq force 'off))
  6432. (not (memq t (mapcar
  6433. (lambda (o)
  6434. (eq (overlay-get o 'invisible) 'org-hide-block))
  6435. overlays))))
  6436. (let ((ov (make-overlay start end)))
  6437. (overlay-put ov 'invisible 'org-hide-block)
  6438. ;; Make the block accessible to `isearch'.
  6439. (overlay-put
  6440. ov 'isearch-open-invisible
  6441. (lambda (ov)
  6442. (when (memq ov org-hide-block-overlays)
  6443. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6444. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6445. (delete-overlay ov))))
  6446. (push ov org-hide-block-overlays)
  6447. ;; When the block is hidden away, make sure point is left in
  6448. ;; a visible part of the buffer.
  6449. (when (> (line-beginning-position) start)
  6450. (goto-char start)
  6451. (beginning-of-line))
  6452. ;; Signal successful toggling.
  6453. t))
  6454. ((or (not force) (eq force 'off))
  6455. (dolist (ov overlays t)
  6456. (when (memq ov org-hide-block-overlays)
  6457. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6458. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6459. (delete-overlay ov))))))))
  6460. ;; Remove overlays when changing major mode
  6461. (add-hook 'org-mode-hook
  6462. (lambda () (add-hook 'change-major-mode-hook
  6463. 'org-show-block-all 'append 'local)))
  6464. ;;; Indirect buffer display of subtrees
  6465. (defvar org-indirect-dedicated-frame nil
  6466. "This is the frame being used for indirect tree display.")
  6467. (defvar org-last-indirect-buffer nil)
  6468. (defun org-tree-to-indirect-buffer (&optional arg)
  6469. "Create indirect buffer and narrow it to current subtree.
  6470. With a numerical prefix ARG, go up to this level and then take that tree.
  6471. If ARG is negative, go up that many levels.
  6472. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6473. indirect buffer previously made with this command, to avoid proliferation of
  6474. indirect buffers. However, when you call the command with a \
  6475. `\\[universal-argument]' prefix, or
  6476. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6477. so that you can work with several indirect buffers at the same time. If
  6478. `org-indirect-buffer-display' is `dedicated-frame', the \
  6479. `\\[universal-argument]' prefix also
  6480. requests that a new frame be made for the new buffer, so that the dedicated
  6481. frame is not changed."
  6482. (interactive "P")
  6483. (let ((cbuf (current-buffer))
  6484. (cwin (selected-window))
  6485. (pos (point))
  6486. beg end level heading ibuf)
  6487. (save-excursion
  6488. (org-back-to-heading t)
  6489. (when (numberp arg)
  6490. (setq level (org-outline-level))
  6491. (when (< arg 0) (setq arg (+ level arg)))
  6492. (while (> (setq level (org-outline-level)) arg)
  6493. (org-up-heading-safe)))
  6494. (setq beg (point)
  6495. heading (org-get-heading 'no-tags))
  6496. (org-end-of-subtree t t)
  6497. (when (org-at-heading-p) (backward-char 1))
  6498. (setq end (point)))
  6499. (when (and (buffer-live-p org-last-indirect-buffer)
  6500. (not (eq org-indirect-buffer-display 'new-frame))
  6501. (not arg))
  6502. (kill-buffer org-last-indirect-buffer))
  6503. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6504. org-last-indirect-buffer ibuf)
  6505. (cond
  6506. ((or (eq org-indirect-buffer-display 'new-frame)
  6507. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6508. (select-frame (make-frame))
  6509. (delete-other-windows)
  6510. (pop-to-buffer-same-window ibuf)
  6511. (org-set-frame-title heading))
  6512. ((eq org-indirect-buffer-display 'dedicated-frame)
  6513. (raise-frame
  6514. (select-frame (or (and org-indirect-dedicated-frame
  6515. (frame-live-p org-indirect-dedicated-frame)
  6516. org-indirect-dedicated-frame)
  6517. (setq org-indirect-dedicated-frame (make-frame)))))
  6518. (delete-other-windows)
  6519. (pop-to-buffer-same-window ibuf)
  6520. (org-set-frame-title (concat "Indirect: " heading)))
  6521. ((eq org-indirect-buffer-display 'current-window)
  6522. (pop-to-buffer-same-window ibuf))
  6523. ((eq org-indirect-buffer-display 'other-window)
  6524. (pop-to-buffer ibuf))
  6525. (t (error "Invalid value")))
  6526. (narrow-to-region beg end)
  6527. (outline-show-all)
  6528. (goto-char pos)
  6529. (run-hook-with-args 'org-cycle-hook 'all)
  6530. (and (window-live-p cwin) (select-window cwin))))
  6531. (defun org-get-indirect-buffer (&optional buffer heading)
  6532. (setq buffer (or buffer (current-buffer)))
  6533. (let ((n 1) (base (buffer-name buffer)) bname)
  6534. (while (buffer-live-p
  6535. (get-buffer
  6536. (setq bname
  6537. (concat base "-"
  6538. (if heading (concat heading "-" (number-to-string n))
  6539. (number-to-string n))))))
  6540. (setq n (1+ n)))
  6541. (condition-case nil
  6542. (make-indirect-buffer buffer bname 'clone)
  6543. (error (make-indirect-buffer buffer bname)))))
  6544. (defun org-set-frame-title (title)
  6545. "Set the title of the current frame to the string TITLE."
  6546. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6547. ;;;; Structure editing
  6548. ;;; Inserting headlines
  6549. (defun org--line-empty-p (n)
  6550. "Is the Nth next line empty?
  6551. Counts the current line as N = 1 and the previous line as N = 0;
  6552. see `beginning-of-line'."
  6553. (save-excursion
  6554. (and (not (bobp))
  6555. (or (beginning-of-line n) t)
  6556. (save-match-data
  6557. (looking-at "[ \t]*$")))))
  6558. (defun org-previous-line-empty-p ()
  6559. "Is the previous line a blank line?
  6560. When NEXT is non-nil, check the next line instead."
  6561. (org--line-empty-p 0))
  6562. (defun org-next-line-empty-p ()
  6563. "Is the previous line a blank line?
  6564. When NEXT is non-nil, check the next line instead."
  6565. (org--line-empty-p 2))
  6566. (defun org--blank-before-heading-p (&optional parent)
  6567. "Non-nil when an empty line should precede a new heading here.
  6568. When optional argument PARENT is non-nil, consider parent
  6569. headline instead of current one."
  6570. (pcase (assq 'heading org-blank-before-new-entry)
  6571. (`(heading . auto)
  6572. (save-excursion
  6573. (org-with-limited-levels
  6574. (unless (and (org-before-first-heading-p)
  6575. (not (outline-next-heading)))
  6576. (org-back-to-heading t)
  6577. (when parent (org-up-heading-safe))
  6578. (cond ((not (bobp))
  6579. (org-previous-line-empty-p))
  6580. ((outline-next-heading)
  6581. (org-previous-line-empty-p))
  6582. ;; Ignore trailing spaces on last buffer line.
  6583. ((progn (skip-chars-backward " \t") (bolp))
  6584. (org-previous-line-empty-p))
  6585. (t nil))))))
  6586. (`(heading . ,value) value)
  6587. (_ nil)))
  6588. (defun org-insert-heading (&optional arg invisible-ok top)
  6589. "Insert a new heading or an item with the same depth at point.
  6590. If point is at the beginning of a heading, insert a new heading
  6591. or a new headline above the current one. When at the beginning
  6592. of a regular line of text, turn it into a heading.
  6593. If point is in the middle of a line, split it and create a new
  6594. headline with the text in the current line after point (see
  6595. `org-M-RET-may-split-line' on how to modify this behavior). As
  6596. a special case, on a headline, splitting can only happen on the
  6597. title itself. E.g., this excludes breaking stars or tags.
  6598. With a `\\[universal-argument]' prefix, set \
  6599. `org-insert-heading-respect-content' to
  6600. a non-nil value for the duration of the command. This forces the
  6601. insertion of a heading after the current subtree, independently
  6602. on the location of point.
  6603. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6604. insert the heading at the end of the tree
  6605. above the current heading. For example, if point is within a
  6606. 2nd-level heading, then it will insert a 2nd-level heading at
  6607. the end of the 1st-level parent subtree.
  6608. When INVISIBLE-OK is set, stop at invisible headlines when going
  6609. back. This is important for non-interactive uses of the
  6610. command.
  6611. When optional argument TOP is non-nil, insert a level 1 heading,
  6612. unconditionally."
  6613. (interactive "P")
  6614. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6615. (level (org-current-level))
  6616. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6617. (cond
  6618. ((or org-insert-heading-respect-content
  6619. (member arg '((4) (16)))
  6620. (and (not invisible-ok)
  6621. (invisible-p (max (1- (point)) (point-min)))))
  6622. ;; Position point at the location of insertion.
  6623. (if (not level) ;before first headline
  6624. (org-with-limited-levels (outline-next-heading))
  6625. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6626. ;; is nil.
  6627. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6628. (cond ((equal arg '(16))
  6629. (org-up-heading-safe)
  6630. (org-end-of-subtree t t))
  6631. (t
  6632. (org-end-of-subtree t t))))
  6633. (unless (bolp) (insert "\n")) ;ensure final newline
  6634. (unless (and blank? (org-previous-line-empty-p))
  6635. (org-N-empty-lines-before-current (if blank? 1 0)))
  6636. (insert stars " \n")
  6637. (forward-char -1))
  6638. ;; At a headline...
  6639. ((org-at-heading-p)
  6640. (cond ((bolp)
  6641. (when blank? (save-excursion (insert "\n")))
  6642. (save-excursion (insert stars " \n"))
  6643. (unless (and blank? (org-previous-line-empty-p))
  6644. (org-N-empty-lines-before-current (if blank? 1 0)))
  6645. (end-of-line))
  6646. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6647. (org-match-line org-complex-heading-regexp)
  6648. (org-pos-in-match-range (point) 4))
  6649. ;; Grab the text that should moved to the new headline.
  6650. ;; Preserve tags.
  6651. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6652. (if (looking-at "[ \t]*$") (replace-match "")
  6653. (org-set-tags nil t))
  6654. (end-of-line)
  6655. (when blank? (insert "\n"))
  6656. (insert "\n" stars " ")
  6657. (when (org-string-nw-p split) (insert split))
  6658. (when (eobp) (save-excursion (insert "\n")))))
  6659. (t
  6660. (end-of-line)
  6661. (when blank? (insert "\n"))
  6662. (insert "\n" stars " ")
  6663. (when (eobp) (save-excursion (insert "\n"))))))
  6664. ;; On regular text, turn line into a headline or split, if
  6665. ;; appropriate.
  6666. ((bolp)
  6667. (insert stars " ")
  6668. (unless (and blank? (org-previous-line-empty-p))
  6669. (org-N-empty-lines-before-current (if blank? 1 0))))
  6670. (t
  6671. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6672. (end-of-line))
  6673. (insert "\n" stars " ")
  6674. (unless (and blank? (org-previous-line-empty-p))
  6675. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6676. (run-hooks 'org-insert-heading-hook))
  6677. (defun org-N-empty-lines-before-current (n)
  6678. "Make the number of empty lines before current exactly N.
  6679. So this will delete or add empty lines."
  6680. (let ((column (current-column)))
  6681. (beginning-of-line)
  6682. (unless (bobp)
  6683. (let ((start (save-excursion
  6684. (skip-chars-backward " \r\t\n")
  6685. (line-end-position))))
  6686. (delete-region start (line-end-position 0))))
  6687. (insert (make-string n ?\n))
  6688. (move-to-column column)))
  6689. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6690. "Return the heading of the current entry, without the stars.
  6691. When NO-TAGS is non-nil, don't include tags.
  6692. When NO-TODO is non-nil, don't include TODO keywords.
  6693. When NO-PRIORITY is non-nil, don't include priority cookie.
  6694. When NO-COMMENT is non-nil, don't include COMMENT string."
  6695. (save-excursion
  6696. (org-back-to-heading t)
  6697. (let ((case-fold-search nil))
  6698. (looking-at org-complex-heading-regexp)
  6699. (let ((todo (and (not no-todo) (match-string 2)))
  6700. (priority (and (not no-priority) (match-string 3)))
  6701. (headline (pcase (match-string 4)
  6702. (`nil "")
  6703. ((and (guard no-comment) h)
  6704. (replace-regexp-in-string
  6705. (eval-when-compile
  6706. (format "\\`%s[ \t]+" org-comment-string))
  6707. "" h))
  6708. (h h)))
  6709. (tags (and (not no-tags) (match-string 5))))
  6710. (mapconcat #'identity
  6711. (delq nil (list todo priority headline tags))
  6712. " ")))))
  6713. (defvar orgstruct-mode) ; defined below
  6714. (defun org-heading-components ()
  6715. "Return the components of the current heading.
  6716. This is a list with the following elements:
  6717. - the level as an integer
  6718. - the reduced level, different if `org-odd-levels-only' is set.
  6719. - the TODO keyword, or nil
  6720. - the priority character, like ?A, or nil if no priority is given
  6721. - the headline text itself, or the tags string if no headline text
  6722. - the tags string, or nil."
  6723. (save-excursion
  6724. (org-back-to-heading t)
  6725. (when (let (case-fold-search)
  6726. (looking-at
  6727. (if orgstruct-mode
  6728. org-heading-regexp
  6729. org-complex-heading-regexp)))
  6730. (if orgstruct-mode
  6731. (list (length (match-string 1))
  6732. (org-reduced-level (length (match-string 1)))
  6733. nil
  6734. nil
  6735. (match-string 2)
  6736. nil)
  6737. (list (length (match-string 1))
  6738. (org-reduced-level (length (match-string 1)))
  6739. (match-string-no-properties 2)
  6740. (and (match-end 3) (aref (match-string 3) 2))
  6741. (match-string-no-properties 4)
  6742. (match-string-no-properties 5))))))
  6743. (defun org-get-entry ()
  6744. "Get the entry text, after heading, entire subtree."
  6745. (save-excursion
  6746. (org-back-to-heading t)
  6747. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6748. (defun org-edit-headline (&optional heading)
  6749. "Edit the current headline.
  6750. Set it to HEADING when provided."
  6751. (interactive)
  6752. (org-with-wide-buffer
  6753. (org-back-to-heading t)
  6754. (let ((case-fold-search nil))
  6755. (when (looking-at org-complex-heading-regexp)
  6756. (let* ((old (match-string-no-properties 4))
  6757. (new (save-match-data
  6758. (org-trim (or heading (read-string "Edit: " old))))))
  6759. (unless (equal old new)
  6760. (if old (replace-match new t t nil 4)
  6761. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6762. (insert " " new))
  6763. (org-set-tags nil t)
  6764. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6765. (defun org-insert-heading-after-current ()
  6766. "Insert a new heading with same level as current, after current subtree."
  6767. (interactive)
  6768. (org-back-to-heading)
  6769. (org-insert-heading)
  6770. (org-move-subtree-down)
  6771. (end-of-line 1))
  6772. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6773. "Insert heading with `org-insert-heading-respect-content' set to t."
  6774. (interactive)
  6775. (org-insert-heading '(4) invisible-ok))
  6776. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6777. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6778. (interactive)
  6779. (org-insert-todo-heading force-state '(4)))
  6780. (defun org-insert-todo-heading (arg &optional force-heading)
  6781. "Insert a new heading with the same level and TODO state as current heading.
  6782. If the heading has no TODO state, or if the state is DONE, use
  6783. the first state (TODO by default). Also with one prefix arg,
  6784. force first state. With two prefix args, force inserting at the
  6785. end of the parent subtree.
  6786. When called at a plain list item, insert a new item with an
  6787. unchecked check box."
  6788. (interactive "P")
  6789. (when (or force-heading (not (org-insert-item 'checkbox)))
  6790. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6791. force-heading))
  6792. (save-excursion
  6793. (org-forward-heading-same-level -1)
  6794. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6795. (let* ((new-mark-x
  6796. (if (or (equal arg '(4))
  6797. (not (match-beginning 2))
  6798. (member (match-string 2) org-done-keywords))
  6799. (car org-todo-keywords-1)
  6800. (match-string 2)))
  6801. (new-mark
  6802. (or
  6803. (run-hook-with-args-until-success
  6804. 'org-todo-get-default-hook new-mark-x nil)
  6805. new-mark-x)))
  6806. (beginning-of-line 1)
  6807. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6808. (if org-treat-insert-todo-heading-as-state-change
  6809. (org-todo new-mark)
  6810. (insert new-mark " "))))
  6811. (when org-provide-todo-statistics
  6812. (org-update-parent-todo-statistics))))
  6813. (defun org-insert-subheading (arg)
  6814. "Insert a new subheading and demote it.
  6815. Works for outline headings and for plain lists alike."
  6816. (interactive "P")
  6817. (org-insert-heading arg)
  6818. (cond
  6819. ((org-at-heading-p) (org-do-demote))
  6820. ((org-at-item-p) (org-indent-item))))
  6821. (defun org-insert-todo-subheading (arg)
  6822. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6823. Works for outline headings and for plain lists alike."
  6824. (interactive "P")
  6825. (org-insert-todo-heading arg)
  6826. (cond
  6827. ((org-at-heading-p) (org-do-demote))
  6828. ((org-at-item-p) (org-indent-item))))
  6829. ;;; Promotion and Demotion
  6830. (defvar org-after-demote-entry-hook nil
  6831. "Hook run after an entry has been demoted.
  6832. The cursor will be at the beginning of the entry.
  6833. When a subtree is being demoted, the hook will be called for each node.")
  6834. (defvar org-after-promote-entry-hook nil
  6835. "Hook run after an entry has been promoted.
  6836. The cursor will be at the beginning of the entry.
  6837. When a subtree is being promoted, the hook will be called for each node.")
  6838. (defun org-promote-subtree ()
  6839. "Promote the entire subtree.
  6840. See also `org-promote'."
  6841. (interactive)
  6842. (save-excursion
  6843. (org-with-limited-levels (org-map-tree 'org-promote)))
  6844. (org-fix-position-after-promote))
  6845. (defun org-demote-subtree ()
  6846. "Demote the entire subtree.
  6847. See `org-demote' and `org-promote'."
  6848. (interactive)
  6849. (save-excursion
  6850. (org-with-limited-levels (org-map-tree 'org-demote)))
  6851. (org-fix-position-after-promote))
  6852. (defun org-do-promote ()
  6853. "Promote the current heading higher up the tree.
  6854. If the region is active in `transient-mark-mode', promote all
  6855. headings in the region."
  6856. (interactive)
  6857. (save-excursion
  6858. (if (org-region-active-p)
  6859. (org-map-region 'org-promote (region-beginning) (region-end))
  6860. (org-promote)))
  6861. (org-fix-position-after-promote))
  6862. (defun org-do-demote ()
  6863. "Demote the current heading lower down the tree.
  6864. If the region is active in `transient-mark-mode', demote all
  6865. headings in the region."
  6866. (interactive)
  6867. (save-excursion
  6868. (if (org-region-active-p)
  6869. (org-map-region 'org-demote (region-beginning) (region-end))
  6870. (org-demote)))
  6871. (org-fix-position-after-promote))
  6872. (defun org-fix-position-after-promote ()
  6873. "Fix cursor position and indentation after demoting/promoting."
  6874. (let ((pos (point)))
  6875. (when (save-excursion
  6876. (beginning-of-line)
  6877. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6878. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6879. (cond ((eobp) (insert " "))
  6880. ((eolp) (insert " "))
  6881. ((equal (char-after) ?\s) (forward-char 1))))))
  6882. (defun org-current-level ()
  6883. "Return the level of the current entry, or nil if before the first headline.
  6884. The level is the number of stars at the beginning of the
  6885. headline. Use `org-reduced-level' to remove the effect of
  6886. `org-odd-levels'. Unlike to `org-outline-level', this function
  6887. ignores inlinetasks."
  6888. (let ((level (org-with-limited-levels (org-outline-level))))
  6889. (and (> level 0) level)))
  6890. (defun org-get-previous-line-level ()
  6891. "Return the outline depth of the last headline before the current line.
  6892. Returns 0 for the first headline in the buffer, and nil if before the
  6893. first headline."
  6894. (and (org-current-level)
  6895. (or (and (/= (line-beginning-position) (point-min))
  6896. (save-excursion (beginning-of-line 0) (org-current-level)))
  6897. 0)))
  6898. (defun org-reduced-level (l)
  6899. "Compute the effective level of a heading.
  6900. This takes into account the setting of `org-odd-levels-only'."
  6901. (cond
  6902. ((zerop l) 0)
  6903. (org-odd-levels-only (1+ (floor (/ l 2))))
  6904. (t l)))
  6905. (defun org-level-increment ()
  6906. "Return the number of stars that will be added or removed at a
  6907. time to headlines when structure editing, based on the value of
  6908. `org-odd-levels-only'."
  6909. (if org-odd-levels-only 2 1))
  6910. (defun org-get-valid-level (level &optional change)
  6911. "Rectify a level change under the influence of `org-odd-levels-only'.
  6912. LEVEL is a current level, CHANGE is by how much the level should
  6913. be modified. Even if CHANGE is nil, LEVEL may be returned
  6914. modified because even level numbers will become the next higher
  6915. odd number. Returns values greater than 0."
  6916. (if org-odd-levels-only
  6917. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6918. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6919. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6920. (max 1 (+ level (or change 0)))))
  6921. (defun org-promote ()
  6922. "Promote the current heading higher up the tree."
  6923. (org-with-wide-buffer
  6924. (org-back-to-heading t)
  6925. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6926. after-change-functions))
  6927. (level (save-match-data (funcall outline-level)))
  6928. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6929. (diff (abs (- level (length up-head) -1))))
  6930. (cond
  6931. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6932. (replace-match "# " nil t))
  6933. ((= level 1)
  6934. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6935. (t (replace-match up-head nil t)))
  6936. (unless (= level 1)
  6937. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6938. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6939. (run-hooks 'org-after-promote-entry-hook))))
  6940. (defun org-demote ()
  6941. "Demote the current heading lower down the tree."
  6942. (org-with-wide-buffer
  6943. (org-back-to-heading t)
  6944. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6945. after-change-functions))
  6946. (level (save-match-data (funcall outline-level)))
  6947. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6948. (diff (abs (- level (length down-head) -1))))
  6949. (replace-match down-head nil t)
  6950. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6951. (when org-adapt-indentation (org-fixup-indentation diff))
  6952. (run-hooks 'org-after-demote-entry-hook))))
  6953. (defun org-cycle-level ()
  6954. "Cycle the level of an empty headline through possible states.
  6955. This goes first to child, then to parent, level, then up the hierarchy.
  6956. After top level, it switches back to sibling level."
  6957. (interactive)
  6958. (let ((org-adapt-indentation nil))
  6959. (when (org-point-at-end-of-empty-headline)
  6960. (setq this-command 'org-cycle-level) ; Only needed for caching
  6961. (let ((cur-level (org-current-level))
  6962. (prev-level (org-get-previous-line-level)))
  6963. (cond
  6964. ;; If first headline in file, promote to top-level.
  6965. ((= prev-level 0)
  6966. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6967. do (org-do-promote)))
  6968. ;; If same level as prev, demote one.
  6969. ((= prev-level cur-level)
  6970. (org-do-demote))
  6971. ;; If parent is top-level, promote to top level if not already.
  6972. ((= prev-level 1)
  6973. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6974. do (org-do-promote)))
  6975. ;; If top-level, return to prev-level.
  6976. ((= cur-level 1)
  6977. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6978. do (org-do-demote)))
  6979. ;; If less than prev-level, promote one.
  6980. ((< cur-level prev-level)
  6981. (org-do-promote))
  6982. ;; If deeper than prev-level, promote until higher than
  6983. ;; prev-level.
  6984. ((> cur-level prev-level)
  6985. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6986. do (org-do-promote))))
  6987. t))))
  6988. (defun org-map-tree (fun)
  6989. "Call FUN for every heading underneath the current one."
  6990. (org-back-to-heading t)
  6991. (let ((level (funcall outline-level)))
  6992. (save-excursion
  6993. (funcall fun)
  6994. (while (and (progn
  6995. (outline-next-heading)
  6996. (> (funcall outline-level) level))
  6997. (not (eobp)))
  6998. (funcall fun)))))
  6999. (defun org-map-region (fun beg end)
  7000. "Call FUN for every heading between BEG and END."
  7001. (let ((org-ignore-region t))
  7002. (save-excursion
  7003. (setq end (copy-marker end))
  7004. (goto-char beg)
  7005. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7006. (< (point) end))
  7007. (funcall fun))
  7008. (while (and (progn
  7009. (outline-next-heading)
  7010. (< (point) end))
  7011. (not (eobp)))
  7012. (funcall fun)))))
  7013. (defun org-fixup-indentation (diff)
  7014. "Change the indentation in the current entry by DIFF.
  7015. DIFF is an integer. Indentation is done according to the
  7016. following rules:
  7017. - Planning information and property drawers are always indented
  7018. according to the new level of the headline;
  7019. - Footnote definitions and their contents are ignored;
  7020. - Inlinetasks' boundaries are not shifted;
  7021. - Empty lines are ignored;
  7022. - Other lines' indentation are shifted by DIFF columns, unless
  7023. it would introduce a structural change in the document, in
  7024. which case no shifting is done at all.
  7025. Assume point is at a heading or an inlinetask beginning."
  7026. (org-with-wide-buffer
  7027. (narrow-to-region (line-beginning-position)
  7028. (save-excursion
  7029. (if (org-with-limited-levels (org-at-heading-p))
  7030. (org-with-limited-levels (outline-next-heading))
  7031. (org-inlinetask-goto-end))
  7032. (point)))
  7033. (forward-line)
  7034. ;; Indent properly planning info and property drawer.
  7035. (when (looking-at-p org-planning-line-re)
  7036. (org-indent-line)
  7037. (forward-line))
  7038. (when (looking-at org-property-drawer-re)
  7039. (goto-char (match-end 0))
  7040. (forward-line)
  7041. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7042. (catch 'no-shift
  7043. (when (zerop diff) (throw 'no-shift nil))
  7044. ;; If DIFF is negative, first check if a shift is possible at all
  7045. ;; (e.g., it doesn't break structure). This can only happen if
  7046. ;; some contents are not properly indented.
  7047. (let ((case-fold-search t))
  7048. (when (< diff 0)
  7049. (let ((diff (- diff))
  7050. (forbidden-re (concat org-outline-regexp
  7051. "\\|"
  7052. (substring org-footnote-definition-re 1))))
  7053. (save-excursion
  7054. (while (not (eobp))
  7055. (cond
  7056. ((looking-at-p "[ \t]*$") (forward-line))
  7057. ((and (looking-at-p org-footnote-definition-re)
  7058. (let ((e (org-element-at-point)))
  7059. (and (eq (org-element-type e) 'footnote-definition)
  7060. (goto-char (org-element-property :end e))))))
  7061. ((looking-at-p org-outline-regexp) (forward-line))
  7062. ;; Give up if shifting would move before column 0 or
  7063. ;; if it would introduce a headline or a footnote
  7064. ;; definition.
  7065. (t
  7066. (skip-chars-forward " \t")
  7067. (let ((ind (current-column)))
  7068. (when (or (< ind diff)
  7069. (and (= ind diff) (looking-at-p forbidden-re)))
  7070. (throw 'no-shift nil)))
  7071. ;; Ignore contents of example blocks and source
  7072. ;; blocks if their indentation is meant to be
  7073. ;; preserved. Jump to block's closing line.
  7074. (beginning-of-line)
  7075. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7076. (let ((e (org-element-at-point)))
  7077. (and (memq (org-element-type e)
  7078. '(example-block src-block))
  7079. (or org-src-preserve-indentation
  7080. (org-element-property :preserve-indent e))
  7081. (goto-char (org-element-property :end e))
  7082. (progn (skip-chars-backward " \r\t\n")
  7083. (beginning-of-line)
  7084. t))))
  7085. (forward-line))))))))
  7086. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7087. ;; by DIFF. Also skip contents of source or example blocks
  7088. ;; when indentation is meant to be preserved.
  7089. (while (not (eobp))
  7090. (cond
  7091. ((and (looking-at-p org-footnote-definition-re)
  7092. (let ((e (org-element-at-point)))
  7093. (and (eq (org-element-type e) 'footnote-definition)
  7094. (goto-char (org-element-property :end e))))))
  7095. ((looking-at-p org-outline-regexp) (forward-line))
  7096. ((looking-at-p "[ \t]*$") (forward-line))
  7097. (t
  7098. (indent-line-to (+ (org-get-indentation) diff))
  7099. (beginning-of-line)
  7100. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7101. (let ((e (org-element-at-point)))
  7102. (and (memq (org-element-type e)
  7103. '(example-block src-block))
  7104. (or org-src-preserve-indentation
  7105. (org-element-property :preserve-indent e))
  7106. (goto-char (org-element-property :end e))
  7107. (progn (skip-chars-backward " \r\t\n")
  7108. (beginning-of-line)
  7109. t))))
  7110. (forward-line)))))))))
  7111. (defun org-convert-to-odd-levels ()
  7112. "Convert an Org file with all levels allowed to one with odd levels.
  7113. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7114. level 5 etc."
  7115. (interactive)
  7116. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7117. (let ((outline-level 'org-outline-level)
  7118. (org-odd-levels-only nil) n)
  7119. (save-excursion
  7120. (goto-char (point-min))
  7121. (while (re-search-forward "^\\*\\*+ " nil t)
  7122. (setq n (- (length (match-string 0)) 2))
  7123. (while (>= (setq n (1- n)) 0)
  7124. (org-demote))
  7125. (end-of-line 1))))))
  7126. (defun org-convert-to-oddeven-levels ()
  7127. "Convert an Org file with only odd levels to one with odd/even levels.
  7128. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7129. file contains a section with an even level, conversion would
  7130. destroy the structure of the file. An error is signaled in this
  7131. case."
  7132. (interactive)
  7133. (goto-char (point-min))
  7134. ;; First check if there are no even levels
  7135. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7136. (org-show-set-visibility 'canonical)
  7137. (error "Not all levels are odd in this file. Conversion not possible"))
  7138. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7139. (let ((outline-regexp org-outline-regexp)
  7140. (outline-level 'org-outline-level)
  7141. (org-odd-levels-only nil) n)
  7142. (save-excursion
  7143. (goto-char (point-min))
  7144. (while (re-search-forward "^\\*\\*+ " nil t)
  7145. (setq n (/ (1- (length (match-string 0))) 2))
  7146. (while (>= (setq n (1- n)) 0)
  7147. (org-promote))
  7148. (end-of-line 1))))))
  7149. (defun org-tr-level (n)
  7150. "Make N odd if required."
  7151. (if org-odd-levels-only (1+ (/ n 2)) n))
  7152. ;;; Vertical tree motion, cutting and pasting of subtrees
  7153. (defun org-move-subtree-up (&optional arg)
  7154. "Move the current subtree up past ARG headlines of the same level."
  7155. (interactive "p")
  7156. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7157. (defun org-move-subtree-down (&optional arg)
  7158. "Move the current subtree down past ARG headlines of the same level."
  7159. (interactive "p")
  7160. (setq arg (prefix-numeric-value arg))
  7161. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7162. 'org-get-last-sibling))
  7163. (ins-point (make-marker))
  7164. (cnt (abs arg))
  7165. (col (current-column))
  7166. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7167. ;; Select the tree
  7168. (org-back-to-heading)
  7169. (setq beg0 (point))
  7170. (save-excursion
  7171. (setq ne-beg (org-back-over-empty-lines))
  7172. (setq beg (point)))
  7173. (save-match-data
  7174. (save-excursion (outline-end-of-heading)
  7175. (setq folded (org-invisible-p)))
  7176. (progn (org-end-of-subtree nil t)
  7177. (unless (eobp) (backward-char))))
  7178. (outline-next-heading)
  7179. (setq ne-end (org-back-over-empty-lines))
  7180. (setq end (point))
  7181. (goto-char beg0)
  7182. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7183. ;; include less whitespace
  7184. (save-excursion
  7185. (goto-char beg)
  7186. (forward-line (- ne-beg ne-end))
  7187. (setq beg (point))))
  7188. ;; Find insertion point, with error handling
  7189. (while (> cnt 0)
  7190. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7191. (progn (goto-char beg0)
  7192. (user-error "Cannot move past superior level or buffer limit")))
  7193. (setq cnt (1- cnt)))
  7194. (when (> arg 0)
  7195. ;; Moving forward - still need to move over subtree
  7196. (org-end-of-subtree t t)
  7197. (save-excursion
  7198. (org-back-over-empty-lines)
  7199. (or (bolp) (newline))))
  7200. (setq ne-ins (org-back-over-empty-lines))
  7201. (move-marker ins-point (point))
  7202. (setq txt (buffer-substring beg end))
  7203. (org-save-markers-in-region beg end)
  7204. (delete-region beg end)
  7205. (org-remove-empty-overlays-at beg)
  7206. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7207. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7208. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7209. (let ((bbb (point)))
  7210. (insert-before-markers txt)
  7211. (org-reinstall-markers-in-region bbb)
  7212. (move-marker ins-point bbb))
  7213. (or (bolp) (insert "\n"))
  7214. (setq ins-end (point))
  7215. (goto-char ins-point)
  7216. (org-skip-whitespace)
  7217. (when (and (< arg 0)
  7218. (org-first-sibling-p)
  7219. (> ne-ins ne-beg))
  7220. ;; Move whitespace back to beginning
  7221. (save-excursion
  7222. (goto-char ins-end)
  7223. (let ((kill-whole-line t))
  7224. (kill-line (- ne-ins ne-beg)) (point)))
  7225. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7226. (move-marker ins-point nil)
  7227. (if folded
  7228. (outline-hide-subtree)
  7229. (org-show-entry)
  7230. (org-show-children)
  7231. (org-cycle-hide-drawers 'children))
  7232. (org-clean-visibility-after-subtree-move)
  7233. ;; move back to the initial column we were at
  7234. (move-to-column col)))
  7235. (defvar org-subtree-clip ""
  7236. "Clipboard for cut and paste of subtrees.
  7237. This is actually only a copy of the kill, because we use the normal kill
  7238. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7239. (defvar org-subtree-clip-folded nil
  7240. "Was the last copied subtree folded?
  7241. This is used to fold the tree back after pasting.")
  7242. (defun org-cut-subtree (&optional n)
  7243. "Cut the current subtree into the clipboard.
  7244. With prefix arg N, cut this many sequential subtrees.
  7245. This is a short-hand for marking the subtree and then cutting it."
  7246. (interactive "p")
  7247. (org-copy-subtree n 'cut))
  7248. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7249. "Copy the current subtree it in the clipboard.
  7250. With prefix arg N, copy this many sequential subtrees.
  7251. This is a short-hand for marking the subtree and then copying it.
  7252. If CUT is non-nil, actually cut the subtree.
  7253. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7254. of some markers in the region, even if CUT is non-nil. This is
  7255. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7256. (interactive "p")
  7257. (let (beg end folded (beg0 (point)))
  7258. (if (called-interactively-p 'any)
  7259. (org-back-to-heading nil) ; take what looks like a subtree
  7260. (org-back-to-heading t)) ; take what is really there
  7261. (setq beg (point))
  7262. (skip-chars-forward " \t\r\n")
  7263. (save-match-data
  7264. (if nosubtrees
  7265. (outline-next-heading)
  7266. (save-excursion (outline-end-of-heading)
  7267. (setq folded (org-invisible-p)))
  7268. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7269. (org-end-of-subtree t t)))
  7270. ;; Include the end of an inlinetask
  7271. (when (and (featurep 'org-inlinetask)
  7272. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7273. "END[ \t]*$")))
  7274. (end-of-line))
  7275. (setq end (point))
  7276. (goto-char beg0)
  7277. (when (> end beg)
  7278. (setq org-subtree-clip-folded folded)
  7279. (when (or cut force-store-markers)
  7280. (org-save-markers-in-region beg end))
  7281. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7282. (setq org-subtree-clip (current-kill 0))
  7283. (message "%s: Subtree(s) with %d characters"
  7284. (if cut "Cut" "Copied")
  7285. (length org-subtree-clip)))))
  7286. (defun org-paste-subtree (&optional level tree for-yank remove)
  7287. "Paste the clipboard as a subtree, with modification of headline level.
  7288. The entire subtree is promoted or demoted in order to match a new headline
  7289. level.
  7290. If the cursor is at the beginning of a headline, the same level as
  7291. that headline is used to paste the tree.
  7292. If not, the new level is derived from the *visible* headings
  7293. before and after the insertion point, and taken to be the inferior headline
  7294. level of the two. So if the previous visible heading is level 3 and the
  7295. next is level 4 (or vice versa), level 4 will be used for insertion.
  7296. This makes sure that the subtree remains an independent subtree and does
  7297. not swallow low level entries.
  7298. You can also force a different level, either by using a numeric prefix
  7299. argument, or by inserting the heading marker by hand. For example, if the
  7300. cursor is after \"*****\", then the tree will be shifted to level 5.
  7301. If optional TREE is given, use this text instead of the kill ring.
  7302. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7303. move back over whitespace before inserting, and move point to the end of
  7304. the inserted text when done.
  7305. When REMOVE is non-nil, remove the subtree from the clipboard."
  7306. (interactive "P")
  7307. (setq tree (or tree (and kill-ring (current-kill 0))))
  7308. (unless (org-kill-is-subtree-p tree)
  7309. (user-error "%s"
  7310. (substitute-command-keys
  7311. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7312. (org-with-limited-levels
  7313. (let* ((visp (not (org-invisible-p)))
  7314. (txt tree)
  7315. (^re_ "\\(\\*+\\)[ \t]*")
  7316. (old-level (if (string-match org-outline-regexp-bol txt)
  7317. (- (match-end 0) (match-beginning 0) 1)
  7318. -1))
  7319. (force-level (cond (level (prefix-numeric-value level))
  7320. ((and (looking-at "[ \t]*$")
  7321. (string-match
  7322. "^\\*+$" (buffer-substring
  7323. (point-at-bol) (point))))
  7324. (- (match-end 0) (match-beginning 0)))
  7325. ((and (bolp)
  7326. (looking-at org-outline-regexp))
  7327. (- (match-end 0) (point) 1))))
  7328. (previous-level (save-excursion
  7329. (condition-case nil
  7330. (progn
  7331. (outline-previous-visible-heading 1)
  7332. (if (looking-at ^re_)
  7333. (- (match-end 0) (match-beginning 0) 1)
  7334. 1))
  7335. (error 1))))
  7336. (next-level (save-excursion
  7337. (condition-case nil
  7338. (progn
  7339. (or (looking-at org-outline-regexp)
  7340. (outline-next-visible-heading 1))
  7341. (if (looking-at ^re_)
  7342. (- (match-end 0) (match-beginning 0) 1)
  7343. 1))
  7344. (error 1))))
  7345. (new-level (or force-level (max previous-level next-level)))
  7346. (shift (if (or (= old-level -1)
  7347. (= new-level -1)
  7348. (= old-level new-level))
  7349. 0
  7350. (- new-level old-level)))
  7351. (delta (if (> shift 0) -1 1))
  7352. (func (if (> shift 0) 'org-demote 'org-promote))
  7353. (org-odd-levels-only nil)
  7354. beg end newend)
  7355. ;; Remove the forced level indicator
  7356. (when force-level
  7357. (delete-region (point-at-bol) (point)))
  7358. ;; Paste
  7359. (beginning-of-line (if (bolp) 1 2))
  7360. (setq beg (point))
  7361. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7362. (insert-before-markers txt)
  7363. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7364. (setq newend (point))
  7365. (org-reinstall-markers-in-region beg)
  7366. (setq end (point))
  7367. (goto-char beg)
  7368. (skip-chars-forward " \t\n\r")
  7369. (setq beg (point))
  7370. (when (and (org-invisible-p) visp)
  7371. (save-excursion (outline-show-heading)))
  7372. ;; Shift if necessary
  7373. (unless (= shift 0)
  7374. (save-restriction
  7375. (narrow-to-region beg end)
  7376. (while (not (= shift 0))
  7377. (org-map-region func (point-min) (point-max))
  7378. (setq shift (+ delta shift)))
  7379. (goto-char (point-min))
  7380. (setq newend (point-max))))
  7381. (when (or (called-interactively-p 'interactive) for-yank)
  7382. (message "Clipboard pasted as level %d subtree" new-level))
  7383. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7384. kill-ring
  7385. (eq org-subtree-clip (current-kill 0))
  7386. org-subtree-clip-folded)
  7387. ;; The tree was folded before it was killed/copied
  7388. (outline-hide-subtree))
  7389. (and for-yank (goto-char newend))
  7390. (and remove (setq kill-ring (cdr kill-ring))))))
  7391. (defun org-kill-is-subtree-p (&optional txt)
  7392. "Check if the current kill is an outline subtree, or a set of trees.
  7393. Returns nil if kill does not start with a headline, or if the first
  7394. headline level is not the largest headline level in the tree.
  7395. So this will actually accept several entries of equal levels as well,
  7396. which is OK for `org-paste-subtree'.
  7397. If optional TXT is given, check this string instead of the current kill."
  7398. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7399. (re (org-get-limited-outline-regexp))
  7400. (^re (concat "^" re))
  7401. (start-level (and kill
  7402. (string-match
  7403. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7404. kill)
  7405. (- (match-end 2) (match-beginning 2) 1)))
  7406. (start (1+ (or (match-beginning 2) -1))))
  7407. (if (not start-level)
  7408. (progn
  7409. nil) ;; does not even start with a heading
  7410. (catch 'exit
  7411. (while (setq start (string-match ^re kill (1+ start)))
  7412. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7413. (throw 'exit nil)))
  7414. t))))
  7415. (defvar org-markers-to-move nil
  7416. "Markers that should be moved with a cut-and-paste operation.
  7417. Those markers are stored together with their positions relative to
  7418. the start of the region.")
  7419. (defun org-save-markers-in-region (beg end)
  7420. "Check markers in region.
  7421. If these markers are between BEG and END, record their position relative
  7422. to BEG, so that after moving the block of text, we can put the markers back
  7423. into place.
  7424. This function gets called just before an entry or tree gets cut from the
  7425. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7426. called immediately, to move the markers with the entries."
  7427. (setq org-markers-to-move nil)
  7428. (when (featurep 'org-clock)
  7429. (org-clock-save-markers-for-cut-and-paste beg end))
  7430. (when (featurep 'org-agenda)
  7431. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7432. (defun org-check-and-save-marker (marker beg end)
  7433. "Check if MARKER is between BEG and END.
  7434. If yes, remember the marker and the distance to BEG."
  7435. (when (and (marker-buffer marker)
  7436. (equal (marker-buffer marker) (current-buffer))
  7437. (>= marker beg) (< marker end))
  7438. (push (cons marker (- marker beg)) org-markers-to-move)))
  7439. (defun org-reinstall-markers-in-region (beg)
  7440. "Move all remembered markers to their position relative to BEG."
  7441. (dolist (x org-markers-to-move)
  7442. (move-marker (car x) (+ beg (cdr x))))
  7443. (setq org-markers-to-move nil))
  7444. (defun org-narrow-to-subtree ()
  7445. "Narrow buffer to the current subtree."
  7446. (interactive)
  7447. (save-excursion
  7448. (save-match-data
  7449. (org-with-limited-levels
  7450. (narrow-to-region
  7451. (progn (org-back-to-heading t) (point))
  7452. (progn (org-end-of-subtree t t)
  7453. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7454. (point)))))))
  7455. (defun org-narrow-to-block ()
  7456. "Narrow buffer to the current block."
  7457. (interactive)
  7458. (let* ((case-fold-search t)
  7459. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7460. "^[ \t]*#\\+end_.*")))
  7461. (if blockp
  7462. (narrow-to-region (car blockp) (cdr blockp))
  7463. (user-error "Not in a block"))))
  7464. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7465. "Clone the task (subtree) at point N times.
  7466. The clones will be inserted as siblings.
  7467. In interactive use, the user will be prompted for the number of
  7468. clones to be produced. If the entry has a timestamp, the user
  7469. will also be prompted for a time shift, which may be a repeater
  7470. as used in time stamps, for example `+3d'. To disable this,
  7471. you can call the function with a universal prefix argument.
  7472. When a valid repeater is given and the entry contains any time
  7473. stamps, the clones will become a sequence in time, with time
  7474. stamps in the subtree shifted for each clone produced. If SHIFT
  7475. is nil or the empty string, time stamps will be left alone. The
  7476. ID property of the original subtree is removed.
  7477. In each clone, all the CLOCK entries will be removed. This
  7478. prevents Org from considering that the clocked times overlap.
  7479. If the original subtree did contain time stamps with a repeater,
  7480. the following will happen:
  7481. - the repeater will be removed in each clone
  7482. - an additional clone will be produced, with the current, unshifted
  7483. date(s) in the entry.
  7484. - the original entry will be placed *after* all the clones, with
  7485. repeater intact.
  7486. - the start days in the repeater in the original entry will be shifted
  7487. to past the last clone.
  7488. In this way you can spell out a number of instances of a repeating task,
  7489. and still retain the repeater to cover future instances of the task.
  7490. As described above, N+1 clones are produced when the original
  7491. subtree has a repeater. Setting N to 0, then, can be used to
  7492. remove the repeater from a subtree and create a shifted clone
  7493. with the original repeater."
  7494. (interactive "nNumber of clones to produce: ")
  7495. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7496. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7497. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7498. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7499. (shift
  7500. (or shift
  7501. (if (and (not (equal current-prefix-arg '(4)))
  7502. (save-excursion
  7503. (goto-char beg)
  7504. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7505. (read-from-minibuffer
  7506. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7507. ""))) ;No time shift
  7508. (doshift
  7509. (and (org-string-nw-p shift)
  7510. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7511. shift)
  7512. (user-error "Invalid shift specification %s" shift)))))
  7513. (goto-char end-of-tree)
  7514. (unless (bolp) (insert "\n"))
  7515. (let* ((end (point))
  7516. (template (buffer-substring beg end))
  7517. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7518. (shift-what (pcase (and doshift (match-string 2 shift))
  7519. (`nil nil)
  7520. ("d" 'day)
  7521. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7522. ("m" 'month)
  7523. ("y" 'year)
  7524. (_ (error "Unsupported time unit"))))
  7525. (nmin 1)
  7526. (nmax n)
  7527. (n-no-remove -1)
  7528. (idprop (org-entry-get nil "ID")))
  7529. (when (and doshift
  7530. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7531. template))
  7532. (delete-region beg end)
  7533. (setq end beg)
  7534. (setq nmin 0)
  7535. (setq nmax (1+ nmax))
  7536. (setq n-no-remove nmax))
  7537. (goto-char end)
  7538. (cl-loop for n from nmin to nmax do
  7539. (insert
  7540. ;; Prepare clone.
  7541. (with-temp-buffer
  7542. (insert template)
  7543. (org-mode)
  7544. (goto-char (point-min))
  7545. (org-show-subtree)
  7546. (and idprop (if org-clone-delete-id
  7547. (org-entry-delete nil "ID")
  7548. (org-id-get-create t)))
  7549. (unless (= n 0)
  7550. (while (re-search-forward org-clock-line-re nil t)
  7551. (delete-region (line-beginning-position)
  7552. (line-beginning-position 2)))
  7553. (goto-char (point-min))
  7554. (while (re-search-forward org-drawer-regexp nil t)
  7555. (org-remove-empty-drawer-at (point))))
  7556. (goto-char (point-min))
  7557. (when doshift
  7558. (while (re-search-forward org-ts-regexp-both nil t)
  7559. (org-timestamp-change (* n shift-n) shift-what))
  7560. (unless (= n n-no-remove)
  7561. (goto-char (point-min))
  7562. (while (re-search-forward org-ts-regexp nil t)
  7563. (save-excursion
  7564. (goto-char (match-beginning 0))
  7565. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7566. (delete-region (match-beginning 1) (match-end 1)))))))
  7567. (buffer-string)))))
  7568. (goto-char beg)))
  7569. ;;; Outline Sorting
  7570. (defun org-sort (&optional with-case)
  7571. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7572. Optional argument WITH-CASE means sort case-sensitively."
  7573. (interactive "P")
  7574. (org-call-with-arg
  7575. (cond ((org-at-table-p) #'org-table-sort-lines)
  7576. ((org-at-item-p) #'org-sort-list)
  7577. (t #'org-sort-entries))
  7578. with-case))
  7579. (defun org-sort-remove-invisible (s)
  7580. "Remove invisible part of links and emphasis markers from string S."
  7581. (remove-text-properties 0 (length s) org-rm-props s)
  7582. (replace-regexp-in-string
  7583. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7584. (replace-regexp-in-string
  7585. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7586. (org-link-display-format s)
  7587. t t) t t))
  7588. (defvar org-priority-regexp) ; defined later in the file
  7589. (defvar org-after-sorting-entries-or-items-hook nil
  7590. "Hook that is run after a bunch of entries or items have been sorted.
  7591. When children are sorted, the cursor is in the parent line when this
  7592. hook gets called. When a region or a plain list is sorted, the cursor
  7593. will be in the first entry of the sorted region/list.")
  7594. (defun org-sort-entries
  7595. (&optional with-case sorting-type getkey-func compare-func property
  7596. interactive?)
  7597. "Sort entries on a certain level of an outline tree.
  7598. If there is an active region, the entries in the region are sorted.
  7599. Else, if the cursor is before the first entry, sort the top-level items.
  7600. Else, the children of the entry at point are sorted.
  7601. Sorting can be alphabetically, numerically, by date/time as given by
  7602. a time stamp, by a property, by priority order, or by a custom function.
  7603. The command prompts for the sorting type unless it has been given to the
  7604. function through the SORTING-TYPE argument, which needs to be a character,
  7605. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7606. the precise meaning of each character:
  7607. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7608. c By creation time, which is assumed to be the first inactive time stamp
  7609. at the beginning of a line.
  7610. d By deadline date/time.
  7611. k By clocking time.
  7612. n Numerically, by converting the beginning of the entry/item to a number.
  7613. o By order of TODO keywords.
  7614. p By priority according to the cookie.
  7615. r By the value of a property.
  7616. s By scheduled date/time.
  7617. t By date/time, either the first active time stamp in the entry, or, if
  7618. none exist, by the first inactive one.
  7619. Capital letters will reverse the sort order.
  7620. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7621. called with point at the beginning of the record. It must return a
  7622. value that is compatible with COMPARE-FUNC, the function used to
  7623. compare entries.
  7624. Comparing entries ignores case by default. However, with an optional argument
  7625. WITH-CASE, the sorting considers case as well.
  7626. Sorting is done against the visible part of the headlines, it ignores hidden
  7627. links.
  7628. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7629. A non-nil value for INTERACTIVE? is used to signal that this
  7630. function is being called interactively."
  7631. (interactive (list current-prefix-arg nil nil nil nil t))
  7632. (let ((case-func (if with-case 'identity 'downcase))
  7633. start beg end stars re re2
  7634. txt what tmp)
  7635. ;; Find beginning and end of region to sort
  7636. (cond
  7637. ((org-region-active-p)
  7638. ;; we will sort the region
  7639. (setq end (region-end)
  7640. what "region")
  7641. (goto-char (region-beginning))
  7642. (unless (org-at-heading-p) (outline-next-heading))
  7643. (setq start (point)))
  7644. ((or (org-at-heading-p)
  7645. (ignore-errors (progn (org-back-to-heading) t)))
  7646. ;; we will sort the children of the current headline
  7647. (org-back-to-heading)
  7648. (setq start (point)
  7649. end (progn (org-end-of-subtree t t)
  7650. (or (bolp) (insert "\n"))
  7651. (when (>= (org-back-over-empty-lines) 1)
  7652. (forward-line 1))
  7653. (point))
  7654. what "children")
  7655. (goto-char start)
  7656. (outline-show-subtree)
  7657. (outline-next-heading))
  7658. (t
  7659. ;; we will sort the top-level entries in this file
  7660. (goto-char (point-min))
  7661. (or (org-at-heading-p) (outline-next-heading))
  7662. (setq start (point))
  7663. (goto-char (point-max))
  7664. (beginning-of-line 1)
  7665. (when (looking-at ".*?\\S-")
  7666. ;; File ends in a non-white line
  7667. (end-of-line 1)
  7668. (insert "\n"))
  7669. (setq end (point-max))
  7670. (setq what "top-level")
  7671. (goto-char start)
  7672. (outline-show-all)))
  7673. (setq beg (point))
  7674. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7675. (looking-at "\\(\\*+\\)")
  7676. (setq stars (match-string 1)
  7677. re (concat "^" (regexp-quote stars) " +")
  7678. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7679. txt (buffer-substring beg end))
  7680. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7681. (when (and (not (equal stars "*")) (string-match re2 txt))
  7682. (user-error "Region to sort contains a level above the first entry"))
  7683. (unless sorting-type
  7684. (message
  7685. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7686. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7687. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7688. what)
  7689. (setq sorting-type (read-char-exclusive)))
  7690. (unless getkey-func
  7691. (and (= (downcase sorting-type) ?f)
  7692. (setq getkey-func
  7693. (or (and interactive?
  7694. (org-read-function
  7695. "Function for extracting keys: "))
  7696. (error "Missing key extractor")))))
  7697. (and (= (downcase sorting-type) ?r)
  7698. (not property)
  7699. (setq property
  7700. (completing-read "Property: "
  7701. (mapcar #'list (org-buffer-property-keys t))
  7702. nil t)))
  7703. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7704. (message "Sorting entries...")
  7705. (save-restriction
  7706. (narrow-to-region start end)
  7707. (let ((restore-clock?
  7708. ;; The clock marker is lost when using `sort-subr'; mark
  7709. ;; the clock with temporary `:org-clock-marker-backup'
  7710. ;; text property.
  7711. (when (and (eq (org-clock-is-active) (current-buffer))
  7712. (<= start (marker-position org-clock-marker))
  7713. (>= end (marker-position org-clock-marker)))
  7714. (org-with-silent-modifications
  7715. (put-text-property (1- org-clock-marker) org-clock-marker
  7716. :org-clock-marker-backup t))
  7717. t))
  7718. (dcst (downcase sorting-type))
  7719. (case-fold-search nil)
  7720. (now (current-time)))
  7721. (sort-subr
  7722. (/= dcst sorting-type)
  7723. ;; This function moves to the beginning character of the "record" to
  7724. ;; be sorted.
  7725. (lambda nil
  7726. (if (re-search-forward re nil t)
  7727. (goto-char (match-beginning 0))
  7728. (goto-char (point-max))))
  7729. ;; This function moves to the last character of the "record" being
  7730. ;; sorted.
  7731. (lambda nil
  7732. (save-match-data
  7733. (condition-case nil
  7734. (outline-forward-same-level 1)
  7735. (error
  7736. (goto-char (point-max))))))
  7737. ;; This function returns the value that gets sorted against.
  7738. (lambda nil
  7739. (cond
  7740. ((= dcst ?n)
  7741. (if (looking-at org-complex-heading-regexp)
  7742. (string-to-number (org-sort-remove-invisible (match-string 4)))
  7743. nil))
  7744. ((= dcst ?a)
  7745. (if (looking-at org-complex-heading-regexp)
  7746. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  7747. nil))
  7748. ((= dcst ?k)
  7749. (or (get-text-property (point) :org-clock-minutes) 0))
  7750. ((= dcst ?t)
  7751. (let ((end (save-excursion (outline-next-heading) (point))))
  7752. (if (or (re-search-forward org-ts-regexp end t)
  7753. (re-search-forward org-ts-regexp-both end t))
  7754. (org-time-string-to-seconds (match-string 0))
  7755. (float-time now))))
  7756. ((= dcst ?c)
  7757. (let ((end (save-excursion (outline-next-heading) (point))))
  7758. (if (re-search-forward
  7759. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7760. end t)
  7761. (org-time-string-to-seconds (match-string 0))
  7762. (float-time now))))
  7763. ((= dcst ?s)
  7764. (let ((end (save-excursion (outline-next-heading) (point))))
  7765. (if (re-search-forward org-scheduled-time-regexp end t)
  7766. (org-time-string-to-seconds (match-string 1))
  7767. (float-time now))))
  7768. ((= dcst ?d)
  7769. (let ((end (save-excursion (outline-next-heading) (point))))
  7770. (if (re-search-forward org-deadline-time-regexp end t)
  7771. (org-time-string-to-seconds (match-string 1))
  7772. (float-time now))))
  7773. ((= dcst ?p)
  7774. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7775. (string-to-char (match-string 2))
  7776. org-default-priority))
  7777. ((= dcst ?r)
  7778. (or (org-entry-get nil property) ""))
  7779. ((= dcst ?o)
  7780. (when (looking-at org-complex-heading-regexp)
  7781. (let* ((m (match-string 2))
  7782. (s (if (member m org-done-keywords) '- '+)))
  7783. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7784. ((= dcst ?f)
  7785. (if getkey-func
  7786. (progn
  7787. (setq tmp (funcall getkey-func))
  7788. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7789. tmp)
  7790. (error "Invalid key function `%s'" getkey-func)))
  7791. (t (error "Invalid sorting type `%c'" sorting-type))))
  7792. nil
  7793. (cond
  7794. ((= dcst ?a) 'string<)
  7795. ((= dcst ?f)
  7796. (or compare-func
  7797. (and interactive?
  7798. (org-read-function
  7799. (concat "Function for comparing keys "
  7800. "(empty for default `sort-subr' predicate): ")
  7801. 'allow-empty))))
  7802. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  7803. (when restore-clock?
  7804. (move-marker org-clock-marker
  7805. (1+ (next-single-property-change
  7806. start :org-clock-marker-backup)))
  7807. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7808. '(:org-clock-marker-backup t)))))
  7809. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7810. (message "Sorting entries...done")))
  7811. ;;; The orgstruct minor mode
  7812. ;; Define a minor mode which can be used in other modes in order to
  7813. ;; integrate the Org mode structure editing commands.
  7814. ;; This is really a hack, because the Org mode structure commands use
  7815. ;; keys which normally belong to the major mode. Here is how it
  7816. ;; works: The minor mode defines all the keys necessary to operate the
  7817. ;; structure commands, but wraps the commands into a function which
  7818. ;; tests if the cursor is currently at a headline or a plain list
  7819. ;; item. If that is the case, the structure command is used,
  7820. ;; temporarily setting many Org mode variables like regular
  7821. ;; expressions for filling etc. However, when any of those keys is
  7822. ;; used at a different location, function uses `key-binding' to look
  7823. ;; up if the key has an associated command in another currently active
  7824. ;; keymap (minor modes, major mode, global), and executes that
  7825. ;; command. There might be problems if any of the keys is otherwise
  7826. ;; used as a prefix key.
  7827. (defcustom orgstruct-heading-prefix-regexp ""
  7828. "Regexp that matches the custom prefix of Org headlines in
  7829. orgstruct(++)-mode."
  7830. :group 'org
  7831. :version "26.1"
  7832. :package-version '(Org . "8.3")
  7833. :type 'regexp)
  7834. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  7835. (defcustom orgstruct-setup-hook nil
  7836. "Hook run after orgstruct-mode-map is filled."
  7837. :group 'org
  7838. :version "24.4"
  7839. :package-version '(Org . "8.0")
  7840. :type 'hook)
  7841. (defvar orgstruct-initialized nil)
  7842. (defvar org-local-vars nil
  7843. "List of local variables, for use by `orgstruct-mode'.")
  7844. ;;;###autoload
  7845. (define-minor-mode orgstruct-mode
  7846. "Toggle the minor mode `orgstruct-mode'.
  7847. This mode is for using Org mode structure commands in other
  7848. modes. The following keys behave as if Org mode were active, if
  7849. the cursor is on a headline, or on a plain list item (both as
  7850. defined by Org mode)."
  7851. nil " OrgStruct" (make-sparse-keymap)
  7852. (funcall (if orgstruct-mode
  7853. 'add-to-invisibility-spec
  7854. 'remove-from-invisibility-spec)
  7855. '(outline . t))
  7856. (when orgstruct-mode
  7857. (org-load-modules-maybe)
  7858. (unless orgstruct-initialized
  7859. (orgstruct-setup)
  7860. (setq orgstruct-initialized t))))
  7861. ;;;###autoload
  7862. (defun turn-on-orgstruct ()
  7863. "Unconditionally turn on `orgstruct-mode'."
  7864. (orgstruct-mode 1))
  7865. (defvar-local orgstruct-is-++ nil
  7866. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  7867. (defvar-local org-fb-vars nil)
  7868. (defun orgstruct++-mode (&optional arg)
  7869. "Toggle `orgstruct-mode', the enhanced version of it.
  7870. In addition to setting orgstruct-mode, this also exports all
  7871. indentation and autofilling variables from Org mode into the
  7872. buffer. It will also recognize item context in multiline items."
  7873. (interactive "P")
  7874. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  7875. (if (< arg 1)
  7876. (progn (orgstruct-mode -1)
  7877. (dolist (v org-fb-vars)
  7878. (set (make-local-variable (car v))
  7879. (if (eq (car-safe (cadr v)) 'quote)
  7880. (cl-cadadr v)
  7881. (nth 1 v)))))
  7882. (orgstruct-mode 1)
  7883. (setq org-fb-vars nil)
  7884. (unless org-local-vars
  7885. (setq org-local-vars (org-get-local-variables)))
  7886. (let (var val)
  7887. (dolist (x org-local-vars)
  7888. (when (string-match
  7889. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  7890. \\|fill-prefix\\|indent-\\)"
  7891. (symbol-name (car x)))
  7892. (setq var (car x) val (nth 1 x))
  7893. (push (list var `(quote ,(eval var))) org-fb-vars)
  7894. (set (make-local-variable var)
  7895. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  7896. (setq-local orgstruct-is-++ t))))
  7897. ;;;###autoload
  7898. (defun turn-on-orgstruct++ ()
  7899. "Unconditionally turn on `orgstruct++-mode'."
  7900. (orgstruct++-mode 1))
  7901. (defun orgstruct-error ()
  7902. "Error when there is no default binding for a structure key."
  7903. (interactive)
  7904. (funcall (if (fboundp 'user-error)
  7905. 'user-error
  7906. 'error)
  7907. "This key has no function outside structure elements"))
  7908. (defun orgstruct-setup ()
  7909. "Setup orgstruct keymap."
  7910. (dolist (cell '((org-demote . t)
  7911. (org-metaleft . t)
  7912. (org-metaright . t)
  7913. (org-promote . t)
  7914. (org-shiftmetaleft . t)
  7915. (org-shiftmetaright . t)
  7916. org-backward-element
  7917. org-backward-heading-same-level
  7918. org-ctrl-c-ret
  7919. org-ctrl-c-minus
  7920. org-ctrl-c-star
  7921. org-cycle
  7922. org-force-cycle-archived
  7923. org-forward-heading-same-level
  7924. org-insert-heading
  7925. org-insert-heading-respect-content
  7926. org-kill-note-or-show-branches
  7927. org-mark-subtree
  7928. org-meta-return
  7929. org-metadown
  7930. org-metaup
  7931. org-narrow-to-subtree
  7932. org-promote-subtree
  7933. org-reveal
  7934. org-shiftdown
  7935. org-shiftleft
  7936. org-shiftmetadown
  7937. org-shiftmetaup
  7938. org-shiftright
  7939. org-shifttab
  7940. org-shifttab
  7941. org-shiftup
  7942. org-show-children
  7943. org-show-subtree
  7944. org-sort
  7945. org-up-element
  7946. outline-demote
  7947. outline-next-visible-heading
  7948. outline-previous-visible-heading
  7949. outline-promote
  7950. outline-up-heading))
  7951. (let ((f (or (car-safe cell) cell))
  7952. (disable-when-heading-prefix (cdr-safe cell)))
  7953. (when (fboundp f)
  7954. (let ((new-bindings))
  7955. (dolist (binding (nconc (where-is-internal f org-mode-map)
  7956. (where-is-internal f outline-mode-map)))
  7957. (push binding new-bindings)
  7958. ;; TODO use local-function-key-map
  7959. (dolist (rep '(("<tab>" . "TAB")
  7960. ("<return>" . "RET")
  7961. ("<escape>" . "ESC")
  7962. ("<delete>" . "DEL")))
  7963. (setq binding (read-kbd-macro
  7964. (let ((case-fold-search))
  7965. (replace-regexp-in-string
  7966. (regexp-quote (cdr rep))
  7967. (car rep)
  7968. (key-description binding)))))
  7969. (cl-pushnew binding new-bindings :test 'equal)))
  7970. (dolist (binding new-bindings)
  7971. (let ((key (lookup-key orgstruct-mode-map binding)))
  7972. (when (or (not key) (numberp key))
  7973. (ignore-errors
  7974. (org-defkey orgstruct-mode-map
  7975. binding
  7976. (orgstruct-make-binding
  7977. f binding disable-when-heading-prefix))))))))))
  7978. (run-hooks 'orgstruct-setup-hook))
  7979. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  7980. "Create a function for binding in the structure minor mode.
  7981. FUN is the command to call inside a table. KEY is the key that
  7982. should be checked in for a command to execute outside of tables.
  7983. Non-nil `disable-when-heading-prefix' means to disable the command
  7984. if `orgstruct-heading-prefix-regexp' is not empty."
  7985. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  7986. (let ((nname name)
  7987. (i 0))
  7988. (while (fboundp (intern nname))
  7989. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  7990. (setq name (intern nname)))
  7991. (eval
  7992. (let ((bindings '((org-heading-regexp
  7993. (concat "^"
  7994. orgstruct-heading-prefix-regexp
  7995. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  7996. (org-outline-regexp
  7997. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  7998. (org-outline-regexp-bol
  7999. (concat "^" org-outline-regexp))
  8000. (outline-regexp org-outline-regexp)
  8001. (outline-heading-end-regexp "\n")
  8002. (outline-level 'org-outline-level)
  8003. (outline-heading-alist))))
  8004. `(defun ,name (arg)
  8005. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8006. "Outside of structure, run the binding of `"
  8007. (key-description key) "'."
  8008. (when disable-when-heading-prefix
  8009. (concat
  8010. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8011. "back to the default binding due to limitations of Org's implementation of\n"
  8012. "`" (symbol-name fun) "'.")))
  8013. (interactive "p")
  8014. (let* ((disable
  8015. ,(and disable-when-heading-prefix
  8016. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8017. (fallback
  8018. (or disable
  8019. (not
  8020. (let* ,bindings
  8021. (org-context-p 'headline 'item
  8022. ,(when (memq fun
  8023. '(org-insert-heading
  8024. org-insert-heading-respect-content
  8025. org-meta-return))
  8026. '(when orgstruct-is-++
  8027. 'item-body))))))))
  8028. (if fallback
  8029. (let* ((orgstruct-mode)
  8030. (binding
  8031. (let ((key ,key))
  8032. (catch 'exit
  8033. (dolist
  8034. (rep
  8035. '(nil
  8036. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8037. ("<\\([^>]*\\)return>" . "\\1RET")
  8038. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8039. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8040. nil)
  8041. (when rep
  8042. (setq key (read-kbd-macro
  8043. (let ((case-fold-search))
  8044. (replace-regexp-in-string
  8045. (car rep)
  8046. (cdr rep)
  8047. (key-description key))))))
  8048. (when (key-binding key)
  8049. (throw 'exit (key-binding key))))))))
  8050. (if (keymapp binding)
  8051. (org-set-transient-map binding)
  8052. (let ((func (or binding
  8053. (unless disable
  8054. 'orgstruct-error))))
  8055. (when func
  8056. (call-interactively func)))))
  8057. (org-run-like-in-org-mode
  8058. (lambda ()
  8059. (interactive)
  8060. (let* ,bindings
  8061. (call-interactively ',fun)))))))))
  8062. name))
  8063. (defun org-contextualize-keys (alist contexts)
  8064. "Return valid elements in ALIST depending on CONTEXTS.
  8065. `org-agenda-custom-commands' or `org-capture-templates' are the
  8066. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8067. or `org-capture-templates-contexts' are the associated contexts
  8068. definitions."
  8069. (let ((contexts
  8070. ;; normalize contexts
  8071. (mapcar
  8072. (lambda(c) (cond ((listp (cadr c))
  8073. (list (car c) (car c) (nth 1 c)))
  8074. ((string= "" (cadr c))
  8075. (list (car c) (car c) (nth 2 c)))
  8076. (t c)))
  8077. contexts))
  8078. (a alist) r s)
  8079. ;; loop over all commands or templates
  8080. (dolist (c a)
  8081. (let (vrules repl)
  8082. (cond
  8083. ((not (assoc (car c) contexts))
  8084. (push c r))
  8085. ((and (assoc (car c) contexts)
  8086. (setq vrules (org-contextualize-validate-key
  8087. (car c) contexts)))
  8088. (mapc (lambda (vr)
  8089. (unless (equal (car vr) (cadr vr))
  8090. (setq repl vr)))
  8091. vrules)
  8092. (if (not repl) (push c r)
  8093. (push (cadr repl) s)
  8094. (push
  8095. (cons (car c)
  8096. (cdr (or (assoc (cadr repl) alist)
  8097. (error "Undefined key `%s' as contextual replacement for `%s'"
  8098. (cadr repl) (car c)))))
  8099. r))))))
  8100. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8101. (delq
  8102. nil
  8103. (delete-dups
  8104. (mapcar (lambda (x)
  8105. (let ((tpl (car x)))
  8106. (unless (delq
  8107. nil
  8108. (mapcar (lambda (y)
  8109. (equal y tpl))
  8110. s))
  8111. x)))
  8112. (reverse r))))))
  8113. (defun org-contextualize-validate-key (key contexts)
  8114. "Check CONTEXTS for agenda or capture KEY."
  8115. (let (res)
  8116. (dolist (r contexts)
  8117. (dolist (rr (car (last r)))
  8118. (when
  8119. (and (equal key (car r))
  8120. (if (functionp rr) (funcall rr)
  8121. (or (and (eq (car rr) 'in-file)
  8122. (buffer-file-name)
  8123. (string-match (cdr rr) (buffer-file-name)))
  8124. (and (eq (car rr) 'in-mode)
  8125. (string-match (cdr rr) (symbol-name major-mode)))
  8126. (and (eq (car rr) 'in-buffer)
  8127. (string-match (cdr rr) (buffer-name)))
  8128. (when (and (eq (car rr) 'not-in-file)
  8129. (buffer-file-name))
  8130. (not (string-match (cdr rr) (buffer-file-name))))
  8131. (when (eq (car rr) 'not-in-mode)
  8132. (not (string-match (cdr rr) (symbol-name major-mode))))
  8133. (when (eq (car rr) 'not-in-buffer)
  8134. (not (string-match (cdr rr) (buffer-name)))))))
  8135. (push r res))))
  8136. (delete-dups (delq nil res))))
  8137. (defun org-context-p (&rest contexts)
  8138. "Check if local context is any of CONTEXTS.
  8139. Possible values in the list of contexts are `table', `headline', and `item'."
  8140. (let ((pos (point)))
  8141. (goto-char (point-at-bol))
  8142. (prog1 (or (and (memq 'table contexts)
  8143. (looking-at "[ \t]*|"))
  8144. (and (memq 'headline contexts)
  8145. (looking-at org-outline-regexp))
  8146. (and (memq 'item contexts)
  8147. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8148. (and (memq 'item-body contexts)
  8149. (org-in-item-p)))
  8150. (goto-char pos))))
  8151. ;;;###autoload
  8152. (defun org-run-like-in-org-mode (cmd)
  8153. "Run a command, pretending that the current buffer is in Org mode.
  8154. This will temporarily bind local variables that are typically bound in
  8155. Org mode to the values they have in Org mode, and then interactively
  8156. call CMD."
  8157. (org-load-modules-maybe)
  8158. (unless org-local-vars
  8159. (setq org-local-vars (org-get-local-variables)))
  8160. (let (binds)
  8161. (dolist (var org-local-vars)
  8162. (when (or (not (boundp (car var)))
  8163. (eq (symbol-value (car var))
  8164. (default-value (car var))))
  8165. (push (list (car var) `(quote ,(cadr var))) binds)))
  8166. (eval `(let ,binds
  8167. (call-interactively (quote ,cmd))))))
  8168. (defun org-get-category (&optional pos force-refresh)
  8169. "Get the category applying to position POS."
  8170. (save-match-data
  8171. (when force-refresh (org-refresh-category-properties))
  8172. (let ((pos (or pos (point))))
  8173. (or (get-text-property pos 'org-category)
  8174. (progn (org-refresh-category-properties)
  8175. (get-text-property pos 'org-category))))))
  8176. ;;; Refresh properties
  8177. (defun org-refresh-properties (dprop tprop)
  8178. "Refresh buffer text properties.
  8179. DPROP is the drawer property and TPROP is either the
  8180. corresponding text property to set, or an alist with each element
  8181. being a text property (as a symbol) and a function to apply to
  8182. the value of the drawer property."
  8183. (let* ((case-fold-search t)
  8184. (inhibit-read-only t)
  8185. (inherit? (org-property-inherit-p dprop))
  8186. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8187. (global (and inherit? (org--property-global-value dprop nil))))
  8188. (org-with-silent-modifications
  8189. (org-with-point-at 1
  8190. ;; Set global values (e.g., values defined through
  8191. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8192. (when global (put-text-property (point-min) (point-max) tprop global))
  8193. ;; Set local values.
  8194. (while (re-search-forward property-re nil t)
  8195. (when (org-at-property-p)
  8196. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8197. (outline-next-heading))))))
  8198. (defun org-refresh-property (tprop p &optional inherit)
  8199. "Refresh the buffer text property TPROP from the drawer property P.
  8200. The refresh happens only for the current headline, or the whole
  8201. sub-tree if optional argument INHERIT is non-nil."
  8202. (unless (org-before-first-heading-p)
  8203. (save-excursion
  8204. (org-back-to-heading t)
  8205. (let ((start (point))
  8206. (end (save-excursion
  8207. (if inherit (org-end-of-subtree t t)
  8208. (or (outline-next-heading) (point-max))))))
  8209. (if (symbolp tprop)
  8210. ;; TPROP is a text property symbol.
  8211. (put-text-property start end tprop p)
  8212. ;; TPROP is an alist with (property . function) elements.
  8213. (pcase-dolist (`(,prop . ,f) tprop)
  8214. (put-text-property start end prop (funcall f p))))))))
  8215. (defun org-refresh-category-properties ()
  8216. "Refresh category text properties in the buffer."
  8217. (let ((case-fold-search t)
  8218. (inhibit-read-only t)
  8219. (default-category
  8220. (cond ((null org-category)
  8221. (if buffer-file-name
  8222. (file-name-sans-extension
  8223. (file-name-nondirectory buffer-file-name))
  8224. "???"))
  8225. ((symbolp org-category) (symbol-name org-category))
  8226. (t org-category))))
  8227. (org-with-silent-modifications
  8228. (org-with-wide-buffer
  8229. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8230. ;; This is the default category for the buffer. If none is
  8231. ;; found, fall-back to `org-category' or buffer file name.
  8232. (put-text-property
  8233. (point-min) (point-max)
  8234. 'org-category
  8235. (catch 'buffer-category
  8236. (goto-char (point-max))
  8237. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8238. (let ((element (org-element-at-point)))
  8239. (when (eq (org-element-type element) 'keyword)
  8240. (throw 'buffer-category
  8241. (org-element-property :value element)))))
  8242. default-category))
  8243. ;; Set sub-tree specific categories.
  8244. (goto-char (point-min))
  8245. (let ((regexp (org-re-property "CATEGORY")))
  8246. (while (re-search-forward regexp nil t)
  8247. (let ((value (match-string-no-properties 3)))
  8248. (when (org-at-property-p)
  8249. (put-text-property
  8250. (save-excursion (org-back-to-heading t) (point))
  8251. (save-excursion (org-end-of-subtree t t) (point))
  8252. 'org-category
  8253. value)))))))))
  8254. (defun org-refresh-stats-properties ()
  8255. "Refresh stats text properties in the buffer."
  8256. (org-with-silent-modifications
  8257. (org-with-point-at 1
  8258. (let ((regexp (concat org-outline-regexp-bol
  8259. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8260. (while (re-search-forward regexp nil t)
  8261. (let* ((numerator (string-to-number (match-string 1)))
  8262. (denominator (and (match-end 2)
  8263. (string-to-number (match-string 2))))
  8264. (stats (cond ((not denominator) numerator) ;percent
  8265. ((= denominator 0) 0)
  8266. (t (/ (* numerator 100) denominator)))))
  8267. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8268. 'org-stats stats)))))))
  8269. (defun org-refresh-effort-properties ()
  8270. "Refresh effort properties"
  8271. (org-refresh-properties
  8272. org-effort-property
  8273. '((effort . identity)
  8274. (effort-minutes . org-duration-to-minutes))))
  8275. ;;;; Link Stuff
  8276. ;;; Link abbreviations
  8277. (defun org-link-expand-abbrev (link)
  8278. "Apply replacements as defined in `org-link-abbrev-alist'."
  8279. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8280. (let* ((key (match-string 1 link))
  8281. (as (or (assoc key org-link-abbrev-alist-local)
  8282. (assoc key org-link-abbrev-alist)))
  8283. (tag (and (match-end 2) (match-string 3 link)))
  8284. rpl)
  8285. (if (not as)
  8286. link
  8287. (setq rpl (cdr as))
  8288. (cond
  8289. ((symbolp rpl) (funcall rpl tag))
  8290. ((string-match "%(\\([^)]+\\))" rpl)
  8291. (replace-match
  8292. (save-match-data
  8293. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8294. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8295. ((string-match "%h" rpl)
  8296. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8297. (t (concat rpl tag)))))
  8298. link))
  8299. ;;; Storing and inserting links
  8300. (defvar org-insert-link-history nil
  8301. "Minibuffer history for links inserted with `org-insert-link'.")
  8302. (defvar org-stored-links nil
  8303. "Contains the links stored with `org-store-link'.")
  8304. (defvar org-store-link-plist nil
  8305. "Plist with info about the most recently link created with `org-store-link'.")
  8306. (defun org-store-link-functions ()
  8307. "Return a list of functions that are called to create and store a link.
  8308. The functions defined in the :store property of
  8309. `org-link-parameters'.
  8310. Each function will be called in turn until one returns a non-nil
  8311. value. Each function should check if it is responsible for
  8312. creating this link (for example by looking at the major mode).
  8313. If not, it must exit and return nil. If yes, it should return
  8314. a non-nil value after calling `org-store-link-props' with a list
  8315. of properties and values. Special properties are:
  8316. :type The link prefix, like \"http\". This must be given.
  8317. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8318. This is obligatory as well.
  8319. :description Optional default description for the second pair
  8320. of brackets in an Org mode link. The user can still change
  8321. this when inserting this link into an Org mode buffer.
  8322. In addition to these, any additional properties can be specified
  8323. and then used in capture templates."
  8324. (cl-loop for link in org-link-parameters
  8325. with store-func
  8326. do (setq store-func (org-link-get-parameter (car link) :store))
  8327. if store-func
  8328. collect store-func))
  8329. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8330. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8331. ;;;###autoload
  8332. (defun org-store-link (arg)
  8333. "Store an org-link to the current location.
  8334. \\<org-mode-map>
  8335. This link is added to `org-stored-links' and can later be inserted
  8336. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8337. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8338. A single
  8339. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8340. `org-gnus-prefer-web-links' for links to Usenet articles.
  8341. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8342. skipping storing functions that are not
  8343. part of Org core.
  8344. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8345. prefix ARG forces storing a link for each line in the
  8346. active region."
  8347. (interactive "P")
  8348. (org-load-modules-maybe)
  8349. (if (and (equal arg '(64)) (org-region-active-p))
  8350. (save-excursion
  8351. (let ((end (region-end)))
  8352. (goto-char (region-beginning))
  8353. (set-mark (point))
  8354. (while (< (point-at-eol) end)
  8355. (move-end-of-line 1) (activate-mark)
  8356. (let (current-prefix-arg)
  8357. (call-interactively 'org-store-link))
  8358. (move-beginning-of-line 2)
  8359. (set-mark (point)))))
  8360. (setq org-store-link-plist nil)
  8361. (let (link cpltxt desc description search txt custom-id agenda-link)
  8362. (cond
  8363. ;; Store a link using an external link type, if any function is
  8364. ;; available. If more than one can generate a link from current
  8365. ;; location, ask which one to use.
  8366. ((and (not (equal arg '(16)))
  8367. (let ((results-alist nil))
  8368. (dolist (f (org-store-link-functions))
  8369. (when (funcall f)
  8370. ;; XXX: return value is not link's plist, so we
  8371. ;; store the new value before it is modified. It
  8372. ;; would be cleaner to ask store link functions to
  8373. ;; return the plist instead.
  8374. (push (cons f (copy-sequence org-store-link-plist))
  8375. results-alist)))
  8376. (pcase results-alist
  8377. (`nil nil)
  8378. (`((,_ . ,_)) t) ;single choice: nothing to do
  8379. (`((,name . ,_) . ,_)
  8380. ;; Reinstate link plist associated to the chosen
  8381. ;; function.
  8382. (apply #'org-store-link-props
  8383. (cdr (assoc-string
  8384. (completing-read
  8385. "Which function for creating the link? "
  8386. (mapcar #'car results-alist) nil t name)
  8387. results-alist)))
  8388. t))))
  8389. (setq link (plist-get org-store-link-plist :link))
  8390. (setq desc (or (plist-get org-store-link-plist :description)
  8391. link)))
  8392. ;; Store a link from a source code buffer.
  8393. ((org-src-edit-buffer-p)
  8394. (let ((coderef-format (org-src-coderef-format)))
  8395. (cond ((save-excursion
  8396. (beginning-of-line)
  8397. (looking-at (org-src-coderef-regexp coderef-format)))
  8398. (setq link (format "(%s)" (match-string-no-properties 3))))
  8399. ((called-interactively-p 'any)
  8400. (let ((label (read-string "Code line label: ")))
  8401. (end-of-line)
  8402. (setq link (format coderef-format label))
  8403. (let ((gc (- 79 (length link))))
  8404. (if (< (current-column) gc)
  8405. (org-move-to-column gc t)
  8406. (insert " ")))
  8407. (insert link)
  8408. (setq link (concat "(" label ")"))
  8409. (setq desc nil)))
  8410. (t (setq link nil)))))
  8411. ;; We are in the agenda, link to referenced location
  8412. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8413. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8414. (get-text-property (point) 'org-marker))))
  8415. (when m
  8416. (org-with-point-at m
  8417. (setq agenda-link
  8418. (if (called-interactively-p 'any)
  8419. (call-interactively 'org-store-link)
  8420. (org-store-link nil)))))))
  8421. ((eq major-mode 'calendar-mode)
  8422. (let ((cd (calendar-cursor-to-date)))
  8423. (setq link
  8424. (format-time-string
  8425. (car org-time-stamp-formats)
  8426. (apply 'encode-time
  8427. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8428. nil nil nil))))
  8429. (org-store-link-props :type "calendar" :date cd)))
  8430. ((eq major-mode 'help-mode)
  8431. (setq link (concat "help:" (save-excursion
  8432. (goto-char (point-min))
  8433. (looking-at "^[^ ]+")
  8434. (match-string 0))))
  8435. (org-store-link-props :type "help"))
  8436. ((eq major-mode 'w3-mode)
  8437. (setq cpltxt (if (and (buffer-name)
  8438. (not (string-match "Untitled" (buffer-name))))
  8439. (buffer-name)
  8440. (url-view-url t))
  8441. link (url-view-url t))
  8442. (org-store-link-props :type "w3" :url (url-view-url t)))
  8443. ((eq major-mode 'image-mode)
  8444. (setq cpltxt (concat "file:"
  8445. (abbreviate-file-name buffer-file-name))
  8446. link cpltxt)
  8447. (org-store-link-props :type "image" :file buffer-file-name))
  8448. ;; In dired, store a link to the file of the current line
  8449. ((derived-mode-p 'dired-mode)
  8450. (let ((file (dired-get-filename nil t)))
  8451. (setq file (if file
  8452. (abbreviate-file-name
  8453. (expand-file-name (dired-get-filename nil t)))
  8454. ;; otherwise, no file so use current directory.
  8455. default-directory))
  8456. (setq cpltxt (concat "file:" file)
  8457. link cpltxt)))
  8458. ((setq search (run-hook-with-args-until-success
  8459. 'org-create-file-search-functions))
  8460. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8461. "::" search))
  8462. (setq cpltxt (or description link)))
  8463. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8464. (org-with-limited-levels
  8465. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8466. (cond
  8467. ;; Store a link using the target at point
  8468. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8469. (setq cpltxt
  8470. (concat "file:"
  8471. (abbreviate-file-name
  8472. (buffer-file-name (buffer-base-buffer)))
  8473. "::" (match-string 1))
  8474. link cpltxt))
  8475. ((and (featurep 'org-id)
  8476. (or (eq org-id-link-to-org-use-id t)
  8477. (and (called-interactively-p 'any)
  8478. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8479. (and (eq org-id-link-to-org-use-id
  8480. 'create-if-interactive-and-no-custom-id)
  8481. (not custom-id))))
  8482. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8483. ;; Store a link using the ID at point
  8484. (setq link (condition-case nil
  8485. (prog1 (org-id-store-link)
  8486. (setq desc (or (plist-get org-store-link-plist
  8487. :description)
  8488. "")))
  8489. (error
  8490. ;; Probably before first headline, link only to file
  8491. (concat "file:"
  8492. (abbreviate-file-name
  8493. (buffer-file-name (buffer-base-buffer))))))))
  8494. (t
  8495. ;; Just link to current headline
  8496. (setq cpltxt (concat "file:"
  8497. (abbreviate-file-name
  8498. (buffer-file-name (buffer-base-buffer)))))
  8499. ;; Add a context search string
  8500. (when (org-xor org-context-in-file-links
  8501. (equal arg '(4)))
  8502. (let* ((element (org-element-at-point))
  8503. (name (org-element-property :name element)))
  8504. (setq txt (cond
  8505. ((org-at-heading-p) nil)
  8506. (name)
  8507. ((org-region-active-p)
  8508. (buffer-substring (region-beginning) (region-end)))))
  8509. (when (or (null txt) (string-match "\\S-" txt))
  8510. (setq cpltxt
  8511. (concat cpltxt "::"
  8512. (condition-case nil
  8513. (org-make-org-heading-search-string txt)
  8514. (error "")))
  8515. desc (or name
  8516. (nth 4 (ignore-errors (org-heading-components)))
  8517. "NONE")))))
  8518. (when (string-match "::\\'" cpltxt)
  8519. (setq cpltxt (substring cpltxt 0 -2)))
  8520. (setq link cpltxt)))))
  8521. ((buffer-file-name (buffer-base-buffer))
  8522. ;; Just link to this file here.
  8523. (setq cpltxt (concat "file:"
  8524. (abbreviate-file-name
  8525. (buffer-file-name (buffer-base-buffer)))))
  8526. ;; Add a context string.
  8527. (when (org-xor org-context-in-file-links
  8528. (equal arg '(4)))
  8529. (setq txt (if (org-region-active-p)
  8530. (buffer-substring (region-beginning) (region-end))
  8531. (buffer-substring (point-at-bol) (point-at-eol))))
  8532. ;; Only use search option if there is some text.
  8533. (when (string-match "\\S-" txt)
  8534. (setq cpltxt
  8535. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8536. desc "NONE")))
  8537. (setq link cpltxt))
  8538. ((called-interactively-p 'interactive)
  8539. (user-error "No method for storing a link from this buffer"))
  8540. (t (setq link nil)))
  8541. ;; We're done setting link and desc, clean up
  8542. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8543. (setq link (or link cpltxt)
  8544. desc (or desc cpltxt))
  8545. (cond ((not desc))
  8546. ((equal desc "NONE") (setq desc nil))
  8547. (t (setq desc
  8548. (replace-regexp-in-string
  8549. org-bracket-link-analytic-regexp
  8550. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8551. desc))))
  8552. ;; Return the link
  8553. (if (not (and (or (called-interactively-p 'any)
  8554. executing-kbd-macro)
  8555. link))
  8556. (or agenda-link (and link (org-make-link-string link desc)))
  8557. (push (list link desc) org-stored-links)
  8558. (message "Stored: %s" (or desc link))
  8559. (when custom-id
  8560. (setq link (concat "file:" (abbreviate-file-name
  8561. (buffer-file-name)) "::#" custom-id))
  8562. (push (list link desc) org-stored-links))
  8563. (car org-stored-links)))))
  8564. (defun org-store-link-props (&rest plist)
  8565. "Store link properties.
  8566. The properties are pre-processed by extracting names, addresses
  8567. and dates."
  8568. (let ((x (plist-get plist :from)))
  8569. (when x
  8570. (let ((adr (mail-extract-address-components x)))
  8571. (setq plist (plist-put plist :fromname (car adr)))
  8572. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8573. (let ((x (plist-get plist :to)))
  8574. (when x
  8575. (let ((adr (mail-extract-address-components x)))
  8576. (setq plist (plist-put plist :toname (car adr)))
  8577. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8578. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8579. (when x
  8580. (setq plist (plist-put plist :date-timestamp
  8581. (format-time-string
  8582. (org-time-stamp-format t) x)))
  8583. (setq plist (plist-put plist :date-timestamp-inactive
  8584. (format-time-string
  8585. (org-time-stamp-format t t) x)))))
  8586. (let ((from (plist-get plist :from))
  8587. (to (plist-get plist :to)))
  8588. (when (and from to org-from-is-user-regexp)
  8589. (setq plist
  8590. (plist-put plist :fromto
  8591. (if (string-match org-from-is-user-regexp from)
  8592. (concat "to %t")
  8593. (concat "from %f"))))))
  8594. (setq org-store-link-plist plist))
  8595. (defun org-add-link-props (&rest plist)
  8596. "Add these properties to the link property list."
  8597. (let (key value)
  8598. (while plist
  8599. (setq key (pop plist) value (pop plist))
  8600. (setq org-store-link-plist
  8601. (plist-put org-store-link-plist key value)))))
  8602. (defun org-email-link-description (&optional fmt)
  8603. "Return the description part of an email link.
  8604. This takes information from `org-store-link-plist' and formats it
  8605. according to FMT (default from `org-email-link-description-format')."
  8606. (setq fmt (or fmt org-email-link-description-format))
  8607. (let* ((p org-store-link-plist)
  8608. (to (plist-get p :toaddress))
  8609. (from (plist-get p :fromaddress))
  8610. (table
  8611. (list
  8612. (cons "%c" (plist-get p :fromto))
  8613. (cons "%F" (plist-get p :from))
  8614. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8615. (cons "%T" (plist-get p :to))
  8616. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8617. (cons "%s" (plist-get p :subject))
  8618. (cons "%d" (plist-get p :date))
  8619. (cons "%m" (plist-get p :message-id)))))
  8620. (when (string-match "%c" fmt)
  8621. ;; Check if the user wrote this message
  8622. (if (and org-from-is-user-regexp from to
  8623. (save-match-data (string-match org-from-is-user-regexp from)))
  8624. (setq fmt (replace-match "to %t" t t fmt))
  8625. (setq fmt (replace-match "from %f" t t fmt))))
  8626. (org-replace-escapes fmt table)))
  8627. (defun org-make-org-heading-search-string (&optional string)
  8628. "Make search string for the current headline or STRING."
  8629. (let ((s (or string
  8630. (and (derived-mode-p 'org-mode)
  8631. (save-excursion
  8632. (org-back-to-heading t)
  8633. (org-element-property :raw-value (org-element-at-point))))))
  8634. (lines org-context-in-file-links))
  8635. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8636. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8637. (when (and string (integerp lines) (> lines 0))
  8638. (let ((slines (org-split-string s "\n")))
  8639. (when (< lines (length slines))
  8640. (setq s (mapconcat
  8641. 'identity
  8642. (reverse (nthcdr (- (length slines) lines)
  8643. (reverse slines))) "\n")))))
  8644. (mapconcat #'identity (split-string s) " ")))
  8645. (defun org-make-link-string (link &optional description)
  8646. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8647. (unless (org-string-nw-p link) (error "Empty link"))
  8648. (let ((uri (cond ((string-match org-link-types-re link)
  8649. (concat (match-string 1 link)
  8650. (org-link-escape (substring link (match-end 1)))))
  8651. ;; For readability, url-encode internal links only
  8652. ;; when absolutely needed (i.e, when they contain
  8653. ;; square brackets). File links however, are
  8654. ;; encoded since, e.g., spaces are significant.
  8655. ((or (file-name-absolute-p link)
  8656. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8657. (org-link-escape link))
  8658. (t link)))
  8659. (description
  8660. (and (org-string-nw-p description)
  8661. ;; Remove brackets from description, as they are fatal.
  8662. (replace-regexp-in-string
  8663. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8664. (org-trim description)))))
  8665. (format "[[%s]%s]"
  8666. uri
  8667. (if description (format "[%s]" description) ""))))
  8668. (defconst org-link-escape-chars
  8669. ;;%20 %5B %5D %25
  8670. '(?\s ?\[ ?\] ?%)
  8671. "List of characters that should be escaped in a link when stored to Org.
  8672. This is the list that is used for internal purposes.")
  8673. (defun org-link-escape (text &optional table merge)
  8674. "Return percent escaped representation of TEXT.
  8675. TEXT is a string with the text to escape.
  8676. Optional argument TABLE is a list with characters that should be
  8677. escaped. When nil, `org-link-escape-chars' is used.
  8678. If optional argument MERGE is set, merge TABLE into
  8679. `org-link-escape-chars'."
  8680. (let ((characters-to-encode
  8681. (cond ((null table) org-link-escape-chars)
  8682. (merge (append org-link-escape-chars table))
  8683. (t table))))
  8684. (mapconcat
  8685. (lambda (c)
  8686. (if (or (memq c characters-to-encode)
  8687. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8688. (mapconcat (lambda (e) (format "%%%.2X" e))
  8689. (or (encode-coding-char c 'utf-8)
  8690. (error "Unable to percent escape character: %c" c))
  8691. "")
  8692. (char-to-string c)))
  8693. text "")))
  8694. (defun org-link-unescape (str)
  8695. "Unhex hexified Unicode parts in string STR.
  8696. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8697. reciprocal of `org-link-escape', which see."
  8698. (if (org-string-nw-p str)
  8699. (replace-regexp-in-string
  8700. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8701. str))
  8702. (defun org-link-unescape-compound (hex)
  8703. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8704. Note: this function also decodes single byte encodings like
  8705. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8706. (save-match-data
  8707. (let* ((bytes (cdr (split-string hex "%")))
  8708. (ret "")
  8709. (eat 0)
  8710. (sum 0))
  8711. (while bytes
  8712. (let* ((val (string-to-number (pop bytes) 16))
  8713. (shift-xor
  8714. (if (= 0 eat)
  8715. (cond
  8716. ((>= val 252) (cons 6 252))
  8717. ((>= val 248) (cons 5 248))
  8718. ((>= val 240) (cons 4 240))
  8719. ((>= val 224) (cons 3 224))
  8720. ((>= val 192) (cons 2 192))
  8721. (t (cons 0 0)))
  8722. (cons 6 128))))
  8723. (when (>= val 192) (setq eat (car shift-xor)))
  8724. (setq val (logxor val (cdr shift-xor)))
  8725. (setq sum (+ (lsh sum (car shift-xor)) val))
  8726. (when (> eat 0) (setq eat (- eat 1)))
  8727. (cond
  8728. ((= 0 eat) ;multi byte
  8729. (setq ret (concat ret (char-to-string sum)))
  8730. (setq sum 0))
  8731. ((not bytes) ; single byte(s)
  8732. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8733. ret)))
  8734. (defun org-link-unescape-single-byte-sequence (hex)
  8735. "Unhexify hex-encoded single byte character sequences."
  8736. (mapconcat (lambda (byte)
  8737. (char-to-string (string-to-number byte 16)))
  8738. (cdr (split-string hex "%")) ""))
  8739. (defun org-fixup-message-id-for-http (s)
  8740. "Replace special characters in a message id, so it can be used in an http query."
  8741. (when (string-match "%" s)
  8742. (setq s (mapconcat (lambda (c)
  8743. (if (eq c ?%)
  8744. "%25"
  8745. (char-to-string c)))
  8746. s "")))
  8747. (while (string-match "<" s)
  8748. (setq s (replace-match "%3C" t t s)))
  8749. (while (string-match ">" s)
  8750. (setq s (replace-match "%3E" t t s)))
  8751. (while (string-match "@" s)
  8752. (setq s (replace-match "%40" t t s)))
  8753. s)
  8754. (defun org-link-prettify (link)
  8755. "Return a human-readable representation of LINK.
  8756. The car of LINK must be a raw link.
  8757. The cdr of LINK must be either a link description or nil."
  8758. (let ((desc (or (cadr link) "<no description>")))
  8759. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8760. "<" (car link) ">")))
  8761. ;;;###autoload
  8762. (defun org-insert-link-global ()
  8763. "Insert a link like Org mode does.
  8764. This command can be called in any mode to insert a link in Org syntax."
  8765. (interactive)
  8766. (org-load-modules-maybe)
  8767. (org-run-like-in-org-mode 'org-insert-link))
  8768. (defun org-insert-all-links (arg &optional pre post)
  8769. "Insert all links in `org-stored-links'.
  8770. When a universal prefix, do not delete the links from `org-stored-links'.
  8771. When `ARG' is a number, insert the last N link(s).
  8772. `PRE' and `POST' are optional arguments to define a string to
  8773. prepend or to append."
  8774. (interactive "P")
  8775. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8776. (links (copy-sequence org-stored-links))
  8777. (pr (or pre "- "))
  8778. (po (or post "\n"))
  8779. (cnt 1) l)
  8780. (if (null org-stored-links)
  8781. (message "No link to insert")
  8782. (while (and (or (listp arg) (>= arg cnt))
  8783. (setq l (if (listp arg)
  8784. (pop links)
  8785. (pop org-stored-links))))
  8786. (setq cnt (1+ cnt))
  8787. (insert pr)
  8788. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8789. (insert po)))))
  8790. (defun org-insert-last-stored-link (arg)
  8791. "Insert the last link stored in `org-stored-links'."
  8792. (interactive "p")
  8793. (org-insert-all-links arg "" "\n"))
  8794. (defun org-link-fontify-links-to-this-file ()
  8795. "Fontify links to the current file in `org-stored-links'."
  8796. (let ((f (buffer-file-name)) a b)
  8797. (setq a (mapcar (lambda(l)
  8798. (let ((ll (car l)))
  8799. (when (and (string-match "^file:\\(.+\\)::" ll)
  8800. (equal f (expand-file-name (match-string 1 ll))))
  8801. ll)))
  8802. org-stored-links))
  8803. (when (featurep 'org-id)
  8804. (setq b (mapcar (lambda(l)
  8805. (let ((ll (car l)))
  8806. (when (and (string-match "^id:\\(.+\\)$" ll)
  8807. (equal f (expand-file-name
  8808. (or (org-id-find-id-file
  8809. (match-string 1 ll)) ""))))
  8810. ll)))
  8811. org-stored-links)))
  8812. (mapcar (lambda(l)
  8813. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8814. (delq nil (append a b)))))
  8815. (defvar org--links-history nil)
  8816. (defun org-insert-link (&optional complete-file link-location default-description)
  8817. "Insert a link. At the prompt, enter the link.
  8818. Completion can be used to insert any of the link protocol prefixes in use.
  8819. The history can be used to select a link previously stored with
  8820. `org-store-link'. When the empty string is entered (i.e. if you just
  8821. press `RET' at the prompt), the link defaults to the most recently
  8822. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8823. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8824. You will also be prompted for a description, and if one is given, it will
  8825. be displayed in the buffer instead of the link.
  8826. If there is already a link at point, this command will allow you to edit
  8827. link and description parts.
  8828. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8829. file name can be
  8830. selected using completion. The path to the file will be relative to the
  8831. current directory if the file is in the current directory or a subdirectory.
  8832. Otherwise, the link will be the absolute path as completed in the minibuffer
  8833. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8834. option `org-link-file-path-type'.
  8835. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8836. absolute path even if the file is in
  8837. the current directory or below.
  8838. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8839. prefix negates `org-keep-stored-link-after-insertion'.
  8840. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8841. the link location instead of reading one interactively.
  8842. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8843. be used as the default description. Otherwise, if
  8844. `org-make-link-description-function' is non-nil, this function
  8845. will be called with the link target, and the result will be the
  8846. default link description."
  8847. (interactive "P")
  8848. (let* ((wcf (current-window-configuration))
  8849. (origbuf (current-buffer))
  8850. (region (when (org-region-active-p)
  8851. (buffer-substring (region-beginning) (region-end))))
  8852. (remove (and region (list (region-beginning) (region-end))))
  8853. (desc region)
  8854. (link link-location)
  8855. (abbrevs org-link-abbrev-alist-local)
  8856. entry all-prefixes auto-desc)
  8857. (cond
  8858. (link-location) ; specified by arg, just use it.
  8859. ((org-in-regexp org-bracket-link-regexp 1)
  8860. ;; We do have a link at point, and we are going to edit it.
  8861. (setq remove (list (match-beginning 0) (match-end 0)))
  8862. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8863. (setq link (read-string "Link: "
  8864. (org-link-unescape
  8865. (match-string-no-properties 1)))))
  8866. ((or (org-in-regexp org-angle-link-re)
  8867. (org-in-regexp org-plain-link-re))
  8868. ;; Convert to bracket link
  8869. (setq remove (list (match-beginning 0) (match-end 0))
  8870. link (read-string "Link: "
  8871. (org-unbracket-string "<" ">" (match-string 0)))))
  8872. ((member complete-file '((4) (16)))
  8873. ;; Completing read for file names.
  8874. (setq link (org-file-complete-link complete-file)))
  8875. (t
  8876. ;; Read link, with completion for stored links.
  8877. (org-link-fontify-links-to-this-file)
  8878. (org-switch-to-buffer-other-window "*Org Links*")
  8879. (with-current-buffer "*Org Links*"
  8880. (erase-buffer)
  8881. (insert "Insert a link.
  8882. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8883. (when org-stored-links
  8884. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8885. (insert (mapconcat 'org-link-prettify
  8886. (reverse org-stored-links) "\n")))
  8887. (goto-char (point-min)))
  8888. (let ((cw (selected-window)))
  8889. (select-window (get-buffer-window "*Org Links*" 'visible))
  8890. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8891. (unless (pos-visible-in-window-p (point-max))
  8892. (org-fit-window-to-buffer))
  8893. (and (window-live-p cw) (select-window cw)))
  8894. (setq all-prefixes (append (mapcar 'car abbrevs)
  8895. (mapcar 'car org-link-abbrev-alist)
  8896. (org-link-types)))
  8897. (unwind-protect
  8898. ;; Fake a link history, containing the stored links.
  8899. (let ((org--links-history
  8900. (append (mapcar #'car org-stored-links)
  8901. org-insert-link-history)))
  8902. (setq link
  8903. (org-completing-read
  8904. "Link: "
  8905. (append
  8906. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8907. (mapcar #'car org-stored-links))
  8908. nil nil nil
  8909. 'org--links-history
  8910. (caar org-stored-links)))
  8911. (unless (org-string-nw-p link) (user-error "No link selected"))
  8912. (dolist (l org-stored-links)
  8913. (when (equal link (cadr l))
  8914. (setq link (car l))
  8915. (setq auto-desc t)))
  8916. (when (or (member link all-prefixes)
  8917. (and (equal ":" (substring link -1))
  8918. (member (substring link 0 -1) all-prefixes)
  8919. (setq link (substring link 0 -1))))
  8920. (setq link (with-current-buffer origbuf
  8921. (org-link-try-special-completion link)))))
  8922. (set-window-configuration wcf)
  8923. (kill-buffer "*Org Links*"))
  8924. (setq entry (assoc link org-stored-links))
  8925. (or entry (push link org-insert-link-history))
  8926. (setq desc (or desc (nth 1 entry)))))
  8927. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8928. (not org-keep-stored-link-after-insertion))
  8929. (setq org-stored-links (delq (assoc link org-stored-links)
  8930. org-stored-links)))
  8931. (when (and (string-match org-plain-link-re link)
  8932. (not (string-match org-ts-regexp link)))
  8933. ;; URL-like link, normalize the use of angular brackets.
  8934. (setq link (org-unbracket-string "<" ">" link)))
  8935. ;; Check if we are linking to the current file with a search
  8936. ;; option If yes, simplify the link by using only the search
  8937. ;; option.
  8938. (when (and buffer-file-name
  8939. (let ((case-fold-search nil))
  8940. (string-match "\\`file:\\(.+?\\)::" link)))
  8941. (let ((path (match-string-no-properties 1 link))
  8942. (search (substring-no-properties link (match-end 0))))
  8943. (save-match-data
  8944. (when (equal (file-truename buffer-file-name) (file-truename path))
  8945. ;; We are linking to this same file, with a search option
  8946. (setq link search)))))
  8947. ;; Check if we can/should use a relative path. If yes, simplify the link
  8948. (let ((case-fold-search nil))
  8949. (when (string-match "\\`\\(file\\|docview\\):" link)
  8950. (let* ((type (match-string-no-properties 0 link))
  8951. (path (substring-no-properties link (match-end 0)))
  8952. (origpath path))
  8953. (cond
  8954. ((or (eq org-link-file-path-type 'absolute)
  8955. (equal complete-file '(16)))
  8956. (setq path (abbreviate-file-name (expand-file-name path))))
  8957. ((eq org-link-file-path-type 'noabbrev)
  8958. (setq path (expand-file-name path)))
  8959. ((eq org-link-file-path-type 'relative)
  8960. (setq path (file-relative-name path)))
  8961. (t
  8962. (save-match-data
  8963. (if (string-match (concat "^" (regexp-quote
  8964. (expand-file-name
  8965. (file-name-as-directory
  8966. default-directory))))
  8967. (expand-file-name path))
  8968. ;; We are linking a file with relative path name.
  8969. (setq path (substring (expand-file-name path)
  8970. (match-end 0)))
  8971. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8972. (setq link (concat type path))
  8973. (when (equal desc origpath)
  8974. (setq desc path)))))
  8975. (unless auto-desc
  8976. (let ((initial-input
  8977. (cond
  8978. (default-description)
  8979. ((not org-make-link-description-function) desc)
  8980. (t (condition-case nil
  8981. (funcall org-make-link-description-function link desc)
  8982. (error
  8983. (message "Can't get link description from `%s'"
  8984. (symbol-name org-make-link-description-function))
  8985. (sit-for 2)
  8986. nil))))))
  8987. (setq desc (read-string "Description: " initial-input))))
  8988. (unless (string-match "\\S-" desc) (setq desc nil))
  8989. (when remove (apply 'delete-region remove))
  8990. (insert (org-make-link-string link desc))
  8991. ;; Redisplay so as the new link has proper invisible characters.
  8992. (sit-for 0)))
  8993. (defun org-link-try-special-completion (type)
  8994. "If there is completion support for link type TYPE, offer it."
  8995. (let ((fun (org-link-get-parameter type :complete)))
  8996. (if (functionp fun)
  8997. (funcall fun)
  8998. (read-string "Link (no completion support): " (concat type ":")))))
  8999. (defun org-file-complete-link (&optional arg)
  9000. "Create a file link using completion."
  9001. (let ((file (read-file-name "File: "))
  9002. (pwd (file-name-as-directory (expand-file-name ".")))
  9003. (pwd1 (file-name-as-directory (abbreviate-file-name
  9004. (expand-file-name ".")))))
  9005. (cond ((equal arg '(16))
  9006. (concat "file:"
  9007. (abbreviate-file-name (expand-file-name file))))
  9008. ((string-match
  9009. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9010. (concat "file:" (match-string 1 file)))
  9011. ((string-match
  9012. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9013. (expand-file-name file))
  9014. (concat "file:"
  9015. (match-string 1 (expand-file-name file))))
  9016. (t (concat "file:" file)))))
  9017. ;;; Opening/following a link
  9018. (defvar org-link-search-failed nil)
  9019. (defvar org-open-link-functions nil
  9020. "Hook for functions finding a plain text link.
  9021. These functions must take a single argument, the link content.
  9022. They will be called for links that look like [[link text][description]]
  9023. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9024. like a filename (e.g. \"./blue.png\").
  9025. These functions will be called *before* Org attempts to resolve the
  9026. link by doing text searches in the current buffer - so if you want a
  9027. link \"[[target]]\" to still find \"<<target>>\", your function should
  9028. handle this as a special case.
  9029. When the function does handle the link, it must return a non-nil value.
  9030. If it decides that it is not responsible for this link, it must return
  9031. nil to indicate that that Org can continue with other options like
  9032. exact and fuzzy text search.")
  9033. (defun org-next-link (&optional search-backward)
  9034. "Move forward to the next link.
  9035. If the link is in hidden text, expose it."
  9036. (interactive "P")
  9037. (when (and org-link-search-failed (eq this-command last-command))
  9038. (goto-char (point-min))
  9039. (message "Link search wrapped back to beginning of buffer"))
  9040. (setq org-link-search-failed nil)
  9041. (let* ((pos (point))
  9042. (ct (org-context))
  9043. (a (assq :link ct))
  9044. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9045. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9046. ((looking-at org-any-link-re)
  9047. ;; Don't stay stuck at link without an org-link face
  9048. (forward-char (if search-backward -1 1))))
  9049. (if (funcall srch-fun org-any-link-re nil t)
  9050. (progn
  9051. (goto-char (match-beginning 0))
  9052. (when (org-invisible-p) (org-show-context)))
  9053. (goto-char pos)
  9054. (setq org-link-search-failed t)
  9055. (message "No further link found"))))
  9056. (defun org-previous-link ()
  9057. "Move backward to the previous link.
  9058. If the link is in hidden text, expose it."
  9059. (interactive)
  9060. (funcall 'org-next-link t))
  9061. (defun org-translate-link (s)
  9062. "Translate a link string if a translation function has been defined."
  9063. (with-temp-buffer
  9064. (insert (org-trim s))
  9065. (org-trim (org-element-interpret-data (org-element-context)))))
  9066. (defun org-translate-link-from-planner (type path)
  9067. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9068. This is still an experimental function, your mileage may vary."
  9069. (cond
  9070. ((member type '("http" "https" "news" "ftp"))
  9071. ;; standard Internet links are the same.
  9072. nil)
  9073. ((and (equal type "irc") (string-match "^//" path))
  9074. ;; Planner has two / at the beginning of an irc link, we have 1.
  9075. ;; We should have zero, actually....
  9076. (setq path (substring path 1)))
  9077. ((and (equal type "lisp") (string-match "^/" path))
  9078. ;; Planner has a slash, we do not.
  9079. (setq type "elisp" path (substring path 1)))
  9080. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9081. ;; A typical message link. Planner has the id after the final slash,
  9082. ;; we separate it with a hash mark
  9083. (setq path (concat (match-string 1 path) "#"
  9084. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9085. (cons type path))
  9086. (defun org-find-file-at-mouse (ev)
  9087. "Open file link or URL at mouse."
  9088. (interactive "e")
  9089. (mouse-set-point ev)
  9090. (org-open-at-point 'in-emacs))
  9091. (defun org-open-at-mouse (ev)
  9092. "Open file link or URL at mouse.
  9093. See the docstring of `org-open-file' for details."
  9094. (interactive "e")
  9095. (mouse-set-point ev)
  9096. (when (eq major-mode 'org-agenda-mode)
  9097. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9098. (org-open-at-point))
  9099. (defvar org-window-config-before-follow-link nil
  9100. "The window configuration before following a link.
  9101. This is saved in case the need arises to restore it.")
  9102. ;;;###autoload
  9103. (defun org-open-at-point-global ()
  9104. "Follow a link or time-stamp like Org mode does.
  9105. This command can be called in any mode to follow an external link
  9106. or a time-stamp that has Org mode syntax. Its behavior is
  9107. undefined when called on internal links (e.g., fuzzy links).
  9108. Raise an error when there is nothing to follow. "
  9109. (interactive)
  9110. (cond ((org-in-regexp org-any-link-re)
  9111. (org-open-link-from-string (match-string-no-properties 0)))
  9112. ((or (org-in-regexp org-ts-regexp-both nil t)
  9113. (org-in-regexp org-tsr-regexp-both nil t))
  9114. (org-follow-timestamp-link))
  9115. (t (user-error "No link found"))))
  9116. ;;;###autoload
  9117. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9118. "Open a link in the string S, as if it was in Org mode."
  9119. (interactive "sLink: \nP")
  9120. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9121. (with-temp-buffer
  9122. (let ((org-inhibit-startup (not reference-buffer)))
  9123. (org-mode)
  9124. (insert s)
  9125. (goto-char (point-min))
  9126. (when reference-buffer
  9127. (setq org-link-abbrev-alist-local
  9128. (with-current-buffer reference-buffer
  9129. org-link-abbrev-alist-local)))
  9130. (org-open-at-point arg reference-buffer)))))
  9131. (defvar org-open-at-point-functions nil
  9132. "Hook that is run when following a link at point.
  9133. Functions in this hook must return t if they identify and follow
  9134. a link at point. If they don't find anything interesting at point,
  9135. they must return nil.")
  9136. (defvar org-link-search-inhibit-query nil)
  9137. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9138. (defun org--open-doi-link (path)
  9139. "Open a \"doi\" type link.
  9140. PATH is a the path to search for, as a string."
  9141. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9142. (defun org--open-elisp-link (path)
  9143. "Open a \"elisp\" type link.
  9144. PATH is the sexp to evaluate, as a string."
  9145. (let ((cmd path))
  9146. (if (or (and (org-string-nw-p
  9147. org-confirm-elisp-link-not-regexp)
  9148. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9149. (not org-confirm-elisp-link-function)
  9150. (funcall org-confirm-elisp-link-function
  9151. (format "Execute \"%s\" as elisp? "
  9152. (org-add-props cmd nil 'face 'org-warning))))
  9153. (message "%s => %s" cmd
  9154. (if (eq (string-to-char cmd) ?\()
  9155. (eval (read cmd))
  9156. (call-interactively (read cmd))))
  9157. (user-error "Abort"))))
  9158. (defun org--open-help-link (path)
  9159. "Open a \"help\" type link.
  9160. PATH is a symbol name, as a string."
  9161. (pcase (intern path)
  9162. ((and (pred fboundp) variable) (describe-function variable))
  9163. ((and (pred boundp) function) (describe-variable function))
  9164. (name (user-error "Unknown function or variable: %s" name))))
  9165. (defun org--open-shell-link (path)
  9166. "Open a \"shell\" type link.
  9167. PATH is the command to execute, as a string."
  9168. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9169. (cmd path))
  9170. (if (or (and (org-string-nw-p
  9171. org-confirm-shell-link-not-regexp)
  9172. (string-match
  9173. org-confirm-shell-link-not-regexp cmd))
  9174. (not org-confirm-shell-link-function)
  9175. (funcall org-confirm-shell-link-function
  9176. (format "Execute \"%s\" in shell? "
  9177. (org-add-props cmd nil
  9178. 'face 'org-warning))))
  9179. (progn
  9180. (message "Executing %s" cmd)
  9181. (shell-command cmd buf)
  9182. (when (featurep 'midnight)
  9183. (setq clean-buffer-list-kill-buffer-names
  9184. (cons (buffer-name buf)
  9185. clean-buffer-list-kill-buffer-names))))
  9186. (user-error "Abort"))))
  9187. (defun org-open-at-point (&optional arg reference-buffer)
  9188. "Open link, timestamp, footnote or tags at point.
  9189. When point is on a link, follow it. Normally, files will be
  9190. opened by an appropriate application. If the optional prefix
  9191. argument ARG is non-nil, Emacs will visit the file. With
  9192. a double prefix argument, try to open outside of Emacs, in the
  9193. application the system uses for this file type.
  9194. When point is on a timestamp, open the agenda at the day
  9195. specified.
  9196. When point is a footnote definition, move to the first reference
  9197. found. If it is on a reference, move to the associated
  9198. definition.
  9199. When point is on a headline, display a list of every link in the
  9200. entry, so it is possible to pick one, or all, of them. If point
  9201. is on a tag, call `org-tags-view' instead.
  9202. When optional argument REFERENCE-BUFFER is non-nil, it should
  9203. specify a buffer from where the link search should happen. This
  9204. is used internally by `org-open-link-from-string'.
  9205. On top of syntactically correct links, this function will also
  9206. try to open links and time-stamps in comments, example
  9207. blocks... i.e., whenever point is on something looking like
  9208. a timestamp or a link."
  9209. (interactive "P")
  9210. ;; On a code block, open block's results.
  9211. (unless (call-interactively 'org-babel-open-src-block-result)
  9212. (org-load-modules-maybe)
  9213. (setq org-window-config-before-follow-link (current-window-configuration))
  9214. (org-remove-occur-highlights nil nil t)
  9215. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9216. (let* ((context
  9217. ;; Only consider supported types, even if they are not
  9218. ;; the closest one.
  9219. (org-element-lineage
  9220. (org-element-context)
  9221. '(clock footnote-definition footnote-reference headline
  9222. inlinetask link timestamp)
  9223. t))
  9224. (type (org-element-type context))
  9225. (value (org-element-property :value context)))
  9226. (cond
  9227. ;; On a headline or an inlinetask, but not on a timestamp,
  9228. ;; a link, a footnote reference.
  9229. ((memq type '(headline inlinetask))
  9230. (org-match-line org-complex-heading-regexp)
  9231. (if (and (match-beginning 5)
  9232. (>= (point) (match-beginning 5))
  9233. (< (point) (match-end 5)))
  9234. ;; On tags.
  9235. (org-tags-view arg (substring (match-string 5) 0 -1))
  9236. ;; Not on tags.
  9237. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9238. (`(nil . ,_)
  9239. (require 'org-attach)
  9240. (org-attach-reveal 'if-exists))
  9241. (`(,links . ,links-end)
  9242. (dolist (link (if (stringp links) (list links) links))
  9243. (search-forward link nil links-end)
  9244. (goto-char (match-beginning 0))
  9245. (org-open-at-point))))))
  9246. ;; On a footnote reference or at definition's label.
  9247. ((or (eq type 'footnote-reference)
  9248. (and (eq type 'footnote-definition)
  9249. (save-excursion
  9250. ;; Do not validate action when point is on the
  9251. ;; spaces right after the footnote label, in
  9252. ;; order to be on par with behaviour on links.
  9253. (skip-chars-forward " \t")
  9254. (let ((begin
  9255. (org-element-property :contents-begin context)))
  9256. (if begin (< (point) begin)
  9257. (= (org-element-property :post-affiliated context)
  9258. (line-beginning-position)))))))
  9259. (org-footnote-action))
  9260. ;; No valid context. Ignore catch-all types like `headline'.
  9261. ;; If point is on something looking like a link or
  9262. ;; a time-stamp, try opening it. It may be useful in
  9263. ;; comments, example blocks...
  9264. ((memq type '(footnote-definition headline inlinetask nil))
  9265. (call-interactively #'org-open-at-point-global))
  9266. ;; On a clock line, make sure point is on the timestamp
  9267. ;; before opening it.
  9268. ((and (eq type 'clock)
  9269. value
  9270. (>= (point) (org-element-property :begin value))
  9271. (<= (point) (org-element-property :end value)))
  9272. (org-follow-timestamp-link))
  9273. ;; Do nothing on white spaces after an object.
  9274. ((>= (point)
  9275. (save-excursion
  9276. (goto-char (org-element-property :end context))
  9277. (skip-chars-backward " \t")
  9278. (point)))
  9279. (user-error "No link found"))
  9280. ((eq type 'timestamp) (org-follow-timestamp-link))
  9281. ((eq type 'link)
  9282. (let ((type (org-element-property :type context))
  9283. (path (org-link-unescape (org-element-property :path context))))
  9284. ;; Switch back to REFERENCE-BUFFER needed when called in
  9285. ;; a temporary buffer through `org-open-link-from-string'.
  9286. (with-current-buffer (or reference-buffer (current-buffer))
  9287. (cond
  9288. ((equal type "file")
  9289. (if (string-match "[*?{]" (file-name-nondirectory path))
  9290. (dired path)
  9291. ;; Look into `org-link-parameters' in order to find
  9292. ;; a DEDICATED-FUNCTION to open file. The function
  9293. ;; will be applied on raw link instead of parsed
  9294. ;; link due to the limitation in `org-add-link-type'
  9295. ;; ("open" function called with a single argument).
  9296. ;; If no such function is found, fallback to
  9297. ;; `org-open-file'.
  9298. (let* ((option (org-element-property :search-option context))
  9299. (app (org-element-property :application context))
  9300. (dedicated-function
  9301. (org-link-get-parameter
  9302. (if app (concat type "+" app) type)
  9303. :follow)))
  9304. (if dedicated-function
  9305. (funcall dedicated-function
  9306. (concat path
  9307. (and option (concat "::" option))))
  9308. (apply #'org-open-file
  9309. path
  9310. (cond (arg)
  9311. ((equal app "emacs") 'emacs)
  9312. ((equal app "sys") 'system))
  9313. (cond ((not option) nil)
  9314. ((string-match-p "\\`[0-9]+\\'" option)
  9315. (list (string-to-number option)))
  9316. (t (list nil
  9317. (org-link-unescape option)))))))))
  9318. ((functionp (org-link-get-parameter type :follow))
  9319. (funcall (org-link-get-parameter type :follow) path))
  9320. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9321. (unless (run-hook-with-args-until-success
  9322. 'org-open-link-functions path)
  9323. (if (not arg) (org-mark-ring-push)
  9324. (switch-to-buffer-other-window
  9325. (org-get-buffer-for-internal-link (current-buffer))))
  9326. (let ((destination
  9327. (org-with-wide-buffer
  9328. (if (equal type "radio")
  9329. (org-search-radio-target
  9330. (org-element-property :path context))
  9331. (org-link-search
  9332. (if (member type '("custom-id" "coderef"))
  9333. (org-element-property :raw-link context)
  9334. path)
  9335. ;; Prevent fuzzy links from matching
  9336. ;; themselves.
  9337. (and (equal type "fuzzy")
  9338. (+ 2 (org-element-property :begin context)))))
  9339. (point))))
  9340. (unless (and (<= (point-min) destination)
  9341. (>= (point-max) destination))
  9342. (widen))
  9343. (goto-char destination))))
  9344. (t (browse-url-at-point))))))
  9345. (t (user-error "No link found")))))
  9346. (run-hook-with-args 'org-follow-link-hook)))
  9347. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9348. "Offer links in the current entry and return the selected link.
  9349. If there is only one link, return it.
  9350. If NTH is an integer, return the NTH link found.
  9351. If ZERO is a string, check also this string for a link, and if
  9352. there is one, return it."
  9353. (with-current-buffer buffer
  9354. (org-with-wide-buffer
  9355. (goto-char marker)
  9356. (let ((cnt ?0)
  9357. have-zero end links link c)
  9358. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9359. (push (match-string 0 zero) links)
  9360. (setq cnt (1- cnt) have-zero t))
  9361. (save-excursion
  9362. (org-back-to-heading t)
  9363. (setq end (save-excursion (outline-next-heading) (point)))
  9364. (while (re-search-forward org-any-link-re end t)
  9365. (push (match-string 0) links))
  9366. (setq links (org-uniquify (reverse links))))
  9367. (cond
  9368. ((null links)
  9369. (message "No links"))
  9370. ((equal (length links) 1)
  9371. (setq link (car links)))
  9372. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9373. (setq link (nth (if have-zero nth (1- nth)) links)))
  9374. (t ; we have to select a link
  9375. (save-excursion
  9376. (save-window-excursion
  9377. (delete-other-windows)
  9378. (with-output-to-temp-buffer "*Select Link*"
  9379. (dolist (l links)
  9380. (cond
  9381. ((not (string-match org-bracket-link-regexp l))
  9382. (princ (format "[%c] %s\n" (cl-incf cnt)
  9383. (org-unbracket-string "<" ">" l))))
  9384. ((match-end 3)
  9385. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9386. (match-string 3 l) (match-string 1 l))))
  9387. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9388. (match-string 1 l)))))))
  9389. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9390. (message "Select link to open, RET to open all:")
  9391. (setq c (read-char-exclusive))
  9392. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9393. (when (equal c ?q) (user-error "Abort"))
  9394. (if (equal c ?\C-m)
  9395. (setq link links)
  9396. (setq nth (- c ?0))
  9397. (when have-zero (setq nth (1+ nth)))
  9398. (unless (and (integerp nth) (>= (length links) nth))
  9399. (user-error "Invalid link selection"))
  9400. (setq link (nth (1- nth) links)))))
  9401. (cons link end)))))
  9402. ;; TODO: These functions are deprecated since `org-open-at-point'
  9403. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9404. (defun org-open-file-with-system (path)
  9405. "Open file at PATH using the system way of opening it."
  9406. (org-open-file path 'system))
  9407. (defun org-open-file-with-emacs (path)
  9408. "Open file at PATH in Emacs."
  9409. (org-open-file path 'emacs))
  9410. ;;; File search
  9411. (defvar org-create-file-search-functions nil
  9412. "List of functions to construct the right search string for a file link.
  9413. These functions are called in turn with point at the location to
  9414. which the link should point.
  9415. A function in the hook should first test if it would like to
  9416. handle this file type, for example by checking the `major-mode'
  9417. or the file extension. If it decides not to handle this file, it
  9418. should just return nil to give other functions a chance. If it
  9419. does handle the file, it must return the search string to be used
  9420. when following the link. The search string will be part of the
  9421. file link, given after a double colon, and `org-open-at-point'
  9422. will automatically search for it. If special measures must be
  9423. taken to make the search successful, another function should be
  9424. added to the companion hook `org-execute-file-search-functions',
  9425. which see.
  9426. A function in this hook may also use `setq' to set the variable
  9427. `description' to provide a suggestion for the descriptive text to
  9428. be used for this link when it gets inserted into an Org buffer
  9429. with \\[org-insert-link].")
  9430. (defvar org-execute-file-search-functions nil
  9431. "List of functions to execute a file search triggered by a link.
  9432. Functions added to this hook must accept a single argument, the
  9433. search string that was part of the file link, the part after the
  9434. double colon. The function must first check if it would like to
  9435. handle this search, for example by checking the `major-mode' or
  9436. the file extension. If it decides not to handle this search, it
  9437. should just return nil to give other functions a chance. If it
  9438. does handle the search, it must return a non-nil value to keep
  9439. other functions from trying.
  9440. Each function can access the current prefix argument through the
  9441. variable `current-prefix-arg'. Note that a single prefix is used
  9442. to force opening a link in Emacs, so it may be good to only use a
  9443. numeric or double prefix to guide the search function.
  9444. In case this is needed, a function in this hook can also restore
  9445. the window configuration before `org-open-at-point' was called using:
  9446. (set-window-configuration org-window-config-before-follow-link)")
  9447. (defun org-search-radio-target (target)
  9448. "Search a radio target matching TARGET in current buffer.
  9449. White spaces are not significant."
  9450. (let ((re (format "<<<%s>>>"
  9451. (mapconcat #'regexp-quote
  9452. (split-string target)
  9453. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9454. (origin (point)))
  9455. (goto-char (point-min))
  9456. (catch :radio-match
  9457. (while (re-search-forward re nil t)
  9458. (backward-char)
  9459. (let ((object (org-element-context)))
  9460. (when (eq (org-element-type object) 'radio-target)
  9461. (goto-char (org-element-property :begin object))
  9462. (org-show-context 'link-search)
  9463. (throw :radio-match nil))))
  9464. (goto-char origin)
  9465. (user-error "No match for radio target: %s" target))))
  9466. (defun org-link-search (s &optional avoid-pos stealth)
  9467. "Search for a search string S.
  9468. If S starts with \"#\", it triggers a custom ID search.
  9469. If S is enclosed within parenthesis, it initiates a coderef
  9470. search.
  9471. If S is surrounded by forward slashes, it is interpreted as
  9472. a regular expression. In Org mode files, this will create an
  9473. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9474. to list matches. If the current buffer is in `dired-mode', grep
  9475. will be used to search in all files.
  9476. When AVOID-POS is given, ignore matches near that position.
  9477. When optional argument STEALTH is non-nil, do not modify
  9478. visibility around point, thus ignoring `org-show-context-detail'
  9479. variable.
  9480. Search is case-insensitive and ignores white spaces. Return type
  9481. of matched result, which is either `dedicated' or `fuzzy'."
  9482. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9483. (let* ((case-fold-search t)
  9484. (origin (point))
  9485. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9486. (starred (eq (string-to-char normalized) ?*))
  9487. (words (split-string (if starred (substring s 1) s)))
  9488. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9489. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9490. type)
  9491. (cond
  9492. ;; Check if there are any special search functions.
  9493. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9494. ((eq (string-to-char s) ?#)
  9495. ;; Look for a custom ID S if S starts with "#".
  9496. (let* ((id (substring normalized 1))
  9497. (match (org-find-property "CUSTOM_ID" id)))
  9498. (if match (progn (goto-char match) (setf type 'dedicated))
  9499. (error "No match for custom ID: %s" id))))
  9500. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9501. ;; Look for coderef targets if S is enclosed within parenthesis.
  9502. (let ((coderef (match-string-no-properties 1 normalized))
  9503. (re (substring s-single-re 1 -1)))
  9504. (goto-char (point-min))
  9505. (catch :coderef-match
  9506. (while (re-search-forward re nil t)
  9507. (let ((element (org-element-at-point)))
  9508. (when (and (memq (org-element-type element)
  9509. '(example-block src-block))
  9510. ;; Build proper regexp according to current
  9511. ;; block's label format.
  9512. (let ((label-fmt
  9513. (regexp-quote
  9514. (or (org-element-property :label-fmt element)
  9515. org-coderef-label-format))))
  9516. (save-excursion
  9517. (beginning-of-line)
  9518. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9519. (format label-fmt coderef))))))
  9520. (setq type 'dedicated)
  9521. (goto-char (match-beginning 1))
  9522. (throw :coderef-match nil))))
  9523. (goto-char origin)
  9524. (error "No match for coderef: %s" coderef))))
  9525. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9526. ;; Look for a regular expression.
  9527. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9528. (match-string 1 s)))
  9529. ;; From here, we handle fuzzy links.
  9530. ;;
  9531. ;; Look for targets, only if not in a headline search.
  9532. ((and (not starred)
  9533. (let ((target (format "<<%s>>" s-multi-re)))
  9534. (catch :target-match
  9535. (goto-char (point-min))
  9536. (while (re-search-forward target nil t)
  9537. (backward-char)
  9538. (let ((context (org-element-context)))
  9539. (when (eq (org-element-type context) 'target)
  9540. (setq type 'dedicated)
  9541. (goto-char (org-element-property :begin context))
  9542. (throw :target-match t))))
  9543. nil))))
  9544. ;; Look for elements named after S, only if not in a headline
  9545. ;; search.
  9546. ((and (not starred)
  9547. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9548. (catch :name-match
  9549. (goto-char (point-min))
  9550. (while (re-search-forward name nil t)
  9551. (let ((element (org-element-at-point)))
  9552. (when (equal words
  9553. (split-string
  9554. (org-element-property :name element)))
  9555. (setq type 'dedicated)
  9556. (beginning-of-line)
  9557. (throw :name-match t))))
  9558. nil))))
  9559. ;; Regular text search. Prefer headlines in Org mode buffers.
  9560. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9561. ;; statistics cookies and tags.
  9562. ((and (derived-mode-p 'org-mode)
  9563. (let ((title-re
  9564. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9565. org-outline-regexp-bol
  9566. org-comment-string
  9567. (mapconcat #'regexp-quote words ".+")))
  9568. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9569. (comment-re (eval-when-compile
  9570. (format "\\`%s[ \t]+" org-comment-string))))
  9571. (goto-char (point-min))
  9572. (catch :found
  9573. (while (re-search-forward title-re nil t)
  9574. (when (equal words
  9575. (split-string
  9576. (replace-regexp-in-string
  9577. cookie-re ""
  9578. (replace-regexp-in-string
  9579. comment-re "" (org-get-heading t t t)))))
  9580. (throw :found t)))
  9581. nil)))
  9582. (beginning-of-line)
  9583. (setq type 'dedicated))
  9584. ;; Offer to create non-existent headline depending on
  9585. ;; `org-link-search-must-match-exact-headline'.
  9586. ((and (derived-mode-p 'org-mode)
  9587. (not org-link-search-inhibit-query)
  9588. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9589. (yes-or-no-p "No match - create this as a new heading? "))
  9590. (goto-char (point-max))
  9591. (unless (bolp) (newline))
  9592. (org-insert-heading nil t t)
  9593. (insert s "\n")
  9594. (beginning-of-line 0))
  9595. ;; Only headlines are looked after. No need to process
  9596. ;; further: throw an error.
  9597. ((and (derived-mode-p 'org-mode)
  9598. (or starred org-link-search-must-match-exact-headline))
  9599. (goto-char origin)
  9600. (error "No match for fuzzy expression: %s" normalized))
  9601. ;; Regular text search.
  9602. ((catch :fuzzy-match
  9603. (goto-char (point-min))
  9604. (while (re-search-forward s-multi-re nil t)
  9605. ;; Skip match if it contains AVOID-POS or it is included in
  9606. ;; a link with a description but outside the description.
  9607. (unless (or (and avoid-pos
  9608. (<= (match-beginning 0) avoid-pos)
  9609. (> (match-end 0) avoid-pos))
  9610. (and (save-match-data
  9611. (org-in-regexp org-bracket-link-regexp))
  9612. (match-beginning 3)
  9613. (or (> (match-beginning 3) (point))
  9614. (<= (match-end 3) (point)))
  9615. (org-element-lineage
  9616. (save-match-data (org-element-context))
  9617. '(link) t)))
  9618. (goto-char (match-beginning 0))
  9619. (setq type 'fuzzy)
  9620. (throw :fuzzy-match t)))
  9621. nil))
  9622. ;; All failed. Throw an error.
  9623. (t (goto-char origin)
  9624. (error "No match for fuzzy expression: %s" normalized)))
  9625. ;; Disclose surroundings of match, if appropriate.
  9626. (when (and (derived-mode-p 'org-mode) (not stealth))
  9627. (org-show-context 'link-search))
  9628. type))
  9629. (defun org-get-buffer-for-internal-link (buffer)
  9630. "Return a buffer to be used for displaying the link target of internal links."
  9631. (cond
  9632. ((not org-display-internal-link-with-indirect-buffer)
  9633. buffer)
  9634. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9635. (message "Buffer is already a clone, not making another one")
  9636. ;; we also do not modify visibility in this case
  9637. buffer)
  9638. (t ; make a new indirect buffer for displaying the link
  9639. (let* ((bn (buffer-name buffer))
  9640. (ibn (concat bn "(Clone)"))
  9641. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9642. (with-current-buffer ib (org-overview))
  9643. ib))))
  9644. (defun org-do-occur (regexp &optional cleanup)
  9645. "Call the Emacs command `occur'.
  9646. If CLEANUP is non-nil, remove the printout of the regular expression
  9647. in the *Occur* buffer. This is useful if the regex is long and not useful
  9648. to read."
  9649. (occur regexp)
  9650. (when cleanup
  9651. (let ((cwin (selected-window)) win beg end)
  9652. (when (setq win (get-buffer-window "*Occur*"))
  9653. (select-window win))
  9654. (goto-char (point-min))
  9655. (when (re-search-forward "match[a-z]+" nil t)
  9656. (setq beg (match-end 0))
  9657. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9658. (setq end (1- (match-beginning 0)))))
  9659. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9660. (goto-char (point-min))
  9661. (select-window cwin))))
  9662. ;;; The mark ring for links jumps
  9663. (defvar org-mark-ring nil
  9664. "Mark ring for positions before jumps in Org mode.")
  9665. (defvar org-mark-ring-last-goto nil
  9666. "Last position in the mark ring used to go back.")
  9667. ;; Fill and close the ring
  9668. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9669. (dotimes (_ org-mark-ring-length)
  9670. (push (make-marker) org-mark-ring))
  9671. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9672. org-mark-ring)
  9673. (defun org-mark-ring-push (&optional pos buffer)
  9674. "Put the current position or POS into the mark ring and rotate it."
  9675. (interactive)
  9676. (setq pos (or pos (point)))
  9677. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9678. (move-marker (car org-mark-ring)
  9679. (or pos (point))
  9680. (or buffer (current-buffer)))
  9681. (message "%s"
  9682. (substitute-command-keys
  9683. "Position saved to mark ring, go back with \
  9684. `\\[org-mark-ring-goto]'.")))
  9685. (defun org-mark-ring-goto (&optional n)
  9686. "Jump to the previous position in the mark ring.
  9687. With prefix arg N, jump back that many stored positions. When
  9688. called several times in succession, walk through the entire ring.
  9689. Org mode commands jumping to a different position in the current file,
  9690. or to another Org file, automatically push the old position onto the ring."
  9691. (interactive "p")
  9692. (let (p m)
  9693. (if (eq last-command this-command)
  9694. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9695. (setq p org-mark-ring))
  9696. (setq org-mark-ring-last-goto p)
  9697. (setq m (car p))
  9698. (pop-to-buffer-same-window (marker-buffer m))
  9699. (goto-char m)
  9700. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9701. (defun org-add-angle-brackets (s)
  9702. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9703. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9704. s)
  9705. ;;; Following specific links
  9706. (defvar org-agenda-buffer-tmp-name)
  9707. (defvar org-agenda-start-on-weekday)
  9708. (defun org-follow-timestamp-link ()
  9709. "Open an agenda view for the time-stamp date/range at point."
  9710. (cond
  9711. ((org-at-date-range-p t)
  9712. (let ((org-agenda-start-on-weekday)
  9713. (t1 (match-string 1))
  9714. (t2 (match-string 2)) tt1 tt2)
  9715. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9716. tt2 (time-to-days (org-time-string-to-time t2)))
  9717. (let ((org-agenda-buffer-tmp-name
  9718. (format "*Org Agenda(a:%s)"
  9719. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9720. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9721. ((org-at-timestamp-p 'lax)
  9722. (let ((org-agenda-buffer-tmp-name
  9723. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9724. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9725. (substring (match-string 1) 0 10)))
  9726. 1)))
  9727. (t (error "This should not happen"))))
  9728. ;;; Following file links
  9729. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9730. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9731. (declare-function mailcap-mime-info
  9732. "mailcap" (string &optional request no-decode))
  9733. (defvar org-wait nil)
  9734. (defun org-open-file (path &optional in-emacs line search)
  9735. "Open the file at PATH.
  9736. First, this expands any special file name abbreviations. Then the
  9737. configuration variable `org-file-apps' is checked if it contains an
  9738. entry for this file type, and if yes, the corresponding command is launched.
  9739. If no application is found, Emacs simply visits the file.
  9740. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9741. With a double \\[universal-argument] \\[universal-argument] \
  9742. prefix arg, Org tries to avoid opening in Emacs
  9743. and to use an external application to visit the file.
  9744. Optional LINE specifies a line to go to, optional SEARCH a string
  9745. to search for. If LINE or SEARCH is given, the file will be
  9746. opened in Emacs, unless an entry from org-file-apps that makes
  9747. use of groups in a regexp matches.
  9748. If you want to change the way frames are used when following a
  9749. link, please customize `org-link-frame-setup'.
  9750. If the file does not exist, an error is thrown."
  9751. (let* ((file (if (equal path "")
  9752. buffer-file-name
  9753. (substitute-in-file-name (expand-file-name path))))
  9754. (file-apps (append org-file-apps (org-default-apps)))
  9755. (apps (cl-remove-if
  9756. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9757. (apps-dlink (cl-remove-if-not
  9758. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9759. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9760. (dirp (unless remp (file-directory-p file)))
  9761. (file (if (and dirp org-open-directory-means-index-dot-org)
  9762. (concat (file-name-as-directory file) "index.org")
  9763. file))
  9764. (a-m-a-p (assq 'auto-mode apps))
  9765. (dfile (downcase file))
  9766. ;; Reconstruct the original link from the PATH, LINE and
  9767. ;; SEARCH args.
  9768. (link (cond (line (concat file "::" (number-to-string line)))
  9769. (search (concat file "::" search))
  9770. (t file)))
  9771. (dlink (downcase link))
  9772. (ext
  9773. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9774. (match-string 1 dfile)))
  9775. (save-position-maybe
  9776. (let ((old-buffer (current-buffer))
  9777. (old-pos (point))
  9778. (old-mode major-mode))
  9779. (lambda ()
  9780. (and (derived-mode-p 'org-mode)
  9781. (eq old-mode 'org-mode)
  9782. (or (not (eq old-buffer (current-buffer)))
  9783. (not (eq old-pos (point))))
  9784. (org-mark-ring-push old-pos old-buffer)))))
  9785. cmd link-match-data)
  9786. (cond
  9787. ((member in-emacs '((16) system))
  9788. (setq cmd (cdr (assq 'system apps))))
  9789. (in-emacs (setq cmd 'emacs))
  9790. (t
  9791. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9792. (and dirp (cdr (assq 'directory apps)))
  9793. ;; First, try matching against apps-dlink if we
  9794. ;; get a match here, store the match data for
  9795. ;; later.
  9796. (let ((match (assoc-default dlink apps-dlink
  9797. 'string-match)))
  9798. (if match
  9799. (progn (setq link-match-data (match-data))
  9800. match)
  9801. (progn (setq in-emacs (or in-emacs line search))
  9802. nil))) ; if we have no match in apps-dlink,
  9803. ; always open the file in emacs if line or search
  9804. ; is given (for backwards compatibility)
  9805. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9806. 'string-match)
  9807. (cdr (assoc ext apps))
  9808. (cdr (assq t apps))))))
  9809. (when (eq cmd 'system)
  9810. (setq cmd (cdr (assq 'system apps))))
  9811. (when (eq cmd 'default)
  9812. (setq cmd (cdr (assoc t apps))))
  9813. (when (eq cmd 'mailcap)
  9814. (require 'mailcap)
  9815. (mailcap-parse-mailcaps)
  9816. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9817. (command (mailcap-mime-info mime-type)))
  9818. (if (stringp command)
  9819. (setq cmd command)
  9820. (setq cmd 'emacs))))
  9821. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9822. (not (file-exists-p file))
  9823. (not org-open-non-existing-files))
  9824. (user-error "No such file: %s" file))
  9825. (cond
  9826. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9827. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9828. (while (string-match "['\"]%s['\"]" cmd)
  9829. (setq cmd (replace-match "%s" t t cmd)))
  9830. (setq cmd (replace-regexp-in-string
  9831. "%s"
  9832. (shell-quote-argument (convert-standard-filename file))
  9833. cmd
  9834. nil t))
  9835. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9836. (save-match-data
  9837. (let ((match-index 1)
  9838. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9839. (set-match-data link-match-data)
  9840. (while (<= match-index number-of-groups)
  9841. (let ((regex (concat "%" (number-to-string match-index)))
  9842. (replace-with (match-string match-index dlink)))
  9843. (while (string-match regex cmd)
  9844. (setq cmd (replace-match replace-with t t cmd))))
  9845. (setq match-index (+ match-index 1)))))
  9846. (save-window-excursion
  9847. (message "Running %s...done" cmd)
  9848. (start-process-shell-command cmd nil cmd)
  9849. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9850. ((or (stringp cmd)
  9851. (eq cmd 'emacs))
  9852. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9853. (widen)
  9854. (cond (line (org-goto-line line)
  9855. (when (derived-mode-p 'org-mode) (org-reveal)))
  9856. (search (condition-case err
  9857. (org-link-search search)
  9858. ;; Save position before error-ing out so user
  9859. ;; can easily move back to the original buffer.
  9860. (error (funcall save-position-maybe)
  9861. (error (nth 1 err)))))))
  9862. ((functionp cmd)
  9863. (save-match-data
  9864. (set-match-data link-match-data)
  9865. (condition-case nil
  9866. (funcall cmd file link)
  9867. ;; FIXME: Remove this check when most default installations
  9868. ;; of Emacs have at least Org 9.0.
  9869. ((debug wrong-number-of-arguments wrong-type-argument
  9870. invalid-function)
  9871. (user-error "Please see Org News for version 9.0 about \
  9872. `org-file-apps'--Lisp error: %S" cmd)))))
  9873. ((consp cmd)
  9874. ;; FIXME: Remove this check when most default installations of
  9875. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9876. ;; fall back to `org-link-frame-setup' for an old usage of
  9877. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9878. (user-error "Please see Org News for version 9.0 about \
  9879. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9880. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9881. (funcall save-position-maybe)))
  9882. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9883. "This function returns non-nil if `entry' uses a regular
  9884. expression which should be matched against the whole link by
  9885. org-open-file.
  9886. It assumes that is the case when the entry uses a regular
  9887. expression which has at least one grouping construct and the
  9888. action is either a lisp form or a command string containing
  9889. `%1', i.e. using at least one subexpression match as a
  9890. parameter."
  9891. (let ((selector (car entry))
  9892. (action (cdr entry)))
  9893. (if (stringp selector)
  9894. (and (> (regexp-opt-depth selector) 0)
  9895. (or (and (stringp action)
  9896. (string-match "%[0-9]" action))
  9897. (consp action)))
  9898. nil)))
  9899. (defun org-default-apps ()
  9900. "Return the default applications for this operating system."
  9901. (cond
  9902. ((eq system-type 'darwin)
  9903. org-file-apps-defaults-macosx)
  9904. ((eq system-type 'windows-nt)
  9905. org-file-apps-defaults-windowsnt)
  9906. (t org-file-apps-defaults-gnu)))
  9907. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9908. "Convert extensions to regular expressions in the cars of LIST.
  9909. Also, weed out any non-string entries, because the return value is used
  9910. only for regexp matching.
  9911. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9912. point to the symbol `emacs', indicating that the file should
  9913. be opened in Emacs."
  9914. (append
  9915. (delq nil
  9916. (mapcar (lambda (x)
  9917. (unless (not (stringp (car x)))
  9918. (if (string-match "\\W" (car x))
  9919. x
  9920. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9921. list))
  9922. (when add-auto-mode
  9923. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9924. (defvar ange-ftp-name-format)
  9925. (defun org-file-remote-p (file)
  9926. "Test whether FILE specifies a location on a remote system.
  9927. Return non-nil if the location is indeed remote.
  9928. For example, the filename \"/user@host:/foo\" specifies a location
  9929. on the system \"/user@host:\"."
  9930. (cond ((fboundp 'file-remote-p)
  9931. (file-remote-p file))
  9932. ((fboundp 'tramp-handle-file-remote-p)
  9933. (tramp-handle-file-remote-p file))
  9934. ((and (boundp 'ange-ftp-name-format)
  9935. (string-match (car ange-ftp-name-format) file))
  9936. t)))
  9937. ;;;; Refiling
  9938. (defun org-get-org-file ()
  9939. "Read a filename, with default directory `org-directory'."
  9940. (let ((default (or org-default-notes-file remember-data-file)))
  9941. (read-file-name (format "File name [%s]: " default)
  9942. (file-name-as-directory org-directory)
  9943. default)))
  9944. (defun org-notes-order-reversed-p ()
  9945. "Check if the current file should receive notes in reversed order."
  9946. (cond
  9947. ((not org-reverse-note-order) nil)
  9948. ((eq t org-reverse-note-order) t)
  9949. ((not (listp org-reverse-note-order)) nil)
  9950. (t (catch 'exit
  9951. (dolist (entry org-reverse-note-order)
  9952. (when (string-match (car entry) buffer-file-name)
  9953. (throw 'exit (cdr entry))))))))
  9954. (defvar org-refile-target-table nil
  9955. "The list of refile targets, created by `org-refile'.")
  9956. (defvar org-agenda-new-buffers nil
  9957. "Buffers created to visit agenda files.")
  9958. (defvar org-refile-cache nil
  9959. "Cache for refile targets.")
  9960. (defvar org-refile-markers nil
  9961. "All the markers used for caching refile locations.")
  9962. (defun org-refile-marker (pos)
  9963. "Get a new refile marker, but only if caching is in use."
  9964. (if (not org-refile-use-cache)
  9965. pos
  9966. (let ((m (make-marker)))
  9967. (move-marker m pos)
  9968. (push m org-refile-markers)
  9969. m)))
  9970. (defun org-refile-cache-clear ()
  9971. "Clear the refile cache and disable all the markers."
  9972. (dolist (m org-refile-markers) (move-marker m nil))
  9973. (setq org-refile-markers nil)
  9974. (setq org-refile-cache nil)
  9975. (message "Refile cache has been cleared"))
  9976. (defun org-refile-cache-check-set (set)
  9977. "Check if all the markers in the cache still have live buffers."
  9978. (let (marker)
  9979. (catch 'exit
  9980. (while (and set (setq marker (nth 3 (pop set))))
  9981. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9982. (when (and marker (null (marker-buffer marker)))
  9983. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9984. (sit-for 3)
  9985. (throw 'exit nil)))
  9986. t)))
  9987. (defun org-refile-cache-put (set &rest identifiers)
  9988. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9989. (let* ((key (sha1 (prin1-to-string identifiers)))
  9990. (entry (assoc key org-refile-cache)))
  9991. (if entry
  9992. (setcdr entry set)
  9993. (push (cons key set) org-refile-cache))))
  9994. (defun org-refile-cache-get (&rest identifiers)
  9995. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9996. (cond
  9997. ((not org-refile-cache) nil)
  9998. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9999. (t
  10000. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10001. org-refile-cache))))
  10002. (and set (org-refile-cache-check-set set) set)))))
  10003. (defvar org-outline-path-cache nil
  10004. "Alist between buffer positions and outline paths.
  10005. It value is an alist (POSITION . PATH) where POSITION is the
  10006. buffer position at the beginning of an entry and PATH is a list
  10007. of strings describing the outline path for that entry, in reverse
  10008. order.")
  10009. (defun org-refile-get-targets (&optional default-buffer)
  10010. "Produce a table with refile targets."
  10011. (let ((case-fold-search nil)
  10012. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10013. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10014. targets tgs files desc descre)
  10015. (message "Getting targets...")
  10016. (with-current-buffer (or default-buffer (current-buffer))
  10017. (dolist (entry entries)
  10018. (setq files (car entry) desc (cdr entry))
  10019. (cond
  10020. ((null files) (setq files (list (current-buffer))))
  10021. ((eq files 'org-agenda-files)
  10022. (setq files (org-agenda-files 'unrestricted)))
  10023. ((and (symbolp files) (fboundp files))
  10024. (setq files (funcall files)))
  10025. ((and (symbolp files) (boundp files))
  10026. (setq files (symbol-value files))))
  10027. (when (stringp files) (setq files (list files)))
  10028. (cond
  10029. ((eq (car desc) :tag)
  10030. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10031. ((eq (car desc) :todo)
  10032. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10033. ((eq (car desc) :regexp)
  10034. (setq descre (cdr desc)))
  10035. ((eq (car desc) :level)
  10036. (setq descre (concat "^\\*\\{" (number-to-string
  10037. (if org-odd-levels-only
  10038. (1- (* 2 (cdr desc)))
  10039. (cdr desc)))
  10040. "\\}[ \t]")))
  10041. ((eq (car desc) :maxlevel)
  10042. (setq descre (concat "^\\*\\{1," (number-to-string
  10043. (if org-odd-levels-only
  10044. (1- (* 2 (cdr desc)))
  10045. (cdr desc)))
  10046. "\\}[ \t]")))
  10047. (t (error "Bad refiling target description %s" desc)))
  10048. (dolist (f files)
  10049. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10050. (or
  10051. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10052. (progn
  10053. (when (bufferp f)
  10054. (setq f (buffer-file-name (buffer-base-buffer f))))
  10055. (setq f (and f (expand-file-name f)))
  10056. (when (eq org-refile-use-outline-path 'file)
  10057. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10058. (when (eq org-refile-use-outline-path 'buffer-name)
  10059. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10060. (when (eq org-refile-use-outline-path 'full-file-path)
  10061. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10062. (org-with-wide-buffer
  10063. (goto-char (point-min))
  10064. (setq org-outline-path-cache nil)
  10065. (while (re-search-forward descre nil t)
  10066. (beginning-of-line)
  10067. (let ((case-fold-search nil))
  10068. (looking-at org-complex-heading-regexp))
  10069. (let ((begin (point))
  10070. (heading (match-string-no-properties 4)))
  10071. (unless (or (and
  10072. org-refile-target-verify-function
  10073. (not
  10074. (funcall org-refile-target-verify-function)))
  10075. (not heading))
  10076. (let ((re (format org-complex-heading-regexp-format
  10077. (regexp-quote heading)))
  10078. (target
  10079. (if (not org-refile-use-outline-path) heading
  10080. (mapconcat
  10081. #'identity
  10082. (append
  10083. (pcase org-refile-use-outline-path
  10084. (`file (list (file-name-nondirectory
  10085. (buffer-file-name
  10086. (buffer-base-buffer)))))
  10087. (`full-file-path
  10088. (list (buffer-file-name
  10089. (buffer-base-buffer))))
  10090. (`buffer-name
  10091. (list (buffer-name
  10092. (buffer-base-buffer))))
  10093. (_ nil))
  10094. (mapcar (lambda (s) (replace-regexp-in-string
  10095. "/" "\\/" s nil t))
  10096. (org-get-outline-path t t)))
  10097. "/"))))
  10098. (push (list target f re (org-refile-marker (point)))
  10099. tgs)))
  10100. (when (= (point) begin)
  10101. ;; Verification function has not moved point.
  10102. (end-of-line)))))))
  10103. (when org-refile-use-cache
  10104. (org-refile-cache-put tgs (buffer-file-name) descre))
  10105. (setq targets (append tgs targets))))))
  10106. (message "Getting targets...done")
  10107. (delete-dups (nreverse targets))))
  10108. (defun org--get-outline-path-1 (&optional use-cache)
  10109. "Return outline path to current headline.
  10110. Outline path is a list of strings, in reverse order. When
  10111. optional argument USE-CACHE is non-nil, make use of a cache. See
  10112. `org-get-outline-path' for details.
  10113. Assume buffer is widened and point is on a headline."
  10114. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10115. (let ((p (point))
  10116. (heading (let ((case-fold-search nil))
  10117. (looking-at org-complex-heading-regexp)
  10118. (if (not (match-end 4)) ""
  10119. ;; Remove statistics cookies.
  10120. (org-trim
  10121. (org-link-display-format
  10122. (replace-regexp-in-string
  10123. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10124. (match-string-no-properties 4))))))))
  10125. (if (org-up-heading-safe)
  10126. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10127. (when use-cache
  10128. (push (cons p path) org-outline-path-cache))
  10129. path)
  10130. ;; This is a new root node. Since we assume we are moving
  10131. ;; forward, we can drop previous cache so as to limit number
  10132. ;; of associations there.
  10133. (let ((path (list heading)))
  10134. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10135. path)))))
  10136. (defun org-get-outline-path (&optional with-self use-cache)
  10137. "Return the outline path to the current entry.
  10138. An outline path is a list of ancestors for current headline, as
  10139. a list of strings. Statistics cookies are removed and links are
  10140. replaced with their description, if any, or their path otherwise.
  10141. When optional argument WITH-SELF is non-nil, the path also
  10142. includes the current headline.
  10143. When optional argument USE-CACHE is non-nil, cache outline paths
  10144. between calls to this function so as to avoid backtracking. This
  10145. argument is useful when planning to find more than one outline
  10146. path in the same document. In that case, there are two
  10147. conditions to satisfy:
  10148. - `org-outline-path-cache' is set to nil before starting the
  10149. process;
  10150. - outline paths are computed by increasing buffer positions."
  10151. (org-with-wide-buffer
  10152. (and (or (and with-self (org-back-to-heading t))
  10153. (org-up-heading-safe))
  10154. (reverse (org--get-outline-path-1 use-cache)))))
  10155. (defun org-format-outline-path (path &optional width prefix separator)
  10156. "Format the outline path PATH for display.
  10157. WIDTH is the maximum number of characters that is available.
  10158. PREFIX is a prefix to be included in the returned string,
  10159. such as the file name.
  10160. SEPARATOR is inserted between the different parts of the path,
  10161. the default is \"/\"."
  10162. (setq width (or width 79))
  10163. (setq path (delq nil path))
  10164. (unless (> width 0)
  10165. (user-error "Argument `width' must be positive"))
  10166. (setq separator (or separator "/"))
  10167. (let* ((org-odd-levels-only nil)
  10168. (fpath (concat
  10169. prefix (and prefix path separator)
  10170. (mapconcat
  10171. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10172. (cl-loop for head in path
  10173. for n from 0
  10174. collect (org-add-props
  10175. head nil 'face
  10176. (nth (% n org-n-level-faces) org-level-faces)))
  10177. separator))))
  10178. (when (> (length fpath) width)
  10179. (if (< width 7)
  10180. ;; It's unlikely that `width' will be this small, but don't
  10181. ;; waste characters by adding ".." if it is.
  10182. (setq fpath (substring fpath 0 width))
  10183. (setf (substring fpath (- width 2)) "..")))
  10184. fpath))
  10185. (defun org-display-outline-path (&optional file current separator just-return-string)
  10186. "Display the current outline path in the echo area.
  10187. If FILE is non-nil, prepend the output with the file name.
  10188. If CURRENT is non-nil, append the current heading to the output.
  10189. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10190. the different parts of the path and defaults to \"/\".
  10191. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10192. (interactive "P")
  10193. (let* (case-fold-search
  10194. (bfn (buffer-file-name (buffer-base-buffer)))
  10195. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10196. res)
  10197. (when current (setq path (append path
  10198. (save-excursion
  10199. (org-back-to-heading t)
  10200. (when (looking-at org-complex-heading-regexp)
  10201. (list (match-string 4)))))))
  10202. (setq res
  10203. (org-format-outline-path
  10204. path
  10205. (1- (frame-width))
  10206. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10207. separator))
  10208. (if just-return-string
  10209. (org-no-properties res)
  10210. (org-unlogged-message "%s" res))))
  10211. (defvar org-refile-history nil
  10212. "History for refiling operations.")
  10213. (defvar org-after-refile-insert-hook nil
  10214. "Hook run after `org-refile' has inserted its stuff at the new location.
  10215. Note that this is still *before* the stuff will be removed from
  10216. the *old* location.")
  10217. (defvar org-capture-last-stored-marker)
  10218. (defvar org-refile-keep nil
  10219. "Non-nil means `org-refile' will copy instead of refile.")
  10220. (defun org-copy ()
  10221. "Like `org-refile', but copy."
  10222. (interactive)
  10223. (let ((org-refile-keep t))
  10224. (funcall 'org-refile nil nil nil "Copy")))
  10225. (defun org-refile (&optional arg default-buffer rfloc msg)
  10226. "Move the entry or entries at point to another heading.
  10227. The list of target headings is compiled using the information in
  10228. `org-refile-targets', which see.
  10229. At the target location, the entry is filed as a subitem of the
  10230. target heading. Depending on `org-reverse-note-order', the new
  10231. subitem will either be the first or the last subitem.
  10232. If there is an active region, all entries in that region will be
  10233. refiled. However, the region must fulfill the requirement that
  10234. the first heading sets the top-level of the moved text.
  10235. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10236. location
  10237. and not actually move anything.
  10238. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10239. location where the last
  10240. refiling operation has put the subtree.
  10241. With a numeric prefix argument of `2', refile to the running clock.
  10242. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10243. being set to t and copy to the target location, don't move it.
  10244. Beware that keeping refiled entries may result in duplicated ID
  10245. properties.
  10246. RFLOC can be a refile location obtained in a different way.
  10247. MSG is a string to replace \"Refile\" in the default prompt with
  10248. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10249. See also `org-refile-use-outline-path'.
  10250. If you are using target caching (see `org-refile-use-cache'), you
  10251. have to clear the target cache in order to find new targets.
  10252. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10253. prefix argument (`C-u C-u C-u C-c C-w')."
  10254. (interactive "P")
  10255. (if (member arg '(0 (64)))
  10256. (org-refile-cache-clear)
  10257. (let* ((actionmsg (cond (msg msg)
  10258. ((equal arg 3) "Refile (and keep)")
  10259. (t "Refile")))
  10260. (regionp (org-region-active-p))
  10261. (region-start (and regionp (region-beginning)))
  10262. (region-end (and regionp (region-end)))
  10263. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10264. pos it nbuf file level reversed)
  10265. (setq last-command nil)
  10266. (when regionp
  10267. (goto-char region-start)
  10268. (or (bolp) (goto-char (point-at-bol)))
  10269. (setq region-start (point))
  10270. (unless (or (org-kill-is-subtree-p
  10271. (buffer-substring region-start region-end))
  10272. (prog1 org-refile-active-region-within-subtree
  10273. (let ((s (point-at-eol)))
  10274. (org-toggle-heading)
  10275. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10276. (user-error "The region is not a (sequence of) subtree(s)")))
  10277. (if (equal arg '(16))
  10278. (org-refile-goto-last-stored)
  10279. (when (or
  10280. (and (equal arg 2)
  10281. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10282. (prog1
  10283. (setq it (list (or org-clock-heading "running clock")
  10284. (buffer-file-name
  10285. (marker-buffer org-clock-hd-marker))
  10286. ""
  10287. (marker-position org-clock-hd-marker)))
  10288. (setq arg nil)))
  10289. (setq it
  10290. (or rfloc
  10291. (let (heading-text)
  10292. (save-excursion
  10293. (unless (and arg (listp arg))
  10294. (org-back-to-heading t)
  10295. (setq heading-text
  10296. (replace-regexp-in-string
  10297. org-bracket-link-regexp
  10298. "\\3"
  10299. (or (nth 4 (org-heading-components))
  10300. ""))))
  10301. (org-refile-get-location
  10302. (cond ((and arg (listp arg)) "Goto")
  10303. (regionp (concat actionmsg " region to"))
  10304. (t (concat actionmsg " subtree \""
  10305. heading-text "\" to")))
  10306. default-buffer
  10307. (and (not (equal '(4) arg))
  10308. org-refile-allow-creating-parent-nodes)))))))
  10309. (setq file (nth 1 it)
  10310. pos (nth 3 it))
  10311. (when (and (not arg)
  10312. pos
  10313. (equal (buffer-file-name) file)
  10314. (if regionp
  10315. (and (>= pos region-start)
  10316. (<= pos region-end))
  10317. (and (>= pos (point))
  10318. (< pos (save-excursion
  10319. (org-end-of-subtree t t))))))
  10320. (error "Cannot refile to position inside the tree or region"))
  10321. (setq nbuf (or (find-buffer-visiting file)
  10322. (find-file-noselect file)))
  10323. (if (and arg (not (equal arg 3)))
  10324. (progn
  10325. (pop-to-buffer-same-window nbuf)
  10326. (goto-char (cond (pos)
  10327. ((org-notes-order-reversed-p) (point-min))
  10328. (t (point-max))))
  10329. (org-show-context 'org-goto))
  10330. (if regionp
  10331. (progn
  10332. (org-kill-new (buffer-substring region-start region-end))
  10333. (org-save-markers-in-region region-start region-end))
  10334. (org-copy-subtree 1 nil t))
  10335. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10336. (find-file-noselect file)))
  10337. (setq reversed (org-notes-order-reversed-p))
  10338. (org-with-wide-buffer
  10339. (if pos
  10340. (progn
  10341. (goto-char pos)
  10342. (setq level (org-get-valid-level (funcall outline-level) 1))
  10343. (goto-char
  10344. (if reversed
  10345. (or (outline-next-heading) (point-max))
  10346. (or (save-excursion (org-get-next-sibling))
  10347. (org-end-of-subtree t t)
  10348. (point-max)))))
  10349. (setq level 1)
  10350. (if (not reversed)
  10351. (goto-char (point-max))
  10352. (goto-char (point-min))
  10353. (or (outline-next-heading) (goto-char (point-max)))))
  10354. (unless (bolp) (newline))
  10355. (org-paste-subtree level nil nil t)
  10356. (when org-log-refile
  10357. (org-add-log-setup 'refile nil nil org-log-refile)
  10358. (unless (eq org-log-refile 'note)
  10359. (save-excursion (org-add-log-note))))
  10360. (and org-auto-align-tags
  10361. (let ((org-loop-over-headlines-in-active-region nil))
  10362. (org-set-tags nil t)))
  10363. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10364. :last-refile)))
  10365. (when bookmark-name
  10366. (with-demoted-errors
  10367. (bookmark-set bookmark-name))))
  10368. ;; If we are refiling for capture, make sure that the
  10369. ;; last-capture pointers point here
  10370. (when (bound-and-true-p org-capture-is-refiling)
  10371. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10372. :last-capture-marker)))
  10373. (when bookmark-name
  10374. (with-demoted-errors
  10375. (bookmark-set bookmark-name))))
  10376. (move-marker org-capture-last-stored-marker (point)))
  10377. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10378. (run-hooks 'org-after-refile-insert-hook)))
  10379. (unless org-refile-keep
  10380. (if regionp
  10381. (delete-region (point) (+ (point) (- region-end region-start)))
  10382. (delete-region
  10383. (and (org-back-to-heading t) (point))
  10384. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10385. (when (featurep 'org-inlinetask)
  10386. (org-inlinetask-remove-END-maybe))
  10387. (setq org-markers-to-move nil)
  10388. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10389. (defun org-refile-goto-last-stored ()
  10390. "Go to the location where the last refile was stored."
  10391. (interactive)
  10392. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10393. (message "This is the location of the last refile"))
  10394. (defun org-refile--get-location (refloc tbl)
  10395. "When user refile to REFLOC, find the associated target in TBL.
  10396. Also check `org-refile-target-table'."
  10397. (car (delq
  10398. nil
  10399. (mapcar
  10400. (lambda (r) (or (assoc r tbl)
  10401. (assoc r org-refile-target-table)))
  10402. (list (replace-regexp-in-string "/$" "" refloc)
  10403. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10404. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10405. "Prompt the user for a refile location, using PROMPT.
  10406. PROMPT should not be suffixed with a colon and a space, because
  10407. this function appends the default value from
  10408. `org-refile-history' automatically, if that is not empty."
  10409. (let ((org-refile-targets org-refile-targets)
  10410. (org-refile-use-outline-path org-refile-use-outline-path))
  10411. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10412. (unless org-refile-target-table
  10413. (user-error "No refile targets"))
  10414. (let* ((cbuf (current-buffer))
  10415. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10416. (cfunc (if (and org-refile-use-outline-path
  10417. org-outline-path-complete-in-steps)
  10418. #'org-olpath-completing-read
  10419. #'completing-read))
  10420. (extra (if org-refile-use-outline-path "/" ""))
  10421. (cbnex (concat (buffer-name) extra))
  10422. (filename (and cfn (expand-file-name cfn)))
  10423. (tbl (mapcar
  10424. (lambda (x)
  10425. (if (and (not (member org-refile-use-outline-path
  10426. '(file full-file-path)))
  10427. (not (equal filename (nth 1 x))))
  10428. (cons (concat (car x) extra " ("
  10429. (file-name-nondirectory (nth 1 x)) ")")
  10430. (cdr x))
  10431. (cons (concat (car x) extra) (cdr x))))
  10432. org-refile-target-table))
  10433. (completion-ignore-case t)
  10434. cdef
  10435. (prompt (concat prompt
  10436. (or (and (car org-refile-history)
  10437. (concat " (default " (car org-refile-history) ")"))
  10438. (and (assoc cbnex tbl) (setq cdef cbnex)
  10439. (concat " (default " cbnex ")"))) ": "))
  10440. pa answ parent-target child parent old-hist)
  10441. (setq old-hist org-refile-history)
  10442. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10443. nil 'org-refile-history (or cdef (car org-refile-history))))
  10444. (if (setq pa (org-refile--get-location answ tbl))
  10445. (progn
  10446. (org-refile-check-position pa)
  10447. (when (or (not org-refile-history)
  10448. (not (eq old-hist org-refile-history))
  10449. (not (equal (car pa) (car org-refile-history))))
  10450. (setq org-refile-history
  10451. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10452. org-refile-history
  10453. (cdr org-refile-history))))
  10454. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10455. (pop org-refile-history)))
  10456. pa)
  10457. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10458. (progn
  10459. (setq parent (match-string 1 answ)
  10460. child (match-string 2 answ))
  10461. (setq parent-target (org-refile--get-location parent tbl))
  10462. (when (and parent-target
  10463. (or (eq new-nodes t)
  10464. (and (eq new-nodes 'confirm)
  10465. (y-or-n-p (format "Create new node \"%s\"? "
  10466. child)))))
  10467. (org-refile-new-child parent-target child)))
  10468. (user-error "Invalid target location")))))
  10469. (declare-function org-string-nw-p "org-macs" (s))
  10470. (defun org-refile-check-position (refile-pointer)
  10471. "Check if the refile pointer matches the headline to which it points."
  10472. (let* ((file (nth 1 refile-pointer))
  10473. (re (nth 2 refile-pointer))
  10474. (pos (nth 3 refile-pointer))
  10475. buffer)
  10476. (if (and (not (markerp pos)) (not file))
  10477. (user-error "Please indicate a target file in the refile path")
  10478. (when (org-string-nw-p re)
  10479. (setq buffer (if (markerp pos)
  10480. (marker-buffer pos)
  10481. (or (find-buffer-visiting file)
  10482. (find-file-noselect file))))
  10483. (with-current-buffer buffer
  10484. (org-with-wide-buffer
  10485. (goto-char pos)
  10486. (beginning-of-line 1)
  10487. (unless (looking-at-p re)
  10488. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10489. (defun org-refile-new-child (parent-target child)
  10490. "Use refile target PARENT-TARGET to add new CHILD below it."
  10491. (unless parent-target
  10492. (error "Cannot find parent for new node"))
  10493. (let ((file (nth 1 parent-target))
  10494. (pos (nth 3 parent-target))
  10495. level)
  10496. (with-current-buffer (or (find-buffer-visiting file)
  10497. (find-file-noselect file))
  10498. (org-with-wide-buffer
  10499. (if pos
  10500. (goto-char pos)
  10501. (goto-char (point-max))
  10502. (unless (bolp) (newline)))
  10503. (when (looking-at org-outline-regexp)
  10504. (setq level (funcall outline-level))
  10505. (org-end-of-subtree t t))
  10506. (org-back-over-empty-lines)
  10507. (insert "\n" (make-string
  10508. (if pos (org-get-valid-level level 1) 1) ?*)
  10509. " " child "\n")
  10510. (beginning-of-line 0)
  10511. (list (concat (car parent-target) "/" child) file "" (point))))))
  10512. (defun org-olpath-completing-read (prompt collection &rest args)
  10513. "Read an outline path like a file name."
  10514. (let ((thetable collection))
  10515. (apply #'completing-read
  10516. prompt
  10517. (lambda (string predicate &optional flag)
  10518. (cond
  10519. ((eq flag nil) (try-completion string thetable))
  10520. ((eq flag t)
  10521. (let ((l (length string)))
  10522. (mapcar (lambda (x)
  10523. (let ((r (substring x l))
  10524. (f (if (string-match " ([^)]*)$" x)
  10525. (match-string 0 x)
  10526. "")))
  10527. (if (string-match "/" r)
  10528. (concat string (substring r 0 (match-end 0)) f)
  10529. x)))
  10530. (all-completions string thetable predicate))))
  10531. ;; Exact match?
  10532. ((eq flag 'lambda) (assoc string thetable))))
  10533. args)))
  10534. ;;;; Dynamic blocks
  10535. (defun org-find-dblock (name)
  10536. "Find the first dynamic block with name NAME in the buffer.
  10537. If not found, stay at current position and return nil."
  10538. (let ((case-fold-search t) pos)
  10539. (save-excursion
  10540. (goto-char (point-min))
  10541. (setq pos (and (re-search-forward
  10542. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10543. (match-beginning 0))))
  10544. (when pos (goto-char pos))
  10545. pos))
  10546. (defun org-create-dblock (plist)
  10547. "Create a dynamic block section, with parameters taken from PLIST.
  10548. PLIST must contain a :name entry which is used as the name of the block."
  10549. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10550. (end-of-line 1)
  10551. (newline))
  10552. (let ((col (current-column))
  10553. (name (plist-get plist :name)))
  10554. (insert "#+BEGIN: " name)
  10555. (while plist
  10556. (if (eq (car plist) :name)
  10557. (setq plist (cddr plist))
  10558. (insert " " (prin1-to-string (pop plist)))))
  10559. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10560. (beginning-of-line -2)))
  10561. (defun org-prepare-dblock ()
  10562. "Prepare dynamic block for refresh.
  10563. This empties the block, puts the cursor at the insert position and returns
  10564. the property list including an extra property :name with the block name."
  10565. (unless (looking-at org-dblock-start-re)
  10566. (user-error "Not at a dynamic block"))
  10567. (let* ((begdel (1+ (match-end 0)))
  10568. (name (org-no-properties (match-string 1)))
  10569. (params (append (list :name name)
  10570. (read (concat "(" (match-string 3) ")")))))
  10571. (save-excursion
  10572. (beginning-of-line 1)
  10573. (skip-chars-forward " \t")
  10574. (setq params (plist-put params :indentation-column (current-column))))
  10575. (unless (re-search-forward org-dblock-end-re nil t)
  10576. (error "Dynamic block not terminated"))
  10577. (setq params
  10578. (append params
  10579. (list :content (buffer-substring
  10580. begdel (match-beginning 0)))))
  10581. (delete-region begdel (match-beginning 0))
  10582. (goto-char begdel)
  10583. (open-line 1)
  10584. params))
  10585. (defun org-map-dblocks (&optional command)
  10586. "Apply COMMAND to all dynamic blocks in the current buffer.
  10587. If COMMAND is not given, use `org-update-dblock'."
  10588. (let ((cmd (or command 'org-update-dblock)))
  10589. (save-excursion
  10590. (goto-char (point-min))
  10591. (while (re-search-forward org-dblock-start-re nil t)
  10592. (goto-char (match-beginning 0))
  10593. (save-excursion
  10594. (condition-case nil
  10595. (funcall cmd)
  10596. (error (message "Error during update of dynamic block"))))
  10597. (unless (re-search-forward org-dblock-end-re nil t)
  10598. (error "Dynamic block not terminated"))))))
  10599. (defun org-dblock-update (&optional arg)
  10600. "User command for updating dynamic blocks.
  10601. Update the dynamic block at point. With prefix ARG, update all dynamic
  10602. blocks in the buffer."
  10603. (interactive "P")
  10604. (if arg
  10605. (org-update-all-dblocks)
  10606. (or (looking-at org-dblock-start-re)
  10607. (org-beginning-of-dblock))
  10608. (org-update-dblock)))
  10609. (defun org-update-dblock ()
  10610. "Update the dynamic block at point.
  10611. This means to empty the block, parse for parameters and then call
  10612. the correct writing function."
  10613. (interactive)
  10614. (save-excursion
  10615. (let* ((win (selected-window))
  10616. (pos (point))
  10617. (line (org-current-line))
  10618. (params (org-prepare-dblock))
  10619. (name (plist-get params :name))
  10620. (indent (plist-get params :indentation-column))
  10621. (cmd (intern (concat "org-dblock-write:" name))))
  10622. (message "Updating dynamic block `%s' at line %d..." name line)
  10623. (funcall cmd params)
  10624. (message "Updating dynamic block `%s' at line %d...done" name line)
  10625. (goto-char pos)
  10626. (when (and indent (> indent 0))
  10627. (setq indent (make-string indent ?\ ))
  10628. (save-excursion
  10629. (select-window win)
  10630. (org-beginning-of-dblock)
  10631. (forward-line 1)
  10632. (while (not (looking-at org-dblock-end-re))
  10633. (insert indent)
  10634. (beginning-of-line 2))
  10635. (when (looking-at org-dblock-end-re)
  10636. (and (looking-at "[ \t]+")
  10637. (replace-match ""))
  10638. (insert indent)))))))
  10639. (defun org-beginning-of-dblock ()
  10640. "Find the beginning of the dynamic block at point.
  10641. Error if there is no such block at point."
  10642. (let ((pos (point))
  10643. beg)
  10644. (end-of-line 1)
  10645. (if (and (re-search-backward org-dblock-start-re nil t)
  10646. (setq beg (match-beginning 0))
  10647. (re-search-forward org-dblock-end-re nil t)
  10648. (> (match-end 0) pos))
  10649. (goto-char beg)
  10650. (goto-char pos)
  10651. (error "Not in a dynamic block"))))
  10652. (defun org-update-all-dblocks ()
  10653. "Update all dynamic blocks in the buffer.
  10654. This function can be used in a hook."
  10655. (interactive)
  10656. (when (derived-mode-p 'org-mode)
  10657. (org-map-dblocks 'org-update-dblock)))
  10658. ;;;; Completion
  10659. (declare-function org-export-backend-options "ox" (cl-x) t)
  10660. (defun org-get-export-keywords ()
  10661. "Return a list of all currently understood export keywords.
  10662. Export keywords include options, block names, attributes and
  10663. keywords relative to each registered export back-end."
  10664. (let (keywords)
  10665. (dolist (backend
  10666. (bound-and-true-p org-export-registered-backends)
  10667. (delq nil keywords))
  10668. ;; Back-end name (for keywords, like #+LATEX:)
  10669. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10670. (dolist (option-entry (org-export-backend-options backend))
  10671. ;; Back-end options.
  10672. (push (nth 1 option-entry) keywords)))))
  10673. (defconst org-options-keywords
  10674. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10675. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10676. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10677. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10678. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10679. (defcustom org-structure-template-alist
  10680. '((?a . "export ascii")
  10681. (?c . "center")
  10682. (?C . "comment")
  10683. (?e . "example")
  10684. (?E . "export")
  10685. (?h . "export html")
  10686. (?l . "export latex")
  10687. (?q . "quote")
  10688. (?s . "src")
  10689. (?v . "verse"))
  10690. "Structure completion elements.
  10691. This is an alist of characters and values. When
  10692. `org-insert-structure-template' is called, an additional key is
  10693. read. The key is first looked up in this alist, and the
  10694. corresponding structure is inserted, with \"#+BEGIN_\" and
  10695. \"#+END_\" added automatically."
  10696. :group 'org-completion
  10697. :type '(repeat
  10698. (cons (character :tag "Key")
  10699. (string :tag "Template")))
  10700. :package-version '(Org . "9.2"))
  10701. (defun org-insert-structure-template (type)
  10702. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10703. First read a character, which can be one of the keys in
  10704. `org-structure-template-alist'. When it is <TAB>, prompt the
  10705. user for a string to use. With an active region, wrap the region
  10706. in the block. Otherwise, insert an empty block."
  10707. (interactive
  10708. (list
  10709. (let* ((key (read-key "Key: "))
  10710. (struct-string
  10711. (or (cdr (assq key org-structure-template-alist))
  10712. (and (= key ?\t)
  10713. (read-string "Structure type: "))
  10714. (user-error "`%c' has no structure definition" key))))
  10715. struct-string)))
  10716. (let* ((region? (use-region-p))
  10717. (s (if region? (region-beginning) (point)))
  10718. (e (copy-marker (if region? (region-end) (point)) t))
  10719. column)
  10720. (when (string-match-p
  10721. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10722. type)
  10723. (org-escape-code-in-region s e))
  10724. (goto-char s)
  10725. (setq column (current-indentation))
  10726. (beginning-of-line)
  10727. (indent-to column)
  10728. (insert (format "#+begin_%s\n" type))
  10729. (goto-char e)
  10730. (if (bolp)
  10731. (progn
  10732. (skip-chars-backward " \n\t")
  10733. (forward-line))
  10734. (end-of-line)
  10735. (insert "\n"))
  10736. (indent-to column)
  10737. (insert (format "#+end_%s\n"
  10738. (car (split-string type))))
  10739. (when (or (not region?)
  10740. (string-match-p "src\\|\\`export\\'" type))
  10741. (goto-char s)
  10742. (end-of-line))
  10743. (set-marker e nil)))
  10744. ;;;; TODO, DEADLINE, Comments
  10745. (defun org-toggle-comment ()
  10746. "Change the COMMENT state of an entry."
  10747. (interactive)
  10748. (save-excursion
  10749. (org-back-to-heading)
  10750. (let ((case-fold-search nil))
  10751. (looking-at org-complex-heading-regexp))
  10752. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10753. (skip-chars-forward " \t")
  10754. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10755. (if (org-in-commented-heading-p t)
  10756. (delete-region (point)
  10757. (progn (search-forward " " (line-end-position) 'move)
  10758. (skip-chars-forward " \t")
  10759. (point)))
  10760. (insert org-comment-string)
  10761. (unless (eolp) (insert " ")))))
  10762. (defvar org-last-todo-state-is-todo nil
  10763. "This is non-nil when the last TODO state change led to a TODO state.
  10764. If the last change removed the TODO tag or switched to DONE, then
  10765. this is nil.")
  10766. (defvar org-setting-tags nil) ; dynamically skipped
  10767. (defvar org-todo-setup-filter-hook nil
  10768. "Hook for functions that pre-filter todo specs.
  10769. Each function takes a todo spec and returns either nil or the spec
  10770. transformed into canonical form." )
  10771. (defvar org-todo-get-default-hook nil
  10772. "Hook for functions that get a default item for todo.
  10773. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10774. nil or a string to be used for the todo mark." )
  10775. (defvar org-agenda-headline-snapshot-before-repeat)
  10776. (defun org-current-effective-time ()
  10777. "Return current time adjusted for `org-extend-today-until' variable."
  10778. (let* ((ct (org-current-time))
  10779. (dct (decode-time ct))
  10780. (ct1
  10781. (cond
  10782. (org-use-last-clock-out-time-as-effective-time
  10783. (or (org-clock-get-last-clock-out-time) ct))
  10784. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10785. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10786. (t ct))))
  10787. ct1))
  10788. (defun org-todo-yesterday (&optional arg)
  10789. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10790. (interactive "P")
  10791. (if (eq major-mode 'org-agenda-mode)
  10792. (apply 'org-agenda-todo-yesterday arg)
  10793. (let* ((org-use-effective-time t)
  10794. (hour (nth 2 (decode-time (org-current-time))))
  10795. (org-extend-today-until (1+ hour)))
  10796. (org-todo arg))))
  10797. (defvar org-block-entry-blocking ""
  10798. "First entry preventing the TODO state change.")
  10799. (defun org-cancel-repeater ()
  10800. "Cancel a repeater by setting its numeric value to zero."
  10801. (interactive)
  10802. (save-excursion
  10803. (org-back-to-heading t)
  10804. (let ((bound1 (point))
  10805. (bound0 (save-excursion (outline-next-heading) (point))))
  10806. (when (and (re-search-forward
  10807. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10808. org-deadline-time-regexp "\\)\\|\\("
  10809. org-ts-regexp "\\)")
  10810. bound0 t)
  10811. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10812. bound1 t))
  10813. (replace-match "0" t nil nil 1)))))
  10814. (defvar org-state)
  10815. (defvar org-blocked-by-checkboxes)
  10816. (defun org-todo (&optional arg)
  10817. "Change the TODO state of an item.
  10818. The state of an item is given by a keyword at the start of the heading,
  10819. like
  10820. *** TODO Write paper
  10821. *** DONE Call mom
  10822. The different keywords are specified in the variable `org-todo-keywords'.
  10823. By default the available states are \"TODO\" and \"DONE\". So, for this
  10824. example: when the item starts with TODO, it is changed to DONE.
  10825. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10826. DONE are present, add TODO at the beginning of the heading.
  10827. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10828. state.
  10829. With numeric prefix ARG, switch to that state.
  10830. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10831. next set of TODO \
  10832. keywords (nextset).
  10833. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10834. prefix, circumvent any state blocking.
  10835. With a numeric prefix arg of 0, inhibit note taking for the change.
  10836. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10837. When called through ELisp, arg is also interpreted in the following way:
  10838. `none' -> empty state
  10839. \"\" -> switch to empty state
  10840. `done' -> switch to DONE
  10841. `nextset' -> switch to the next set of keywords
  10842. `previousset' -> switch to the previous set of keywords
  10843. \"WAITING\" -> switch to the specified keyword, but only if it
  10844. really is a member of `org-todo-keywords'."
  10845. (interactive "P")
  10846. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10847. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10848. 'region-start-level 'region))
  10849. org-loop-over-headlines-in-active-region)
  10850. (org-map-entries
  10851. `(org-todo ,arg)
  10852. org-loop-over-headlines-in-active-region
  10853. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10854. (when (equal arg '(16)) (setq arg 'nextset))
  10855. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10856. (let ((org-blocker-hook org-blocker-hook)
  10857. commentp
  10858. case-fold-search)
  10859. (when (equal arg '(64))
  10860. (setq arg nil org-blocker-hook nil))
  10861. (when (and org-blocker-hook
  10862. (or org-inhibit-blocking
  10863. (org-entry-get nil "NOBLOCKING")))
  10864. (setq org-blocker-hook nil))
  10865. (save-excursion
  10866. (catch 'exit
  10867. (org-back-to-heading t)
  10868. (when (org-in-commented-heading-p t)
  10869. (org-toggle-comment)
  10870. (setq commentp t))
  10871. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10872. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10873. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10874. (let* ((match-data (match-data))
  10875. (startpos (point-at-bol))
  10876. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10877. (org-log-done org-log-done)
  10878. (org-log-repeat org-log-repeat)
  10879. (org-todo-log-states org-todo-log-states)
  10880. (org-inhibit-logging
  10881. (if (equal arg 0)
  10882. (progn (setq arg nil) 'note) org-inhibit-logging))
  10883. (this (match-string 1))
  10884. (hl-pos (match-beginning 0))
  10885. (head (org-get-todo-sequence-head this))
  10886. (ass (assoc head org-todo-kwd-alist))
  10887. (interpret (nth 1 ass))
  10888. (done-word (nth 3 ass))
  10889. (final-done-word (nth 4 ass))
  10890. (org-last-state (or this ""))
  10891. (completion-ignore-case t)
  10892. (member (member this org-todo-keywords-1))
  10893. (tail (cdr member))
  10894. (org-state (cond
  10895. ((and org-todo-key-trigger
  10896. (or (and (equal arg '(4))
  10897. (eq org-use-fast-todo-selection 'prefix))
  10898. (and (not arg) org-use-fast-todo-selection
  10899. (not (eq org-use-fast-todo-selection
  10900. 'prefix)))))
  10901. ;; Use fast selection.
  10902. (org-fast-todo-selection))
  10903. ((and (equal arg '(4))
  10904. (or (not org-use-fast-todo-selection)
  10905. (not org-todo-key-trigger)))
  10906. ;; Read a state with completion.
  10907. (completing-read
  10908. "State: " (mapcar #'list org-todo-keywords-1)
  10909. nil t))
  10910. ((eq arg 'right)
  10911. (if this
  10912. (if tail (car tail) nil)
  10913. (car org-todo-keywords-1)))
  10914. ((eq arg 'left)
  10915. (unless (equal member org-todo-keywords-1)
  10916. (if this
  10917. (nth (- (length org-todo-keywords-1)
  10918. (length tail) 2)
  10919. org-todo-keywords-1)
  10920. (org-last org-todo-keywords-1))))
  10921. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10922. (setq arg nil))) ;hack to fall back to cycling
  10923. (arg
  10924. ;; User or caller requests a specific state.
  10925. (cond
  10926. ((equal arg "") nil)
  10927. ((eq arg 'none) nil)
  10928. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10929. ((eq arg 'nextset)
  10930. (or (car (cdr (member head org-todo-heads)))
  10931. (car org-todo-heads)))
  10932. ((eq arg 'previousset)
  10933. (let ((org-todo-heads (reverse org-todo-heads)))
  10934. (or (car (cdr (member head org-todo-heads)))
  10935. (car org-todo-heads))))
  10936. ((car (member arg org-todo-keywords-1)))
  10937. ((stringp arg)
  10938. (user-error "State `%s' not valid in this file" arg))
  10939. ((nth (1- (prefix-numeric-value arg))
  10940. org-todo-keywords-1))))
  10941. ((null member) (or head (car org-todo-keywords-1)))
  10942. ((equal this final-done-word) nil) ;-> make empty
  10943. ((null tail) nil) ;-> first entry
  10944. ((memq interpret '(type priority))
  10945. (if (eq this-command last-command)
  10946. (car tail)
  10947. (if (> (length tail) 0)
  10948. (or done-word (car org-done-keywords))
  10949. nil)))
  10950. (t
  10951. (car tail))))
  10952. (org-state (or
  10953. (run-hook-with-args-until-success
  10954. 'org-todo-get-default-hook org-state org-last-state)
  10955. org-state))
  10956. (next (if org-state (concat " " org-state " ") " "))
  10957. (change-plist (list :type 'todo-state-change :from this :to org-state
  10958. :position startpos))
  10959. dolog now-done-p)
  10960. (when org-blocker-hook
  10961. (let (org-blocked-by-checkboxes block-reason)
  10962. (setq org-last-todo-state-is-todo
  10963. (not (member this org-done-keywords)))
  10964. (unless (save-excursion
  10965. (save-match-data
  10966. (org-with-wide-buffer
  10967. (run-hook-with-args-until-failure
  10968. 'org-blocker-hook change-plist))))
  10969. (setq block-reason (if org-blocked-by-checkboxes
  10970. "contained checkboxes"
  10971. (format "\"%s\"" org-block-entry-blocking)))
  10972. (if (called-interactively-p 'interactive)
  10973. (user-error "TODO state change from %s to %s blocked (by %s)"
  10974. this org-state block-reason)
  10975. ;; Fail silently.
  10976. (message "TODO state change from %s to %s blocked (by %s)"
  10977. this org-state block-reason)
  10978. (throw 'exit nil)))))
  10979. (store-match-data match-data)
  10980. (replace-match next t t)
  10981. (cond ((equal this org-state)
  10982. (message "TODO state was already %s" (org-trim next)))
  10983. ((not (pos-visible-in-window-p hl-pos))
  10984. (message "TODO state changed to %s" (org-trim next))))
  10985. (unless head
  10986. (setq head (org-get-todo-sequence-head org-state)
  10987. ass (assoc head org-todo-kwd-alist)
  10988. interpret (nth 1 ass)
  10989. done-word (nth 3 ass)
  10990. final-done-word (nth 4 ass)))
  10991. (when (memq arg '(nextset previousset))
  10992. (message "Keyword-Set %d/%d: %s"
  10993. (- (length org-todo-sets) -1
  10994. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10995. (length org-todo-sets)
  10996. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10997. (setq org-last-todo-state-is-todo
  10998. (not (member org-state org-done-keywords)))
  10999. (setq now-done-p (and (member org-state org-done-keywords)
  11000. (not (member this org-done-keywords))))
  11001. (and logging (org-local-logging logging))
  11002. (when (and (or org-todo-log-states org-log-done)
  11003. (not (eq org-inhibit-logging t))
  11004. (not (memq arg '(nextset previousset))))
  11005. ;; We need to look at recording a time and note.
  11006. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11007. (nth 2 (assoc this org-todo-log-states))))
  11008. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11009. (setq dolog 'time))
  11010. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11011. (and org-state
  11012. (member org-state org-not-done-keywords)
  11013. (not (member this org-not-done-keywords))))
  11014. ;; This is now a todo state and was not one before
  11015. ;; If there was a CLOSED time stamp, get rid of it.
  11016. (org-add-planning-info nil nil 'closed))
  11017. (when (and now-done-p org-log-done)
  11018. ;; It is now done, and it was not done before.
  11019. (org-add-planning-info 'closed (org-current-effective-time))
  11020. (when (and (not dolog) (eq 'note org-log-done))
  11021. (org-add-log-setup 'done org-state this 'note)))
  11022. (when (and org-state dolog)
  11023. ;; This is a non-nil state, and we need to log it.
  11024. (org-add-log-setup 'state org-state this dolog)))
  11025. ;; Fixup tag positioning.
  11026. (org-todo-trigger-tag-changes org-state)
  11027. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11028. (when org-provide-todo-statistics
  11029. (org-update-parent-todo-statistics))
  11030. (run-hooks 'org-after-todo-state-change-hook)
  11031. (when (and arg (not (member org-state org-done-keywords)))
  11032. (setq head (org-get-todo-sequence-head org-state)))
  11033. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11034. ;; Do we need to trigger a repeat?
  11035. (when now-done-p
  11036. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11037. ;; This is for the agenda, take a snapshot of the headline.
  11038. (save-match-data
  11039. (setq org-agenda-headline-snapshot-before-repeat
  11040. (org-get-heading))))
  11041. (org-auto-repeat-maybe org-state))
  11042. ;; Fixup cursor location if close to the keyword.
  11043. (when (and (outline-on-heading-p)
  11044. (not (bolp))
  11045. (save-excursion (beginning-of-line 1)
  11046. (looking-at org-todo-line-regexp))
  11047. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11048. (goto-char (or (match-end 2) (match-end 1)))
  11049. (and (looking-at " ") (just-one-space)))
  11050. (when org-trigger-hook
  11051. (save-excursion
  11052. (run-hook-with-args 'org-trigger-hook change-plist)))
  11053. (when commentp (org-toggle-comment))))))))
  11054. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11055. "Block turning an entry into a TODO, using the hierarchy.
  11056. This checks whether the current task should be blocked from state
  11057. changes. Such blocking occurs when:
  11058. 1. The task has children which are not all in a completed state.
  11059. 2. A task has a parent with the property :ORDERED:, and there
  11060. are siblings prior to the current task with incomplete
  11061. status.
  11062. 3. The parent of the task is blocked because it has siblings that should
  11063. be done first, or is child of a block grandparent TODO entry."
  11064. (if (not org-enforce-todo-dependencies)
  11065. t ; if locally turned off don't block
  11066. (catch 'dont-block
  11067. ;; If this is not a todo state change, or if this entry is already DONE,
  11068. ;; do not block
  11069. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11070. (member (plist-get change-plist :from)
  11071. (cons 'done org-done-keywords))
  11072. (member (plist-get change-plist :to)
  11073. (cons 'todo org-not-done-keywords))
  11074. (not (plist-get change-plist :to)))
  11075. (throw 'dont-block t))
  11076. ;; If this task has children, and any are undone, it's blocked
  11077. (save-excursion
  11078. (org-back-to-heading t)
  11079. (let ((this-level (funcall outline-level)))
  11080. (outline-next-heading)
  11081. (let ((child-level (funcall outline-level)))
  11082. (while (and (not (eobp))
  11083. (> child-level this-level))
  11084. ;; this todo has children, check whether they are all
  11085. ;; completed
  11086. (when (and (not (org-entry-is-done-p))
  11087. (org-entry-is-todo-p))
  11088. (setq org-block-entry-blocking (org-get-heading))
  11089. (throw 'dont-block nil))
  11090. (outline-next-heading)
  11091. (setq child-level (funcall outline-level))))))
  11092. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11093. ;; any previous siblings are undone, it's blocked
  11094. (save-excursion
  11095. (org-back-to-heading t)
  11096. (let* ((pos (point))
  11097. (parent-pos (and (org-up-heading-safe) (point)))
  11098. (case-fold-search nil))
  11099. (unless parent-pos (throw 'dont-block t)) ; no parent
  11100. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11101. (forward-line 1)
  11102. (re-search-forward org-not-done-heading-regexp pos t))
  11103. (setq org-block-entry-blocking (match-string 0))
  11104. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11105. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11106. (while t
  11107. (goto-char parent-pos)
  11108. (unless (looking-at org-not-done-heading-regexp)
  11109. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11110. (setq pos (point))
  11111. (setq parent-pos (and (org-up-heading-safe) (point)))
  11112. (unless parent-pos (throw 'dont-block t)) ; no parent
  11113. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11114. (forward-line 1)
  11115. (re-search-forward org-not-done-heading-regexp pos t)
  11116. (setq org-block-entry-blocking (org-get-heading)))
  11117. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11118. (defcustom org-track-ordered-property-with-tag nil
  11119. "Should the ORDERED property also be shown as a tag?
  11120. The ORDERED property decides if an entry should require subtasks to be
  11121. completed in sequence. Since a property is not very visible, setting
  11122. this option means that toggling the ORDERED property with the command
  11123. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11124. not relevant for the behavior, but it makes things more visible.
  11125. Note that toggling the tag with tags commands will not change the property
  11126. and therefore not influence behavior!
  11127. This can be t, meaning the tag ORDERED should be used, It can also be a
  11128. string to select a different tag for this task."
  11129. :group 'org-todo
  11130. :type '(choice
  11131. (const :tag "No tracking" nil)
  11132. (const :tag "Track with ORDERED tag" t)
  11133. (string :tag "Use other tag")))
  11134. (defun org-toggle-ordered-property ()
  11135. "Toggle the ORDERED property of the current entry.
  11136. For better visibility, you can track the value of this property with a tag.
  11137. See variable `org-track-ordered-property-with-tag'."
  11138. (interactive)
  11139. (let* ((t1 org-track-ordered-property-with-tag)
  11140. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11141. (save-excursion
  11142. (org-back-to-heading)
  11143. (if (org-entry-get nil "ORDERED")
  11144. (progn
  11145. (org-delete-property "ORDERED")
  11146. (and tag (org-toggle-tag tag 'off))
  11147. (message "Subtasks can be completed in arbitrary order"))
  11148. (org-entry-put nil "ORDERED" "t")
  11149. (and tag (org-toggle-tag tag 'on))
  11150. (message "Subtasks must be completed in sequence")))))
  11151. (defun org-block-todo-from-checkboxes (change-plist)
  11152. "Block turning an entry into a TODO, using checkboxes.
  11153. This checks whether the current task should be blocked from state
  11154. changes because there are unchecked boxes in this entry."
  11155. (if (not org-enforce-todo-checkbox-dependencies)
  11156. t ; if locally turned off don't block
  11157. (catch 'dont-block
  11158. ;; If this is not a todo state change, or if this entry is already DONE,
  11159. ;; do not block
  11160. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11161. (member (plist-get change-plist :from)
  11162. (cons 'done org-done-keywords))
  11163. (member (plist-get change-plist :to)
  11164. (cons 'todo org-not-done-keywords))
  11165. (not (plist-get change-plist :to)))
  11166. (throw 'dont-block t))
  11167. ;; If this task has checkboxes that are not checked, it's blocked
  11168. (save-excursion
  11169. (org-back-to-heading t)
  11170. (let ((beg (point)) end)
  11171. (outline-next-heading)
  11172. (setq end (point))
  11173. (goto-char beg)
  11174. (when (org-list-search-forward
  11175. (concat (org-item-beginning-re)
  11176. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11177. "\\[[- ]\\]")
  11178. end t)
  11179. (when (boundp 'org-blocked-by-checkboxes)
  11180. (setq org-blocked-by-checkboxes t))
  11181. (throw 'dont-block nil))))
  11182. t))) ; do not block
  11183. (defun org-entry-blocked-p ()
  11184. "Non-nil if entry at point is blocked."
  11185. (and (not (org-entry-get nil "NOBLOCKING"))
  11186. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11187. (not (run-hook-with-args-until-failure
  11188. 'org-blocker-hook
  11189. (list :type 'todo-state-change
  11190. :position (point)
  11191. :from 'todo
  11192. :to 'done)))))
  11193. (defun org-update-statistics-cookies (all)
  11194. "Update the statistics cookie, either from TODO or from checkboxes.
  11195. This should be called with the cursor in a line with a statistics
  11196. cookie. When called with a \\[universal-argument] prefix, update
  11197. all statistics cookies in the buffer."
  11198. (interactive "P")
  11199. (if all
  11200. (progn
  11201. (org-update-checkbox-count 'all)
  11202. (org-map-entries 'org-update-parent-todo-statistics))
  11203. (if (not (org-at-heading-p))
  11204. (org-update-checkbox-count)
  11205. (let ((pos (point-marker))
  11206. end l1 l2)
  11207. (ignore-errors (org-back-to-heading t))
  11208. (if (not (org-at-heading-p))
  11209. (org-update-checkbox-count)
  11210. (setq l1 (org-outline-level))
  11211. (setq end (save-excursion
  11212. (outline-next-heading)
  11213. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11214. (point)))
  11215. (if (and (save-excursion
  11216. (re-search-forward
  11217. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11218. (not (save-excursion (re-search-forward
  11219. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11220. (org-update-checkbox-count)
  11221. (if (and l2 (> l2 l1))
  11222. (progn
  11223. (goto-char end)
  11224. (org-update-parent-todo-statistics))
  11225. (goto-char pos)
  11226. (beginning-of-line 1)
  11227. (while (re-search-forward
  11228. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11229. (point-at-eol) t)
  11230. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11231. (goto-char pos)
  11232. (move-marker pos nil)))))
  11233. (defvar org-entry-property-inherited-from) ;; defined below
  11234. (defun org-update-parent-todo-statistics ()
  11235. "Update any statistics cookie in the parent of the current headline.
  11236. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11237. the entire subtree and this will travel up the hierarchy and update
  11238. statistics everywhere."
  11239. (let* ((prop (save-excursion (org-up-heading-safe)
  11240. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11241. (recursive (or (not org-hierarchical-todo-statistics)
  11242. (and prop (string-match "\\<recursive\\>" prop))))
  11243. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11244. 0))
  11245. (first t)
  11246. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11247. level ltoggle l1 new ndel
  11248. (cnt-all 0) (cnt-done 0) is-percent kwd
  11249. checkbox-beg cookie-present)
  11250. (catch 'exit
  11251. (save-excursion
  11252. (beginning-of-line 1)
  11253. (setq ltoggle (funcall outline-level))
  11254. ;; Three situations are to consider:
  11255. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11256. ;; to the top-level ancestor on the headline;
  11257. ;; 2. If parent has "recursive" property, repeat up to the
  11258. ;; headline setting that property, taking inheritance into
  11259. ;; account;
  11260. ;; 3. Else, move up to direct parent and proceed only once.
  11261. (while (and (setq level (org-up-heading-safe))
  11262. (or recursive first)
  11263. (>= (point) lim))
  11264. (setq first nil cookie-present nil)
  11265. (unless (and level
  11266. (not (string-match
  11267. "\\<checkbox\\>"
  11268. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11269. "")))))
  11270. (throw 'exit nil))
  11271. (while (re-search-forward box-re (point-at-eol) t)
  11272. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11273. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11274. (save-match-data
  11275. (unless (outline-next-heading) (throw 'exit nil))
  11276. (while (and (looking-at org-complex-heading-regexp)
  11277. (> (setq l1 (length (match-string 1))) level))
  11278. (setq kwd (and (or recursive (= l1 ltoggle))
  11279. (match-string 2)))
  11280. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11281. (and (eq org-provide-todo-statistics t)
  11282. (or (member kwd org-done-keywords)))
  11283. (and (listp org-provide-todo-statistics)
  11284. (stringp (car org-provide-todo-statistics))
  11285. (or (member kwd org-provide-todo-statistics)
  11286. (member kwd org-done-keywords)))
  11287. (and (listp org-provide-todo-statistics)
  11288. (listp (car org-provide-todo-statistics))
  11289. (or (member kwd (car org-provide-todo-statistics))
  11290. (and (member kwd org-done-keywords)
  11291. (member kwd (cadr org-provide-todo-statistics))))))
  11292. (setq cnt-all (1+ cnt-all))
  11293. (and (eq org-provide-todo-statistics t)
  11294. kwd
  11295. (setq cnt-all (1+ cnt-all))))
  11296. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11297. (member kwd org-done-keywords))
  11298. (and (listp org-provide-todo-statistics)
  11299. (listp (car org-provide-todo-statistics))
  11300. (member kwd org-done-keywords)
  11301. (member kwd (cadr org-provide-todo-statistics)))
  11302. (and (listp org-provide-todo-statistics)
  11303. (stringp (car org-provide-todo-statistics))
  11304. (member kwd org-done-keywords)))
  11305. (setq cnt-done (1+ cnt-done)))
  11306. (outline-next-heading)))
  11307. (setq new
  11308. (if is-percent
  11309. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11310. (max 1 cnt-all)))
  11311. (format "[%d/%d]" cnt-done cnt-all))
  11312. ndel (- (match-end 0) checkbox-beg))
  11313. (goto-char checkbox-beg)
  11314. (insert new)
  11315. (delete-region (point) (+ (point) ndel))
  11316. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11317. (when cookie-present
  11318. (run-hook-with-args 'org-after-todo-statistics-hook
  11319. cnt-done (- cnt-all cnt-done))))))
  11320. (run-hooks 'org-todo-statistics-hook)))
  11321. (defvar org-after-todo-statistics-hook nil
  11322. "Hook that is called after a TODO statistics cookie has been updated.
  11323. Each function is called with two arguments: the number of not-done entries
  11324. and the number of done entries.
  11325. For example, the following function, when added to this hook, will switch
  11326. an entry to DONE when all children are done, and back to TODO when new
  11327. entries are set to a TODO status. Note that this hook is only called
  11328. when there is a statistics cookie in the headline!
  11329. (defun org-summary-todo (n-done n-not-done)
  11330. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11331. (let (org-log-done org-log-states) ; turn off logging
  11332. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11333. ")
  11334. (defvar org-todo-statistics-hook nil
  11335. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11336. This hook runs even if there is no statistics cookie present, in which case
  11337. `org-after-todo-statistics-hook' would not run.")
  11338. (defun org-todo-trigger-tag-changes (state)
  11339. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11340. (let ((l org-todo-state-tags-triggers)
  11341. changes)
  11342. (when (or (not state) (equal state ""))
  11343. (setq changes (append changes (cdr (assoc "" l)))))
  11344. (when (and (stringp state) (> (length state) 0))
  11345. (setq changes (append changes (cdr (assoc state l)))))
  11346. (when (member state org-not-done-keywords)
  11347. (setq changes (append changes (cdr (assq 'todo l)))))
  11348. (when (member state org-done-keywords)
  11349. (setq changes (append changes (cdr (assq 'done l)))))
  11350. (dolist (c changes)
  11351. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11352. (defun org-local-logging (value)
  11353. "Get logging settings from a property VALUE."
  11354. ;; Directly set the variables, they are already local.
  11355. (setq org-log-done nil
  11356. org-log-repeat nil
  11357. org-todo-log-states nil)
  11358. (dolist (w (split-string value))
  11359. (let (a)
  11360. (cond
  11361. ((setq a (assoc w org-startup-options))
  11362. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11363. (set (nth 1 a) (nth 2 a))))
  11364. ((setq a (org-extract-log-state-settings w))
  11365. (and (member (car a) org-todo-keywords-1)
  11366. (push a org-todo-log-states)))))))
  11367. (defun org-get-todo-sequence-head (kwd)
  11368. "Return the head of the TODO sequence to which KWD belongs.
  11369. If KWD is not set, check if there is a text property remembering the
  11370. right sequence."
  11371. (let (p)
  11372. (cond
  11373. ((not kwd)
  11374. (or (get-text-property (point-at-bol) 'org-todo-head)
  11375. (progn
  11376. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11377. nil (point-at-eol)))
  11378. (get-text-property p 'org-todo-head))))
  11379. ((not (member kwd org-todo-keywords-1))
  11380. (car org-todo-keywords-1))
  11381. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11382. (defun org-fast-todo-selection ()
  11383. "Fast TODO keyword selection with single keys.
  11384. Returns the new TODO keyword, or nil if no state change should occur."
  11385. (let* ((fulltable org-todo-key-alist)
  11386. (done-keywords org-done-keywords) ;; needed for the faces.
  11387. (maxlen (apply 'max (mapcar
  11388. (lambda (x)
  11389. (if (stringp (car x)) (string-width (car x)) 0))
  11390. fulltable)))
  11391. (expert nil)
  11392. (fwidth (+ maxlen 3 1 3))
  11393. (ncol (/ (- (window-width) 4) fwidth))
  11394. tg cnt e c tbl
  11395. groups ingroup)
  11396. (save-excursion
  11397. (save-window-excursion
  11398. (if expert
  11399. (set-buffer (get-buffer-create " *Org todo*"))
  11400. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11401. (erase-buffer)
  11402. (setq-local org-done-keywords done-keywords)
  11403. (setq tbl fulltable cnt 0)
  11404. (while (setq e (pop tbl))
  11405. (cond
  11406. ((equal e '(:startgroup))
  11407. (push '() groups) (setq ingroup t)
  11408. (unless (= cnt 0)
  11409. (setq cnt 0)
  11410. (insert "\n"))
  11411. (insert "{ "))
  11412. ((equal e '(:endgroup))
  11413. (setq ingroup nil cnt 0)
  11414. (insert "}\n"))
  11415. ((equal e '(:newline))
  11416. (unless (= cnt 0)
  11417. (setq cnt 0)
  11418. (insert "\n")
  11419. (setq e (car tbl))
  11420. (while (equal (car tbl) '(:newline))
  11421. (insert "\n")
  11422. (setq tbl (cdr tbl)))))
  11423. (t
  11424. (setq tg (car e) c (cdr e))
  11425. (when ingroup (push tg (car groups)))
  11426. (setq tg (org-add-props tg nil 'face
  11427. (org-get-todo-face tg)))
  11428. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11429. (insert "[" c "] " tg (make-string
  11430. (- fwidth 4 (length tg)) ?\ ))
  11431. (when (= (setq cnt (1+ cnt)) ncol)
  11432. (insert "\n")
  11433. (when ingroup (insert " "))
  11434. (setq cnt 0)))))
  11435. (insert "\n")
  11436. (goto-char (point-min))
  11437. (unless expert (org-fit-window-to-buffer))
  11438. (message "[a-z..]:Set [SPC]:clear")
  11439. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11440. (cond
  11441. ((or (= c ?\C-g)
  11442. (and (= c ?q) (not (rassoc c fulltable))))
  11443. (setq quit-flag t))
  11444. ((= c ?\ ) nil)
  11445. ((setq e (rassoc c fulltable) tg (car e))
  11446. tg)
  11447. (t (setq quit-flag t)))))))
  11448. (defun org-entry-is-todo-p ()
  11449. (member (org-get-todo-state) org-not-done-keywords))
  11450. (defun org-entry-is-done-p ()
  11451. (member (org-get-todo-state) org-done-keywords))
  11452. (defun org-get-todo-state ()
  11453. "Return the TODO keyword of the current subtree."
  11454. (save-excursion
  11455. (org-back-to-heading t)
  11456. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11457. (match-end 2)
  11458. (match-string 2))))
  11459. (defun org-at-date-range-p (&optional inactive-ok)
  11460. "Non-nil if point is inside a date range.
  11461. When optional argument INACTIVE-OK is non-nil, also consider
  11462. inactive time ranges.
  11463. When this function returns a non-nil value, match data is set
  11464. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11465. on INACTIVE-OK."
  11466. (interactive)
  11467. (save-excursion
  11468. (catch 'exit
  11469. (let ((pos (point)))
  11470. (skip-chars-backward "^[<\r\n")
  11471. (skip-chars-backward "<[")
  11472. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11473. (>= (match-end 0) pos)
  11474. (throw 'exit t))
  11475. (skip-chars-backward "^<[\r\n")
  11476. (skip-chars-backward "<[")
  11477. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11478. (>= (match-end 0) pos)
  11479. (throw 'exit t)))
  11480. nil)))
  11481. (defun org-get-repeat (&optional timestamp)
  11482. "Check if there is a time-stamp with repeater in this entry.
  11483. Return the repeater, as a string, or nil. Also return nil when
  11484. this function is called before first heading.
  11485. When optional argument TIMESTAMP is a string, extract the
  11486. repeater from there instead."
  11487. (save-match-data
  11488. (cond (timestamp
  11489. (and (string-match org-repeat-re timestamp)
  11490. (match-string-no-properties 1 timestamp)))
  11491. ((org-before-first-heading-p) nil)
  11492. (t
  11493. (save-excursion
  11494. (org-back-to-heading t)
  11495. (let ((end (org-entry-end-position)))
  11496. (catch :repeat
  11497. (while (re-search-forward org-repeat-re end t)
  11498. (when (save-match-data (org-at-timestamp-p 'agenda))
  11499. (throw :repeat (match-string-no-properties 1)))))))))))
  11500. (defvar org-last-changed-timestamp)
  11501. (defvar org-last-inserted-timestamp)
  11502. (defvar org-log-post-message)
  11503. (defvar org-log-note-purpose)
  11504. (defvar org-log-note-how nil)
  11505. (defvar org-log-note-extra)
  11506. (defun org-auto-repeat-maybe (done-word)
  11507. "Check if the current headline contains a repeated time-stamp.
  11508. If yes, set TODO state back to what it was and change the base date
  11509. of repeating deadline/scheduled time stamps to new date.
  11510. This function is run automatically after each state change to a DONE state."
  11511. (let* ((repeat (org-get-repeat))
  11512. (aa (assoc org-last-state org-todo-kwd-alist))
  11513. (interpret (nth 1 aa))
  11514. (head (nth 2 aa))
  11515. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11516. (msg "Entry repeats: ")
  11517. (org-log-done nil)
  11518. (org-todo-log-states nil)
  11519. (end (copy-marker (org-entry-end-position))))
  11520. (unwind-protect
  11521. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11522. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11523. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11524. org-todo-repeat-to-state)))
  11525. (org-todo (cond
  11526. ((and to-state (member to-state org-todo-keywords-1))
  11527. to-state)
  11528. ((eq interpret 'type) org-last-state)
  11529. (head)
  11530. (t 'none))))
  11531. (org-back-to-heading t)
  11532. (org-add-planning-info nil nil 'closed)
  11533. ;; When `org-log-repeat' is non-nil or entry contains
  11534. ;; a clock, set LAST_REPEAT property.
  11535. (when (or org-log-repeat
  11536. (catch :clock
  11537. (save-excursion
  11538. (while (re-search-forward org-clock-line-re end t)
  11539. (when (org-at-clock-log-p) (throw :clock t))))))
  11540. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11541. (org-time-stamp-format t t)
  11542. (current-time))))
  11543. (when org-log-repeat
  11544. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11545. (memq 'org-add-log-note post-command-hook))
  11546. ;; We are already setup for some record.
  11547. (when (eq org-log-repeat 'note)
  11548. ;; Make sure we take a note, not only a time stamp.
  11549. (setq org-log-note-how 'note))
  11550. ;; Set up for taking a record.
  11551. (org-add-log-setup 'state
  11552. (or done-word (car org-done-keywords))
  11553. org-last-state
  11554. org-log-repeat)))
  11555. (let ((planning-re (regexp-opt
  11556. (list org-scheduled-string org-deadline-string))))
  11557. (while (re-search-forward org-ts-regexp end t)
  11558. (let* ((ts (match-string 0))
  11559. (planning? (org-at-planning-p))
  11560. (type (if (not planning?) "Plain:"
  11561. (save-excursion
  11562. (re-search-backward
  11563. planning-re (line-beginning-position) t)
  11564. (match-string 0)))))
  11565. (cond
  11566. ;; Ignore fake time-stamps (e.g., within comments).
  11567. ((not (org-at-timestamp-p 'agenda)))
  11568. ;; Time-stamps without a repeater are usually
  11569. ;; skipped. However, a SCHEDULED time-stamp without
  11570. ;; one is removed, as they are no longer relevant.
  11571. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11572. ts))
  11573. (when (equal type org-scheduled-string)
  11574. (org-remove-timestamp-with-keyword type)))
  11575. (t
  11576. (let ((n (string-to-number (match-string 2 ts)))
  11577. (what (match-string 3 ts)))
  11578. (when (equal what "w") (setq n (* n 7) what "d"))
  11579. (when (and (equal what "h")
  11580. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11581. ts)))
  11582. (user-error
  11583. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11584. has been set"
  11585. n))
  11586. ;; Preparation, see if we need to modify the start
  11587. ;; date for the change.
  11588. (when (match-end 1)
  11589. (let ((time (save-match-data
  11590. (org-time-string-to-time ts))))
  11591. (cond
  11592. ((equal (match-string 1 ts) ".")
  11593. ;; Shift starting date to today
  11594. (org-timestamp-change
  11595. (- (org-today) (time-to-days time))
  11596. 'day))
  11597. ((equal (match-string 1 ts) "+")
  11598. (let ((nshiftmax 10)
  11599. (nshift 0))
  11600. (while (or (= nshift 0)
  11601. (not (time-less-p (current-time) time)))
  11602. (when (= (cl-incf nshift) nshiftmax)
  11603. (or (y-or-n-p
  11604. (format "%d repeater intervals were not \
  11605. enough to shift date past today. Continue? "
  11606. nshift))
  11607. (user-error "Abort")))
  11608. (org-timestamp-change n (cdr (assoc what whata)))
  11609. (org-in-regexp org-ts-regexp3)
  11610. (setq ts (match-string 1))
  11611. (setq time
  11612. (save-match-data
  11613. (org-time-string-to-time ts)))))
  11614. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11615. ;; Rematch, so that we have everything in place
  11616. ;; for the real shift.
  11617. (org-in-regexp org-ts-regexp3)
  11618. (setq ts (match-string 1))
  11619. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11620. ts)))))
  11621. (save-excursion
  11622. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11623. (setq msg
  11624. (concat
  11625. msg type " " org-last-changed-timestamp " "))))))))
  11626. (setq org-log-post-message msg)
  11627. (message "%s" msg))
  11628. (set-marker end nil))))
  11629. (defun org-show-todo-tree (arg)
  11630. "Make a compact tree which shows all headlines marked with TODO.
  11631. The tree will show the lines where the regexp matches, and all higher
  11632. headlines above the match.
  11633. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11634. With a numeric prefix N, construct a sparse tree for the Nth element
  11635. of `org-todo-keywords-1'."
  11636. (interactive "P")
  11637. (let ((case-fold-search nil)
  11638. (kwd-re
  11639. (cond ((null arg) org-not-done-regexp)
  11640. ((equal arg '(4))
  11641. (let ((kwd
  11642. (completing-read "Keyword (or KWD1|KWD2|...): "
  11643. (mapcar #'list org-todo-keywords-1))))
  11644. (concat "\\("
  11645. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11646. "\\)\\>")))
  11647. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11648. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11649. org-todo-keywords-1)))
  11650. (t (user-error "Invalid prefix argument: %s" arg)))))
  11651. (message "%d TODO entries found"
  11652. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11653. (defun org--deadline-or-schedule (arg type time)
  11654. "Insert DEADLINE or SCHEDULE information in current entry.
  11655. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11656. `org-schedule' for information about ARG and TIME arguments."
  11657. (let* ((deadline? (eq type 'deadline))
  11658. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11659. (log (if deadline? org-log-redeadline org-log-reschedule))
  11660. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11661. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11662. ;; Save repeater cookie from either TIME or current scheduled
  11663. ;; time stamp. We are going to insert it back at the end of
  11664. ;; the process.
  11665. (repeater (or (and (org-string-nw-p time)
  11666. ;; We use `org-repeat-re' because we need
  11667. ;; to tell the difference between a real
  11668. ;; repeater and a time delta, e.g. "+2d".
  11669. (string-match org-repeat-re time)
  11670. (match-string 1 time))
  11671. (and (org-string-nw-p old-date)
  11672. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11673. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11674. old-date)
  11675. (match-string 1 old-date)))))
  11676. (pcase arg
  11677. (`(4)
  11678. (when (and old-date log)
  11679. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11680. nil old-date log))
  11681. (org-remove-timestamp-with-keyword keyword)
  11682. (message (if deadline? "Item no longer has a deadline."
  11683. "Item is no longer scheduled.")))
  11684. (`(16)
  11685. (save-excursion
  11686. (org-back-to-heading t)
  11687. (let ((regexp (if deadline? org-deadline-time-regexp
  11688. org-scheduled-time-regexp)))
  11689. (if (not (re-search-forward regexp (line-end-position 2) t))
  11690. (user-error (if deadline? "No deadline information to update"
  11691. "No scheduled information to update"))
  11692. (let* ((rpl0 (match-string 1))
  11693. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11694. (msg (if deadline? "Warn starting from" "Delay until")))
  11695. (replace-match
  11696. (concat keyword
  11697. " <" rpl
  11698. (format " -%dd"
  11699. (abs (- (time-to-days
  11700. (save-match-data
  11701. (org-read-date
  11702. nil t nil msg old-date-time)))
  11703. (time-to-days old-date-time))))
  11704. ">") t t))))))
  11705. (_
  11706. (org-add-planning-info type time 'closed)
  11707. (when (and old-date
  11708. log
  11709. (not (equal old-date org-last-inserted-timestamp)))
  11710. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11711. org-last-inserted-timestamp
  11712. old-date
  11713. log))
  11714. (when repeater
  11715. (save-excursion
  11716. (org-back-to-heading t)
  11717. (when (re-search-forward
  11718. (concat keyword " " org-last-inserted-timestamp)
  11719. (line-end-position 2)
  11720. t)
  11721. (goto-char (1- (match-end 0)))
  11722. (insert " " repeater)
  11723. (setq org-last-inserted-timestamp
  11724. (concat (substring org-last-inserted-timestamp 0 -1)
  11725. " " repeater
  11726. (substring org-last-inserted-timestamp -1))))))
  11727. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11728. org-last-inserted-timestamp)))))
  11729. (defun org-deadline (arg &optional time)
  11730. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11731. With one universal prefix argument, remove any deadline from the item.
  11732. With two universal prefix arguments, prompt for a warning delay.
  11733. With argument TIME, set the deadline at the corresponding date. TIME
  11734. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11735. (interactive "P")
  11736. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11737. (org-map-entries
  11738. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11739. nil
  11740. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11741. 'region-start-level
  11742. 'region)
  11743. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11744. (org--deadline-or-schedule arg 'deadline time)))
  11745. (defun org-schedule (arg &optional time)
  11746. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11747. With one universal prefix argument, remove any scheduling date from the item.
  11748. With two universal prefix arguments, prompt for a delay cookie.
  11749. With argument TIME, scheduled at the corresponding date. TIME can
  11750. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11751. (interactive "P")
  11752. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11753. (org-map-entries
  11754. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11755. nil
  11756. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11757. 'region-start-level
  11758. 'region)
  11759. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11760. (org--deadline-or-schedule arg 'scheduled time)))
  11761. (defun org-get-scheduled-time (pom &optional inherit)
  11762. "Get the scheduled time as a time tuple, of a format suitable
  11763. for calling org-schedule with, or if there is no scheduling,
  11764. returns nil."
  11765. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11766. (when time
  11767. (apply 'encode-time (org-parse-time-string time)))))
  11768. (defun org-get-deadline-time (pom &optional inherit)
  11769. "Get the deadline as a time tuple, of a format suitable for
  11770. calling org-deadline with, or if there is no scheduling, returns
  11771. nil."
  11772. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11773. (when time
  11774. (apply 'encode-time (org-parse-time-string time)))))
  11775. (defun org-remove-timestamp-with-keyword (keyword)
  11776. "Remove all time stamps with KEYWORD in the current entry."
  11777. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11778. beg)
  11779. (save-excursion
  11780. (org-back-to-heading t)
  11781. (setq beg (point))
  11782. (outline-next-heading)
  11783. (while (re-search-backward re beg t)
  11784. (replace-match "")
  11785. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11786. (equal (char-before) ?\ ))
  11787. (backward-delete-char 1)
  11788. (when (string-match "^[ \t]*$" (buffer-substring
  11789. (point-at-bol) (point-at-eol)))
  11790. (delete-region (point-at-bol)
  11791. (min (point-max) (1+ (point-at-eol))))))))))
  11792. (defvar org-time-was-given) ; dynamically scoped parameter
  11793. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11794. (defun org-at-planning-p ()
  11795. "Non-nil when point is on a planning info line."
  11796. ;; This is as accurate and faster than `org-element-at-point' since
  11797. ;; planning info location is fixed in the section.
  11798. (org-with-wide-buffer
  11799. (beginning-of-line)
  11800. (and (looking-at-p org-planning-line-re)
  11801. (eq (point)
  11802. (ignore-errors
  11803. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11804. (org-back-to-heading t)
  11805. (org-with-limited-levels (org-back-to-heading t)))
  11806. (line-beginning-position 2))))))
  11807. (defun org-add-planning-info (what &optional time &rest remove)
  11808. "Insert new timestamp with keyword in the planning line.
  11809. WHAT indicates what kind of time stamp to add. It is a symbol
  11810. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11811. the time to use. If none is given, the user is prompted for
  11812. a date. REMOVE indicates what kind of entries to remove. An old
  11813. WHAT entry will also be removed."
  11814. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11815. (catch 'exit
  11816. (when (and (memq what '(scheduled deadline))
  11817. (or (not time)
  11818. (and (stringp time)
  11819. (string-match "^[-+]+[0-9]" time))))
  11820. ;; Try to get a default date/time from existing timestamp
  11821. (save-excursion
  11822. (org-back-to-heading t)
  11823. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11824. (when (re-search-forward (if (eq what 'scheduled)
  11825. org-scheduled-time-regexp
  11826. org-deadline-time-regexp)
  11827. end t)
  11828. (setq ts (match-string 1)
  11829. default-time (apply 'encode-time (org-parse-time-string ts))
  11830. default-input (and ts (org-get-compact-tod ts)))))))
  11831. (when what
  11832. (setq time
  11833. (if (stringp time)
  11834. ;; This is a string (relative or absolute), set
  11835. ;; proper date.
  11836. (apply #'encode-time
  11837. (org-read-date-analyze
  11838. time default-time (decode-time default-time)))
  11839. ;; If necessary, get the time from the user
  11840. (or time (org-read-date nil 'to-time nil nil
  11841. default-time default-input)))))
  11842. (org-with-wide-buffer
  11843. (org-back-to-heading t)
  11844. (forward-line)
  11845. (unless (bolp) (insert "\n"))
  11846. (cond ((looking-at-p org-planning-line-re)
  11847. ;; Move to current indentation.
  11848. (skip-chars-forward " \t")
  11849. ;; Check if we have to remove something.
  11850. (dolist (type (if what (cons what remove) remove))
  11851. (save-excursion
  11852. (when (re-search-forward
  11853. (cl-case type
  11854. (closed org-closed-time-regexp)
  11855. (deadline org-deadline-time-regexp)
  11856. (scheduled org-scheduled-time-regexp)
  11857. (otherwise
  11858. (error "Invalid planning type: %s" type)))
  11859. (line-end-position) t)
  11860. ;; Delete until next keyword or end of line.
  11861. (delete-region
  11862. (match-beginning 0)
  11863. (if (re-search-forward org-keyword-time-not-clock-regexp
  11864. (line-end-position)
  11865. t)
  11866. (match-beginning 0)
  11867. (line-end-position))))))
  11868. ;; If there is nothing more to add and no more keyword
  11869. ;; is left, remove the line completely.
  11870. (if (and (looking-at-p "[ \t]*$") (not what))
  11871. (delete-region (line-beginning-position)
  11872. (line-beginning-position 2))
  11873. ;; If we removed last keyword, do not leave trailing
  11874. ;; white space at the end of line.
  11875. (let ((p (point)))
  11876. (save-excursion
  11877. (end-of-line)
  11878. (unless (= (skip-chars-backward " \t" p) 0)
  11879. (delete-region (point) (line-end-position)))))))
  11880. ((not what) (throw 'exit nil)) ; Nothing to do.
  11881. (t (insert-before-markers "\n")
  11882. (backward-char 1)
  11883. (when org-adapt-indentation
  11884. (indent-to-column (1+ (org-outline-level))))))
  11885. (when what
  11886. ;; Insert planning keyword.
  11887. (insert (cl-case what
  11888. (closed org-closed-string)
  11889. (deadline org-deadline-string)
  11890. (scheduled org-scheduled-string)
  11891. (otherwise (error "Invalid planning type: %s" what)))
  11892. " ")
  11893. ;; Insert associated timestamp.
  11894. (let ((ts (org-insert-time-stamp
  11895. time
  11896. (or org-time-was-given
  11897. (and (eq what 'closed) org-log-done-with-time))
  11898. (eq what 'closed)
  11899. nil nil (list org-end-time-was-given))))
  11900. (unless (eolp) (insert " "))
  11901. ts))))))
  11902. (defvar org-log-note-marker (make-marker)
  11903. "Marker pointing at the entry where the note is to be inserted.")
  11904. (defvar org-log-note-purpose nil)
  11905. (defvar org-log-note-state nil)
  11906. (defvar org-log-note-previous-state nil)
  11907. (defvar org-log-note-extra nil)
  11908. (defvar org-log-note-window-configuration nil)
  11909. (defvar org-log-note-return-to (make-marker))
  11910. (defvar org-log-note-effective-time nil
  11911. "Remembered current time so that dynamically scoped
  11912. `org-extend-today-until' affects timestamps in state change log")
  11913. (defvar org-log-post-message nil
  11914. "Message to be displayed after a log note has been stored.
  11915. The auto-repeater uses this.")
  11916. (defun org-add-note ()
  11917. "Add a note to the current entry.
  11918. This is done in the same way as adding a state change note."
  11919. (interactive)
  11920. (org-add-log-setup 'note))
  11921. (defun org-log-beginning (&optional create)
  11922. "Return expected start of log notes in current entry.
  11923. When optional argument CREATE is non-nil, the function creates
  11924. a drawer to store notes, if necessary. Returned position ignores
  11925. narrowing."
  11926. (org-with-wide-buffer
  11927. (let ((drawer (org-log-into-drawer)))
  11928. (cond
  11929. (drawer
  11930. (org-end-of-meta-data)
  11931. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11932. (end (if (org-at-heading-p) (point)
  11933. (save-excursion (outline-next-heading) (point))))
  11934. (case-fold-search t))
  11935. (catch 'exit
  11936. ;; Try to find existing drawer.
  11937. (while (re-search-forward regexp end t)
  11938. (let ((element (org-element-at-point)))
  11939. (when (eq (org-element-type element) 'drawer)
  11940. (let ((cend (org-element-property :contents-end element)))
  11941. (when (and (not org-log-states-order-reversed) cend)
  11942. (goto-char cend)))
  11943. (throw 'exit nil))))
  11944. ;; No drawer found. Create one, if permitted.
  11945. (when create
  11946. (unless (bolp) (insert "\n"))
  11947. (let ((beg (point)))
  11948. (insert ":" drawer ":\n:END:\n")
  11949. (org-indent-region beg (point)))
  11950. (end-of-line -1)))))
  11951. (t
  11952. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11953. (skip-chars-forward " \t\n")
  11954. (beginning-of-line)
  11955. (unless org-log-states-order-reversed
  11956. (org-skip-over-state-notes)
  11957. (skip-chars-backward " \t\n")
  11958. (forward-line)))))
  11959. (if (bolp) (point) (line-beginning-position 2))))
  11960. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11961. "Set up the post command hook to take a note.
  11962. If this is about to TODO state change, the new state is expected in STATE.
  11963. HOW is an indicator what kind of note should be created.
  11964. EXTRA is additional text that will be inserted into the notes buffer."
  11965. (move-marker org-log-note-marker (point))
  11966. (setq org-log-note-purpose purpose
  11967. org-log-note-state state
  11968. org-log-note-previous-state prev-state
  11969. org-log-note-how how
  11970. org-log-note-extra extra
  11971. org-log-note-effective-time (org-current-effective-time))
  11972. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11973. (defun org-skip-over-state-notes ()
  11974. "Skip past the list of State notes in an entry."
  11975. (when (ignore-errors (goto-char (org-in-item-p)))
  11976. (let* ((struct (org-list-struct))
  11977. (prevs (org-list-prevs-alist struct))
  11978. (regexp
  11979. (concat "[ \t]*- +"
  11980. (replace-regexp-in-string
  11981. " +" " +"
  11982. (org-replace-escapes
  11983. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11984. `(("%d" . ,org-ts-regexp-inactive)
  11985. ("%D" . ,org-ts-regexp)
  11986. ("%s" . "\"\\S-+\"")
  11987. ("%S" . "\"\\S-+\"")
  11988. ("%t" . ,org-ts-regexp-inactive)
  11989. ("%T" . ,org-ts-regexp)
  11990. ("%u" . ".*?")
  11991. ("%U" . ".*?")))))))
  11992. (while (looking-at-p regexp)
  11993. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11994. (org-list-get-item-end (point) struct)))))))
  11995. (defun org-add-log-note (&optional _purpose)
  11996. "Pop up a window for taking a note, and add this note later."
  11997. (remove-hook 'post-command-hook 'org-add-log-note)
  11998. (setq org-log-note-window-configuration (current-window-configuration))
  11999. (delete-other-windows)
  12000. (move-marker org-log-note-return-to (point))
  12001. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12002. (goto-char org-log-note-marker)
  12003. (org-switch-to-buffer-other-window "*Org Note*")
  12004. (erase-buffer)
  12005. (if (memq org-log-note-how '(time state))
  12006. (org-store-log-note)
  12007. (let ((org-inhibit-startup t)) (org-mode))
  12008. (insert (format "# Insert note for %s.
  12009. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12010. (cond
  12011. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12012. ((eq org-log-note-purpose 'done) "closed todo item")
  12013. ((eq org-log-note-purpose 'state)
  12014. (format "state change from \"%s\" to \"%s\""
  12015. (or org-log-note-previous-state "")
  12016. (or org-log-note-state "")))
  12017. ((eq org-log-note-purpose 'reschedule)
  12018. "rescheduling")
  12019. ((eq org-log-note-purpose 'delschedule)
  12020. "no longer scheduled")
  12021. ((eq org-log-note-purpose 'redeadline)
  12022. "changing deadline")
  12023. ((eq org-log-note-purpose 'deldeadline)
  12024. "removing deadline")
  12025. ((eq org-log-note-purpose 'refile)
  12026. "refiling")
  12027. ((eq org-log-note-purpose 'note)
  12028. "this entry")
  12029. (t (error "This should not happen")))))
  12030. (when org-log-note-extra (insert org-log-note-extra))
  12031. (setq-local org-finish-function 'org-store-log-note)
  12032. (run-hooks 'org-log-buffer-setup-hook)))
  12033. (defvar org-note-abort nil) ; dynamically scoped
  12034. (defun org-store-log-note ()
  12035. "Finish taking a log note, and insert it to where it belongs."
  12036. (let ((txt (prog1 (buffer-string)
  12037. (kill-buffer)))
  12038. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12039. lines)
  12040. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12041. (setq txt (replace-match "" t t txt)))
  12042. (when (string-match "\\s-+\\'" txt)
  12043. (setq txt (replace-match "" t t txt)))
  12044. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12045. (when (org-string-nw-p note)
  12046. (setq note
  12047. (org-replace-escapes
  12048. note
  12049. (list (cons "%u" (user-login-name))
  12050. (cons "%U" user-full-name)
  12051. (cons "%t" (format-time-string
  12052. (org-time-stamp-format 'long 'inactive)
  12053. org-log-note-effective-time))
  12054. (cons "%T" (format-time-string
  12055. (org-time-stamp-format 'long nil)
  12056. org-log-note-effective-time))
  12057. (cons "%d" (format-time-string
  12058. (org-time-stamp-format nil 'inactive)
  12059. org-log-note-effective-time))
  12060. (cons "%D" (format-time-string
  12061. (org-time-stamp-format nil nil)
  12062. org-log-note-effective-time))
  12063. (cons "%s" (cond
  12064. ((not org-log-note-state) "")
  12065. ((string-match-p org-ts-regexp
  12066. org-log-note-state)
  12067. (format "\"[%s]\""
  12068. (substring org-log-note-state 1 -1)))
  12069. (t (format "\"%s\"" org-log-note-state))))
  12070. (cons "%S"
  12071. (cond
  12072. ((not org-log-note-previous-state) "")
  12073. ((string-match-p org-ts-regexp
  12074. org-log-note-previous-state)
  12075. (format "\"[%s]\""
  12076. (substring
  12077. org-log-note-previous-state 1 -1)))
  12078. (t (format "\"%s\""
  12079. org-log-note-previous-state)))))))
  12080. (when lines (setq note (concat note " \\\\")))
  12081. (push note lines))
  12082. (when (and lines (not org-note-abort))
  12083. (with-current-buffer (marker-buffer org-log-note-marker)
  12084. (org-with-wide-buffer
  12085. ;; Find location for the new note.
  12086. (goto-char org-log-note-marker)
  12087. (set-marker org-log-note-marker nil)
  12088. ;; Note associated to a clock is to be located right after
  12089. ;; the clock. Do not move point.
  12090. (unless (eq org-log-note-purpose 'clock-out)
  12091. (goto-char (org-log-beginning t)))
  12092. ;; Make sure point is at the beginning of an empty line.
  12093. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12094. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12095. ;; In an existing list, add a new item at the top level.
  12096. ;; Otherwise, indent line like a regular one.
  12097. (let ((itemp (org-in-item-p)))
  12098. (if itemp
  12099. (indent-line-to
  12100. (let ((struct (save-excursion
  12101. (goto-char itemp) (org-list-struct))))
  12102. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12103. (org-indent-line)))
  12104. (insert (org-list-bullet-string "-") (pop lines))
  12105. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12106. (dolist (line lines)
  12107. (insert "\n")
  12108. (indent-line-to ind)
  12109. (insert line)))
  12110. (message "Note stored")
  12111. (org-back-to-heading t)
  12112. (org-cycle-hide-drawers 'children))
  12113. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12114. ;; from within `org-add-log-note' because `buffer-undo-list'
  12115. ;; is then modified outside of `org-with-remote-undo'.
  12116. (when (eq this-command 'org-agenda-todo)
  12117. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12118. ;; Don't add undo information when called from `org-agenda-todo'.
  12119. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12120. (set-window-configuration org-log-note-window-configuration)
  12121. (with-current-buffer (marker-buffer org-log-note-return-to)
  12122. (goto-char org-log-note-return-to))
  12123. (move-marker org-log-note-return-to nil)
  12124. (when org-log-post-message (message "%s" org-log-post-message))))
  12125. (defun org-remove-empty-drawer-at (pos)
  12126. "Remove an empty drawer at position POS.
  12127. POS may also be a marker."
  12128. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12129. (org-with-wide-buffer
  12130. (goto-char pos)
  12131. (let ((drawer (org-element-at-point)))
  12132. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12133. (not (org-element-property :contents-begin drawer)))
  12134. (delete-region (org-element-property :begin drawer)
  12135. (progn (goto-char (org-element-property :end drawer))
  12136. (skip-chars-backward " \r\t\n")
  12137. (forward-line)
  12138. (point))))))))
  12139. (defvar org-ts-type nil)
  12140. (defun org-sparse-tree (&optional arg type)
  12141. "Create a sparse tree, prompt for the details.
  12142. This command can create sparse trees. You first need to select the type
  12143. of match used to create the tree:
  12144. t Show all TODO entries.
  12145. T Show entries with a specific TODO keyword.
  12146. m Show entries selected by a tags/property match.
  12147. p Enter a property name and its value (both with completion on existing
  12148. names/values) and show entries with that property.
  12149. r Show entries matching a regular expression (`/' can be used as well).
  12150. b Show deadlines and scheduled items before a date.
  12151. a Show deadlines and scheduled items after a date.
  12152. d Show deadlines due within `org-deadline-warning-days'.
  12153. D Show deadlines and scheduled items between a date range."
  12154. (interactive "P")
  12155. (setq type (or type org-sparse-tree-default-date-type))
  12156. (setq org-ts-type type)
  12157. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12158. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12159. \[c]ycle through date types: %s"
  12160. (cl-case type
  12161. (all "all timestamps")
  12162. (scheduled "only scheduled")
  12163. (deadline "only deadline")
  12164. (active "only active timestamps")
  12165. (inactive "only inactive timestamps")
  12166. (closed "with a closed time-stamp")
  12167. (otherwise "scheduled/deadline")))
  12168. (let ((answer (read-char-exclusive)))
  12169. (cl-case answer
  12170. (?c
  12171. (org-sparse-tree
  12172. arg
  12173. (cadr
  12174. (memq type '(nil all scheduled deadline active inactive closed)))))
  12175. (?d (call-interactively 'org-check-deadlines))
  12176. (?b (call-interactively 'org-check-before-date))
  12177. (?a (call-interactively 'org-check-after-date))
  12178. (?D (call-interactively 'org-check-dates-range))
  12179. (?t (call-interactively 'org-show-todo-tree))
  12180. (?T (org-show-todo-tree '(4)))
  12181. (?m (call-interactively 'org-match-sparse-tree))
  12182. ((?p ?P)
  12183. (let* ((kwd (completing-read
  12184. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12185. (value (completing-read
  12186. "Value: " (mapcar #'list (org-property-values kwd)))))
  12187. (unless (string-match "\\`{.*}\\'" value)
  12188. (setq value (concat "\"" value "\"")))
  12189. (org-match-sparse-tree arg (concat kwd "=" value))))
  12190. ((?r ?R ?/) (call-interactively 'org-occur))
  12191. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12192. (defvar-local org-occur-highlights nil
  12193. "List of overlays used for occur matches.")
  12194. (defvar-local org-occur-parameters nil
  12195. "Parameters of the active org-occur calls.
  12196. This is a list, each call to org-occur pushes as cons cell,
  12197. containing the regular expression and the callback, onto the list.
  12198. The list can contain several entries if `org-occur' has been called
  12199. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12200. will only contain one set of parameters. When the highlights are
  12201. removed (for example with `C-c C-c', or with the next edit (depending
  12202. on `org-remove-highlights-with-change'), this variable is emptied
  12203. as well.")
  12204. (defun org-occur (regexp &optional keep-previous callback)
  12205. "Make a compact tree which shows all matches of REGEXP.
  12206. The tree will show the lines where the regexp matches, and any other context
  12207. defined in `org-show-context-detail', which see.
  12208. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12209. done by a previous call to `org-occur' will be kept, to allow stacking of
  12210. calls to this command.
  12211. Optional argument CALLBACK can be a function of no argument. In this case,
  12212. it is called with point at the end of the match, match data being set
  12213. accordingly. Current match is shown only if the return value is non-nil.
  12214. The function must neither move point nor alter narrowing."
  12215. (interactive "sRegexp: \nP")
  12216. (when (equal regexp "")
  12217. (user-error "Regexp cannot be empty"))
  12218. (unless keep-previous
  12219. (org-remove-occur-highlights nil nil t))
  12220. (push (cons regexp callback) org-occur-parameters)
  12221. (let ((cnt 0))
  12222. (save-excursion
  12223. (goto-char (point-min))
  12224. (when (or (not keep-previous) ; do not want to keep
  12225. (not org-occur-highlights)) ; no previous matches
  12226. ;; hide everything
  12227. (org-overview))
  12228. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12229. (isearch-no-upper-case-p regexp t)
  12230. org-occur-case-fold-search)))
  12231. (while (re-search-forward regexp nil t)
  12232. (when (or (not callback)
  12233. (save-match-data (funcall callback)))
  12234. (setq cnt (1+ cnt))
  12235. (when org-highlight-sparse-tree-matches
  12236. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12237. (org-show-context 'occur-tree)))))
  12238. (when org-remove-highlights-with-change
  12239. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12240. nil 'local))
  12241. (unless org-sparse-tree-open-archived-trees
  12242. (org-hide-archived-subtrees (point-min) (point-max)))
  12243. (run-hooks 'org-occur-hook)
  12244. (when (called-interactively-p 'interactive)
  12245. (message "%d match(es) for regexp %s" cnt regexp))
  12246. cnt))
  12247. (defun org-occur-next-match (&optional n _reset)
  12248. "Function for `next-error-function' to find sparse tree matches.
  12249. N is the number of matches to move, when negative move backwards.
  12250. This function always goes back to the starting point when no
  12251. match is found."
  12252. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12253. (search-func (if (< n 0)
  12254. 'previous-single-char-property-change
  12255. 'next-single-char-property-change))
  12256. (n (abs n))
  12257. (pos (point))
  12258. p1)
  12259. (catch 'exit
  12260. (while (setq p1 (funcall search-func (point) 'org-type))
  12261. (when (equal p1 limit)
  12262. (goto-char pos)
  12263. (user-error "No more matches"))
  12264. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12265. (setq n (1- n))
  12266. (when (= n 0)
  12267. (goto-char p1)
  12268. (throw 'exit (point))))
  12269. (goto-char p1))
  12270. (goto-char p1)
  12271. (user-error "No more matches"))))
  12272. (defun org-show-context (&optional key)
  12273. "Make sure point and context are visible.
  12274. Optional argument KEY, when non-nil, is a symbol. See
  12275. `org-show-context-detail' for allowed values and how much is to
  12276. be shown."
  12277. (org-show-set-visibility
  12278. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12279. ((cdr (assq key org-show-context-detail)))
  12280. (t (cdr (assq 'default org-show-context-detail))))))
  12281. (defun org-show-set-visibility (detail)
  12282. "Set visibility around point according to DETAIL.
  12283. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12284. `tree', `canonical' or t. See `org-show-context-detail' for more
  12285. information."
  12286. ;; Show current heading and possibly its entry, following headline
  12287. ;; or all children.
  12288. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12289. (org-flag-heading nil)
  12290. (org-show-entry)
  12291. ;; If point is hidden within a drawer or a block, make sure to
  12292. ;; expose it.
  12293. (dolist (o (overlays-at (point)))
  12294. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12295. (delete-overlay o)))
  12296. (unless (org-before-first-heading-p)
  12297. (org-with-limited-levels
  12298. (cl-case detail
  12299. ((tree canonical t) (org-show-children))
  12300. ((nil minimal ancestors))
  12301. (t (save-excursion
  12302. (outline-next-heading)
  12303. (org-flag-heading nil)))))))
  12304. ;; Show all siblings.
  12305. (when (eq detail 'lineage) (org-show-siblings))
  12306. ;; Show ancestors, possibly with their children.
  12307. (when (memq detail '(ancestors lineage tree canonical t))
  12308. (save-excursion
  12309. (while (org-up-heading-safe)
  12310. (org-flag-heading nil)
  12311. (when (memq detail '(canonical t)) (org-show-entry))
  12312. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12313. (defvar org-reveal-start-hook nil
  12314. "Hook run before revealing a location.")
  12315. (defun org-reveal (&optional siblings)
  12316. "Show current entry, hierarchy above it, and the following headline.
  12317. This can be used to show a consistent set of context around
  12318. locations exposed with `org-show-context'.
  12319. With optional argument SIBLINGS, on each level of the hierarchy all
  12320. siblings are shown. This repairs the tree structure to what it would
  12321. look like when opened with hierarchical calls to `org-cycle'.
  12322. With a \\[universal-argument] \\[universal-argument] prefix, \
  12323. go to the parent and show the entire tree."
  12324. (interactive "P")
  12325. (run-hooks 'org-reveal-start-hook)
  12326. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12327. ((equal siblings '(16))
  12328. (save-excursion
  12329. (when (org-up-heading-safe)
  12330. (org-show-subtree)
  12331. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12332. (t (org-show-set-visibility 'lineage))))
  12333. (defun org-highlight-new-match (beg end)
  12334. "Highlight from BEG to END and mark the highlight is an occur headline."
  12335. (let ((ov (make-overlay beg end)))
  12336. (overlay-put ov 'face 'secondary-selection)
  12337. (overlay-put ov 'org-type 'org-occur)
  12338. (push ov org-occur-highlights)))
  12339. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12340. "Remove the occur highlights from the buffer.
  12341. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12342. from the `before-change-functions' in the current buffer."
  12343. (interactive)
  12344. (unless org-inhibit-highlight-removal
  12345. (mapc #'delete-overlay org-occur-highlights)
  12346. (setq org-occur-highlights nil)
  12347. (setq org-occur-parameters nil)
  12348. (unless noremove
  12349. (remove-hook 'before-change-functions
  12350. 'org-remove-occur-highlights 'local))))
  12351. ;;;; Priorities
  12352. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12353. "Regular expression matching the priority indicator.")
  12354. (defvar org-remove-priority-next-time nil)
  12355. (defun org-priority-up ()
  12356. "Increase the priority of the current item."
  12357. (interactive)
  12358. (org-priority 'up))
  12359. (defun org-priority-down ()
  12360. "Decrease the priority of the current item."
  12361. (interactive)
  12362. (org-priority 'down))
  12363. (defun org-priority (&optional action _show)
  12364. "Change the priority of an item.
  12365. ACTION can be `set', `up', `down', or a character."
  12366. (interactive "P")
  12367. (if (equal action '(4))
  12368. (org-show-priority)
  12369. (unless org-enable-priority-commands
  12370. (user-error "Priority commands are disabled"))
  12371. (setq action (or action 'set))
  12372. (let (current new news have remove)
  12373. (save-excursion
  12374. (org-back-to-heading t)
  12375. (when (looking-at org-priority-regexp)
  12376. (setq current (string-to-char (match-string 2))
  12377. have t))
  12378. (cond
  12379. ((eq action 'remove)
  12380. (setq remove t new ?\ ))
  12381. ((or (eq action 'set)
  12382. (integerp action))
  12383. (if (not (eq action 'set))
  12384. (setq new action)
  12385. (message "Priority %c-%c, SPC to remove: "
  12386. org-highest-priority org-lowest-priority)
  12387. (save-match-data
  12388. (setq new (read-char-exclusive))))
  12389. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12390. (= (upcase org-lowest-priority) org-lowest-priority))
  12391. (setq new (upcase new)))
  12392. (cond ((equal new ?\ ) (setq remove t))
  12393. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12394. (user-error "Priority must be between `%c' and `%c'"
  12395. org-highest-priority org-lowest-priority))))
  12396. ((eq action 'up)
  12397. (setq new (if have
  12398. (1- current) ; normal cycling
  12399. ;; last priority was empty
  12400. (if (eq last-command this-command)
  12401. org-lowest-priority ; wrap around empty to lowest
  12402. ;; default
  12403. (if org-priority-start-cycle-with-default
  12404. org-default-priority
  12405. (1- org-default-priority))))))
  12406. ((eq action 'down)
  12407. (setq new (if have
  12408. (1+ current) ; normal cycling
  12409. ;; last priority was empty
  12410. (if (eq last-command this-command)
  12411. org-highest-priority ; wrap around empty to highest
  12412. ;; default
  12413. (if org-priority-start-cycle-with-default
  12414. org-default-priority
  12415. (1+ org-default-priority))))))
  12416. (t (user-error "Invalid action")))
  12417. (when (or (< (upcase new) org-highest-priority)
  12418. (> (upcase new) org-lowest-priority))
  12419. (if (and (memq action '(up down))
  12420. (not have) (not (eq last-command this-command)))
  12421. ;; `new' is from default priority
  12422. (error
  12423. "The default can not be set, see `org-default-priority' why")
  12424. ;; normal cycling: `new' is beyond highest/lowest priority
  12425. ;; and is wrapped around to the empty priority
  12426. (setq remove t)))
  12427. (setq news (format "%c" new))
  12428. (if have
  12429. (if remove
  12430. (replace-match "" t t nil 1)
  12431. (replace-match news t t nil 2))
  12432. (if remove
  12433. (user-error "No priority cookie found in line")
  12434. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12435. (if (match-end 2)
  12436. (progn
  12437. (goto-char (match-end 2))
  12438. (insert " [#" news "]"))
  12439. (goto-char (match-beginning 3))
  12440. (insert "[#" news "] "))))
  12441. (org-set-tags nil 'align))
  12442. (if remove
  12443. (message "Priority removed")
  12444. (message "Priority of current item set to %s" news)))))
  12445. (defun org-show-priority ()
  12446. "Show the priority of the current item.
  12447. This priority is composed of the main priority given with the [#A] cookies,
  12448. and by additional input from the age of a schedules or deadline entry."
  12449. (interactive)
  12450. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12451. (org-get-at-bol 'priority)
  12452. (save-excursion
  12453. (save-match-data
  12454. (beginning-of-line)
  12455. (and (looking-at org-heading-regexp)
  12456. (org-get-priority (match-string 0))))))))
  12457. (message "Priority is %d" (if pri pri -1000))))
  12458. (defun org-get-priority (s)
  12459. "Find priority cookie and return priority."
  12460. (save-match-data
  12461. (if (functionp org-get-priority-function)
  12462. (funcall org-get-priority-function)
  12463. (if (not (string-match org-priority-regexp s))
  12464. (* 1000 (- org-lowest-priority org-default-priority))
  12465. (* 1000 (- org-lowest-priority
  12466. (string-to-char (match-string 2 s))))))))
  12467. ;;;; Tags
  12468. (defvar org-agenda-archives-mode)
  12469. (defvar org-map-continue-from nil
  12470. "Position from where mapping should continue.
  12471. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12472. (defvar org-scanner-tags nil
  12473. "The current tag list while the tags scanner is running.")
  12474. (defvar org-trust-scanner-tags nil
  12475. "Should `org-get-tags-at' use the tags for the scanner.
  12476. This is for internal dynamical scoping only.
  12477. When this is non-nil, the function `org-get-tags-at' will return the value
  12478. of `org-scanner-tags' instead of building the list by itself. This
  12479. can lead to large speed-ups when the tags scanner is used in a file with
  12480. many entries, and when the list of tags is retrieved, for example to
  12481. obtain a list of properties. Building the tags list for each entry in such
  12482. a file becomes an N^2 operation - but with this variable set, it scales
  12483. as N.")
  12484. (defvar org--matcher-tags-todo-only nil)
  12485. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12486. "Scan headline tags with inheritance and produce output ACTION.
  12487. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12488. or `agenda' to produce an entry list for an agenda view. It can also be
  12489. a Lisp form or a function that should be called at each matched headline, in
  12490. this case the return value is a list of all return values from these calls.
  12491. MATCHER is a function accepting three arguments, returning
  12492. a non-nil value whenever a given set of tags qualifies a headline
  12493. for inclusion. See `org-make-tags-matcher' for more information.
  12494. As a special case, it can also be set to t (respectively nil) in
  12495. order to match all (respectively none) headline.
  12496. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12497. included in the output.
  12498. START-LEVEL can be a string with asterisks, reducing the scope to
  12499. headlines matching this string."
  12500. (require 'org-agenda)
  12501. (let* ((re (concat "^"
  12502. (if start-level
  12503. ;; Get the correct level to match
  12504. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12505. org-outline-regexp)
  12506. " *\\(\\<\\("
  12507. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12508. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12509. (props (list 'face 'default
  12510. 'done-face 'org-agenda-done
  12511. 'undone-face 'default
  12512. 'mouse-face 'highlight
  12513. 'org-not-done-regexp org-not-done-regexp
  12514. 'org-todo-regexp org-todo-regexp
  12515. 'org-complex-heading-regexp org-complex-heading-regexp
  12516. 'help-echo
  12517. (format "mouse-2 or RET jump to org file %s"
  12518. (abbreviate-file-name
  12519. (or (buffer-file-name (buffer-base-buffer))
  12520. (buffer-name (buffer-base-buffer)))))))
  12521. (org-map-continue-from nil)
  12522. lspos tags tags-list
  12523. (tags-alist (list (cons 0 org-file-tags)))
  12524. (llast 0) rtn rtn1 level category i txt
  12525. todo marker entry priority
  12526. ts-date ts-date-type ts-date-pair)
  12527. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12528. (setq action (list 'lambda nil action)))
  12529. (save-excursion
  12530. (goto-char (point-min))
  12531. (when (eq action 'sparse-tree)
  12532. (org-overview)
  12533. (org-remove-occur-highlights))
  12534. (while (let (case-fold-search)
  12535. (re-search-forward re nil t))
  12536. (setq org-map-continue-from nil)
  12537. (catch :skip
  12538. (setq todo
  12539. ;; TODO: is the 1-2 difference a bug?
  12540. (when (match-end 1) (match-string-no-properties 2))
  12541. tags (when (match-end 4) (match-string-no-properties 4)))
  12542. (goto-char (setq lspos (match-beginning 0)))
  12543. (setq level (org-reduced-level (org-outline-level))
  12544. category (org-get-category))
  12545. (when (eq action 'agenda)
  12546. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12547. ts-date (car ts-date-pair)
  12548. ts-date-type (cdr ts-date-pair)))
  12549. (setq i llast llast level)
  12550. ;; remove tag lists from same and sublevels
  12551. (while (>= i level)
  12552. (when (setq entry (assoc i tags-alist))
  12553. (setq tags-alist (delete entry tags-alist)))
  12554. (setq i (1- i)))
  12555. ;; add the next tags
  12556. (when tags
  12557. (setq tags (org-split-string tags ":")
  12558. tags-alist
  12559. (cons (cons level tags) tags-alist)))
  12560. ;; compile tags for current headline
  12561. (setq tags-list
  12562. (if org-use-tag-inheritance
  12563. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12564. tags)
  12565. org-scanner-tags tags-list)
  12566. (when org-use-tag-inheritance
  12567. (setcdr (car tags-alist)
  12568. (mapcar (lambda (x)
  12569. (setq x (copy-sequence x))
  12570. (org-add-prop-inherited x))
  12571. (cdar tags-alist))))
  12572. (when (and tags org-use-tag-inheritance
  12573. (or (not (eq t org-use-tag-inheritance))
  12574. org-tags-exclude-from-inheritance))
  12575. ;; Selective inheritance, remove uninherited ones.
  12576. (setcdr (car tags-alist)
  12577. (org-remove-uninherited-tags (cdar tags-alist))))
  12578. (when (and
  12579. ;; eval matcher only when the todo condition is OK
  12580. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12581. (if (functionp matcher)
  12582. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12583. (funcall matcher todo tags-list level))
  12584. matcher))
  12585. ;; Call the skipper, but return t if it does not
  12586. ;; skip, so that the `and' form continues evaluating.
  12587. (progn
  12588. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12589. t)
  12590. ;; Check if timestamps are deselecting this entry
  12591. (or (not todo-only)
  12592. (and (member todo org-todo-keywords-1)
  12593. (or (not org-agenda-tags-todo-honor-ignore-options)
  12594. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12595. ;; select this headline
  12596. (cond
  12597. ((eq action 'sparse-tree)
  12598. (and org-highlight-sparse-tree-matches
  12599. (org-get-heading) (match-end 0)
  12600. (org-highlight-new-match
  12601. (match-beginning 1) (match-end 1)))
  12602. (org-show-context 'tags-tree))
  12603. ((eq action 'agenda)
  12604. (setq txt (org-agenda-format-item
  12605. ""
  12606. (concat
  12607. (if (eq org-tags-match-list-sublevels 'indented)
  12608. (make-string (1- level) ?.) "")
  12609. (org-get-heading))
  12610. (make-string level ?\s)
  12611. category
  12612. tags-list)
  12613. priority (org-get-priority txt))
  12614. (goto-char lspos)
  12615. (setq marker (org-agenda-new-marker))
  12616. (org-add-props txt props
  12617. 'org-marker marker 'org-hd-marker marker 'org-category category
  12618. 'todo-state todo
  12619. 'ts-date ts-date
  12620. 'priority priority
  12621. 'type (concat "tagsmatch" ts-date-type))
  12622. (push txt rtn))
  12623. ((functionp action)
  12624. (setq org-map-continue-from nil)
  12625. (save-excursion
  12626. (setq rtn1 (funcall action))
  12627. (push rtn1 rtn)))
  12628. (t (user-error "Invalid action")))
  12629. ;; if we are to skip sublevels, jump to end of subtree
  12630. (unless org-tags-match-list-sublevels
  12631. (org-end-of-subtree t)
  12632. (backward-char 1))))
  12633. ;; Get the correct position from where to continue
  12634. (if org-map-continue-from
  12635. (goto-char org-map-continue-from)
  12636. (and (= (point) lspos) (end-of-line 1)))))
  12637. (when (and (eq action 'sparse-tree)
  12638. (not org-sparse-tree-open-archived-trees))
  12639. (org-hide-archived-subtrees (point-min) (point-max)))
  12640. (nreverse rtn)))
  12641. (defun org-remove-uninherited-tags (tags)
  12642. "Remove all tags that are not inherited from the list TAGS."
  12643. (cond
  12644. ((eq org-use-tag-inheritance t)
  12645. (if org-tags-exclude-from-inheritance
  12646. (org-delete-all org-tags-exclude-from-inheritance tags)
  12647. tags))
  12648. ((not org-use-tag-inheritance) nil)
  12649. ((stringp org-use-tag-inheritance)
  12650. (delq nil (mapcar
  12651. (lambda (x)
  12652. (if (and (string-match org-use-tag-inheritance x)
  12653. (not (member x org-tags-exclude-from-inheritance)))
  12654. x nil))
  12655. tags)))
  12656. ((listp org-use-tag-inheritance)
  12657. (delq nil (mapcar
  12658. (lambda (x)
  12659. (if (member x org-use-tag-inheritance) x nil))
  12660. tags)))))
  12661. (defun org-match-sparse-tree (&optional todo-only match)
  12662. "Create a sparse tree according to tags string MATCH.
  12663. MATCH is a string with match syntax. It can contain a selection
  12664. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12665. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12666. those. See the manual for details.
  12667. If optional argument TODO-ONLY is non-nil, only select lines that
  12668. are also TODO tasks."
  12669. (interactive "P")
  12670. (org-agenda-prepare-buffers (list (current-buffer)))
  12671. (let ((org--matcher-tags-todo-only todo-only))
  12672. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12673. org--matcher-tags-todo-only)))
  12674. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12675. (defvar org-cached-props nil)
  12676. (defun org-cached-entry-get (pom property)
  12677. (if (or (eq t org-use-property-inheritance)
  12678. (and (stringp org-use-property-inheritance)
  12679. (let ((case-fold-search t))
  12680. (string-match-p org-use-property-inheritance property)))
  12681. (and (listp org-use-property-inheritance)
  12682. (member-ignore-case property org-use-property-inheritance)))
  12683. ;; Caching is not possible, check it directly.
  12684. (org-entry-get pom property 'inherit)
  12685. ;; Get all properties, so we can do complicated checks easily.
  12686. (cdr (assoc-string property
  12687. (or org-cached-props
  12688. (setq org-cached-props (org-entry-properties pom)))
  12689. t))))
  12690. (defun org-global-tags-completion-table (&optional files)
  12691. "Return the list of all tags in all agenda buffer/files.
  12692. Optional FILES argument is a list of files which can be used
  12693. instead of the agenda files."
  12694. (save-excursion
  12695. (org-uniquify
  12696. (delq nil
  12697. (apply #'append
  12698. (mapcar
  12699. (lambda (file)
  12700. (set-buffer (find-file-noselect file))
  12701. (mapcar (lambda (x)
  12702. (and (stringp (car-safe x))
  12703. (list (car-safe x))))
  12704. (or org-current-tag-alist (org-get-buffer-tags))))
  12705. (if (car-safe files) files
  12706. (org-agenda-files))))))))
  12707. (defun org-make-tags-matcher (match)
  12708. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12709. Returns a cons of the selection string MATCH and a function
  12710. implementing the matcher.
  12711. The matcher is to be called at an Org entry, with point on the
  12712. headline, and returns non-nil if the entry matches the selection
  12713. string MATCH. It must be called with three arguments: the TODO
  12714. keyword at the entry (or nil if none), the list of all tags at
  12715. the entry including inherited ones and the reduced level of the
  12716. headline. Additionally, the category of the entry, if any, must
  12717. be specified as the text property `org-category' on the headline.
  12718. This function sets the variable `org--matcher-tags-todo-only' to
  12719. a non-nil value if the matcher restricts matching to TODO
  12720. entries, otherwise it is not touched.
  12721. See also `org-scan-tags'."
  12722. (unless match
  12723. ;; Get a new match request, with completion against the global
  12724. ;; tags table and the local tags in current buffer.
  12725. (let ((org-last-tags-completion-table
  12726. (org-uniquify
  12727. (delq nil (append (org-get-buffer-tags)
  12728. (org-global-tags-completion-table))))))
  12729. (setq match
  12730. (completing-read
  12731. "Match: "
  12732. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12733. (let ((match0 match)
  12734. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12735. (start 0)
  12736. tagsmatch todomatch tagsmatcher todomatcher)
  12737. ;; Expand group tags.
  12738. (setq match (org-tags-expand match))
  12739. ;; Check if there is a TODO part of this match, which would be the
  12740. ;; part after a "/". To make sure that this slash is not part of
  12741. ;; a property value to be matched against, we also check that
  12742. ;; there is no / after that slash. First, find the last slash.
  12743. (let ((s 0))
  12744. (while (string-match "/+" match s)
  12745. (setq start (match-beginning 0))
  12746. (setq s (match-end 0))))
  12747. (if (and (string-match "/+" match start)
  12748. (not (string-match-p "\"" match start)))
  12749. ;; Match contains also a TODO-matching request.
  12750. (progn
  12751. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12752. (setq todomatch (substring match (match-end 0)))
  12753. (when (string-prefix-p "!" todomatch)
  12754. (setq org--matcher-tags-todo-only t)
  12755. (setq todomatch (substring todomatch 1)))
  12756. (when (string-match "\\`\\s-*\\'" todomatch)
  12757. (setq todomatch nil)))
  12758. ;; Only matching tags.
  12759. (setq tagsmatch match)
  12760. (setq todomatch nil))
  12761. ;; Make the tags matcher.
  12762. (when (org-string-nw-p tagsmatch)
  12763. (let ((orlist nil)
  12764. (orterms (org-split-string tagsmatch "|"))
  12765. term)
  12766. (while (setq term (pop orterms))
  12767. (while (and (equal (substring term -1) "\\") orterms)
  12768. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12769. (while (string-match re term)
  12770. (let* ((rest (substring term (match-end 0)))
  12771. (minus (and (match-end 1)
  12772. (equal (match-string 1 term) "-")))
  12773. (tag (save-match-data
  12774. (replace-regexp-in-string
  12775. "\\\\-" "-" (match-string 2 term))))
  12776. (regexp (eq (string-to-char tag) ?{))
  12777. (levelp (match-end 4))
  12778. (propp (match-end 5))
  12779. (mm
  12780. (cond
  12781. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12782. (levelp
  12783. `(,(org-op-to-function (match-string 3 term))
  12784. level
  12785. ,(string-to-number (match-string 4 term))))
  12786. (propp
  12787. (let* ((gv (pcase (upcase (match-string 5 term))
  12788. ("CATEGORY"
  12789. '(get-text-property (point) 'org-category))
  12790. ("TODO" 'todo)
  12791. (p `(org-cached-entry-get nil ,p))))
  12792. (pv (match-string 7 term))
  12793. (regexp (eq (string-to-char pv) ?{))
  12794. (strp (eq (string-to-char pv) ?\"))
  12795. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12796. (po (org-op-to-function (match-string 6 term)
  12797. (if timep 'time strp))))
  12798. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12799. (when timep (setq pv (org-matcher-time pv)))
  12800. (cond ((and regexp (eq po 'org<>))
  12801. `(not (string-match ,pv (or ,gv ""))))
  12802. (regexp `(string-match ,pv (or ,gv "")))
  12803. (strp `(,po (or ,gv "") ,pv))
  12804. (t
  12805. `(,po
  12806. (string-to-number (or ,gv ""))
  12807. ,(string-to-number pv))))))
  12808. (t `(member ,tag tags-list)))))
  12809. (push (if minus `(not ,mm) mm) tagsmatcher)
  12810. (setq term rest)))
  12811. (push `(and ,@tagsmatcher) orlist)
  12812. (setq tagsmatcher nil))
  12813. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12814. ;; Make the TODO matcher.
  12815. (when (org-string-nw-p todomatch)
  12816. (let ((orlist nil))
  12817. (dolist (term (org-split-string todomatch "|"))
  12818. (while (string-match re term)
  12819. (let* ((minus (and (match-end 1)
  12820. (equal (match-string 1 term) "-")))
  12821. (kwd (match-string 2 term))
  12822. (regexp (eq (string-to-char kwd) ?{))
  12823. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12824. `(equal todo ,kwd))))
  12825. (push (if minus `(not ,mm) mm) todomatcher))
  12826. (setq term (substring term (match-end 0))))
  12827. (push (if (> (length todomatcher) 1)
  12828. (cons 'and todomatcher)
  12829. (car todomatcher))
  12830. orlist)
  12831. (setq todomatcher nil))
  12832. (setq todomatcher (cons 'or orlist))))
  12833. ;; Return the string and function of the matcher. If no
  12834. ;; tags-specific or todo-specific matcher exists, match
  12835. ;; everything.
  12836. (let ((matcher (if (and tagsmatcher todomatcher)
  12837. `(and ,tagsmatcher ,todomatcher)
  12838. (or tagsmatcher todomatcher t))))
  12839. (when org--matcher-tags-todo-only
  12840. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12841. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12842. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12843. "Expand group tags in MATCH.
  12844. This replaces every group tag in MATCH with a regexp tag search.
  12845. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12846. will be replaced like this:
  12847. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12848. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12849. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12850. Replacing by a regexp preserves the structure of the match.
  12851. E.g., this expansion
  12852. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12853. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12854. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12855. A group tag in MATCH can contain regular expressions of its own.
  12856. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12857. will be replaced like this:
  12858. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12859. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12860. assumed to be a single group tag, and the function will return
  12861. the list of tags in this group.
  12862. When DOWNCASE is non-nil, expand downcased TAGS."
  12863. (if org-group-tags
  12864. (let* ((case-fold-search t)
  12865. (stable org-mode-syntax-table)
  12866. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12867. (taggroups (if downcased
  12868. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12869. taggroups)
  12870. taggroups))
  12871. (taggroups-keys (mapcar #'car taggroups))
  12872. (return-match (if downcased (downcase match) match))
  12873. (count 0)
  12874. (work-already-expanded tags-already-expanded)
  12875. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12876. ;; @ and _ are allowed as word-components in tags.
  12877. (modify-syntax-entry ?@ "w" stable)
  12878. (modify-syntax-entry ?_ "w" stable)
  12879. ;; Temporarily replace regexp-expressions in the match-expression.
  12880. (while (string-match "{.+?}" return-match)
  12881. (cl-incf count)
  12882. (push (match-string 0 return-match) regexps-in-match)
  12883. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12884. (while (and taggroups-keys
  12885. (with-syntax-table stable
  12886. (string-match
  12887. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12888. (regexp-opt taggroups-keys) "\\>\\)")
  12889. return-match)))
  12890. (let* ((dir (match-string 1 return-match))
  12891. (tag (match-string 2 return-match))
  12892. (tag (if downcased (downcase tag) tag)))
  12893. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12894. (member tag work-already-expanded))
  12895. (setq tags-in-group (assoc tag taggroups))
  12896. (push tag work-already-expanded)
  12897. ;; Recursively expand each tag in the group, if the tag hasn't
  12898. ;; already been expanded. Restore the match-data after all recursive calls.
  12899. (save-match-data
  12900. (let (tags-expanded)
  12901. (dolist (x (cdr tags-in-group))
  12902. (if (and (member x taggroups-keys)
  12903. (not (member x work-already-expanded)))
  12904. (setq tags-expanded
  12905. (delete-dups
  12906. (append
  12907. (org-tags-expand x t downcased
  12908. work-already-expanded)
  12909. tags-expanded)))
  12910. (setq tags-expanded
  12911. (append (list x) tags-expanded)))
  12912. (setq work-already-expanded
  12913. (delete-dups
  12914. (append tags-expanded
  12915. work-already-expanded))))
  12916. (setq tags-in-group
  12917. (delete-dups (cons (car tags-in-group)
  12918. tags-expanded)))))
  12919. ;; Filter tag-regexps from tags.
  12920. (setq regexp-in-group-escaped
  12921. (delq nil (mapcar (lambda (x)
  12922. (if (stringp x)
  12923. (and (equal "{" (substring x 0 1))
  12924. (equal "}" (substring x -1))
  12925. x)
  12926. x))
  12927. tags-in-group))
  12928. regexp-in-group
  12929. (mapcar (lambda (x)
  12930. (substring x 1 -1))
  12931. regexp-in-group-escaped)
  12932. tags-in-group
  12933. (delq nil (mapcar (lambda (x)
  12934. (if (stringp x)
  12935. (and (not (equal "{" (substring x 0 1)))
  12936. (not (equal "}" (substring x -1)))
  12937. x)
  12938. x))
  12939. tags-in-group)))
  12940. ;; If single-as-list, do no more in the while-loop.
  12941. (if (not single-as-list)
  12942. (progn
  12943. (when regexp-in-group
  12944. (setq regexp-in-group
  12945. (concat "\\|"
  12946. (mapconcat 'identity regexp-in-group
  12947. "\\|"))))
  12948. (setq tags-in-group
  12949. (concat dir
  12950. "{\\<"
  12951. (regexp-opt tags-in-group)
  12952. "\\>"
  12953. regexp-in-group
  12954. "}"))
  12955. (when (stringp tags-in-group)
  12956. (org-add-props tags-in-group '(grouptag t)))
  12957. (setq return-match
  12958. (replace-match tags-in-group t t return-match)))
  12959. (setq tags-in-group
  12960. (append regexp-in-group-escaped tags-in-group))))
  12961. (setq taggroups-keys (delete tag taggroups-keys))))
  12962. ;; Add the regular expressions back into the match-expression again.
  12963. (while regexps-in-match
  12964. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12965. (pop regexps-in-match)
  12966. return-match t t))
  12967. (cl-decf count))
  12968. (if single-as-list
  12969. (if tags-in-group tags-in-group (list return-match))
  12970. return-match))
  12971. (if single-as-list
  12972. (list (if downcased (downcase match) match))
  12973. match)))
  12974. (defun org-op-to-function (op &optional stringp)
  12975. "Turn an operator into the appropriate function."
  12976. (setq op
  12977. (cond
  12978. ((equal op "<" ) '(< string< org-time<))
  12979. ((equal op ">" ) '(> org-string> org-time>))
  12980. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12981. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12982. ((member op '("=" "==")) '(= string= org-time=))
  12983. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  12984. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12985. (defun org<> (a b) (not (= a b)))
  12986. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  12987. (defun org-string>= (a b) (not (string< a b)))
  12988. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  12989. (defun org-string<> (a b) (not (string= a b)))
  12990. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  12991. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  12992. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  12993. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  12994. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  12995. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  12996. (defun org-2ft (s)
  12997. "Convert S to a floating point time.
  12998. If S is already a number, just return it. If it is a string, parse
  12999. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13000. (cond
  13001. ((numberp s) s)
  13002. ((stringp s)
  13003. (condition-case nil
  13004. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  13005. (error 0.)))
  13006. (t 0.)))
  13007. (defun org-time-today ()
  13008. "Time in seconds today at 0:00.
  13009. Returns the float number of seconds since the beginning of the
  13010. epoch to the beginning of today (00:00)."
  13011. (float-time (apply 'encode-time
  13012. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13013. (defun org-matcher-time (s)
  13014. "Interpret a time comparison value."
  13015. (save-match-data
  13016. (cond
  13017. ((string= s "<now>") (float-time))
  13018. ((string= s "<today>") (org-time-today))
  13019. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13020. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13021. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13022. (+ (org-time-today)
  13023. (* (string-to-number (match-string 1 s))
  13024. (cdr (assoc (match-string 2 s)
  13025. '(("d" . 86400.0) ("w" . 604800.0)
  13026. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13027. (t (org-2ft s)))))
  13028. (defun org-match-any-p (re list)
  13029. "Does re match any element of list?"
  13030. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13031. (delq nil list))
  13032. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13033. (defvar org-tags-overlay (make-overlay 1 1))
  13034. (delete-overlay org-tags-overlay)
  13035. (defun org-get-local-tags-at (&optional pos)
  13036. "Get a list of tags defined in the current headline."
  13037. (org-get-tags-at pos 'local))
  13038. (defun org-get-local-tags ()
  13039. "Get a list of tags defined in the current headline."
  13040. (org-get-tags-at nil 'local))
  13041. (defun org-get-tags-at (&optional pos local)
  13042. "Get a list of all headline tags applicable at POS.
  13043. POS defaults to point. If tags are inherited, the list contains
  13044. the targets in the same sequence as the headlines appear, i.e.
  13045. the tags of the current headline come last.
  13046. When LOCAL is non-nil, only return tags from the current headline,
  13047. ignore inherited ones."
  13048. (interactive)
  13049. (if (and org-trust-scanner-tags
  13050. (or (not pos) (equal pos (point)))
  13051. (not local))
  13052. org-scanner-tags
  13053. (let (tags ltags lastpos parent)
  13054. (save-excursion
  13055. (save-restriction
  13056. (widen)
  13057. (goto-char (or pos (point)))
  13058. (save-match-data
  13059. (catch 'done
  13060. (condition-case nil
  13061. (progn
  13062. (org-back-to-heading t)
  13063. (while (not (equal lastpos (point)))
  13064. (setq lastpos (point))
  13065. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13066. (setq ltags (org-split-string
  13067. (match-string-no-properties 1) ":"))
  13068. (when parent
  13069. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13070. (setq tags (append
  13071. (if parent
  13072. (org-remove-uninherited-tags ltags)
  13073. ltags)
  13074. tags)))
  13075. (or org-use-tag-inheritance (throw 'done t))
  13076. (when local (throw 'done t))
  13077. (or (org-up-heading-safe) (error nil))
  13078. (setq parent t)))
  13079. (error nil)))))
  13080. (if local
  13081. tags
  13082. (reverse (delete-dups
  13083. (reverse (append
  13084. (org-remove-uninherited-tags
  13085. org-file-tags)
  13086. tags)))))))))
  13087. (defun org-add-prop-inherited (s)
  13088. (add-text-properties 0 (length s) '(inherited t) s)
  13089. s)
  13090. (defun org-toggle-tag (tag &optional onoff)
  13091. "Toggle the tag TAG for the current line.
  13092. If ONOFF is `on' or `off', don't toggle but set to this state."
  13093. (save-excursion
  13094. (org-back-to-heading t)
  13095. (let ((current
  13096. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13097. (line-end-position) t)
  13098. (let ((tags (match-string 1)))
  13099. ;; Clear current tags.
  13100. (replace-match "")
  13101. ;; Reverse the tags list so any new tag is appended to
  13102. ;; the current list of tags.
  13103. (nreverse (org-split-string tags ":")))))
  13104. res)
  13105. (pcase onoff
  13106. (`off (setq current (delete tag current)))
  13107. ((or `on (guard (not (member tag current))))
  13108. (setq res t)
  13109. (cl-pushnew tag current :test #'equal))
  13110. (_ (setq current (delete tag current))))
  13111. (end-of-line)
  13112. (if current
  13113. (progn
  13114. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13115. (org-set-tags nil t))
  13116. (delete-horizontal-space))
  13117. (run-hooks 'org-after-tags-change-hook)
  13118. res)))
  13119. (defun org--align-tags-here (to-col)
  13120. "Align tags on the current headline to TO-COL.
  13121. Assume point is on a headline."
  13122. (let ((pos (point)))
  13123. (beginning-of-line)
  13124. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13125. (>= pos (match-beginning 2)))
  13126. ;; No tags or point within tags: do not align.
  13127. (goto-char pos)
  13128. (goto-char (match-beginning 1))
  13129. (let ((shift (max (- (if (>= to-col 0) to-col
  13130. (- (abs to-col) (string-width (match-string 2))))
  13131. (current-column))
  13132. 1)))
  13133. (replace-match (make-string shift ?\s) nil nil nil 1)
  13134. ;; Preserve initial position, if possible. In any case, stop
  13135. ;; before tags.
  13136. (when (< pos (point)) (goto-char pos))))))
  13137. (defun org-set-tags-command (&optional arg just-align)
  13138. "Call the set-tags command for the current entry."
  13139. (interactive "P")
  13140. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13141. (org-set-tags arg just-align)
  13142. (save-excursion
  13143. (unless (and (org-region-active-p)
  13144. org-loop-over-headlines-in-active-region)
  13145. (org-back-to-heading t))
  13146. (org-set-tags arg just-align))))
  13147. (defun org-set-tags-to (data)
  13148. "Set the tags of the current entry to DATA, replacing the current tags.
  13149. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13150. If DATA is nil or the empty string, any tags will be removed."
  13151. (interactive "sTags: ")
  13152. (setq data
  13153. (cond
  13154. ((eq data nil) "")
  13155. ((equal data "") "")
  13156. ((stringp data)
  13157. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13158. ":"))
  13159. ((listp data)
  13160. (concat ":" (mapconcat 'identity data ":") ":"))))
  13161. (when data
  13162. (save-excursion
  13163. (org-back-to-heading t)
  13164. (when (let ((case-fold-search nil))
  13165. (looking-at org-complex-heading-regexp))
  13166. (if (match-end 5)
  13167. (progn
  13168. (goto-char (match-beginning 5))
  13169. (insert data)
  13170. (delete-region (point) (point-at-eol))
  13171. (org-set-tags nil 'align))
  13172. (goto-char (point-at-eol))
  13173. (insert " " data)
  13174. (org-set-tags nil 'align)))
  13175. (beginning-of-line 1)
  13176. (when (looking-at ".*?\\([ \t]+\\)$")
  13177. (delete-region (match-beginning 1) (match-end 1))))))
  13178. (defun org-align-all-tags ()
  13179. "Align the tags in all headings."
  13180. (interactive)
  13181. (save-excursion
  13182. (or (ignore-errors (org-back-to-heading t))
  13183. (outline-next-heading))
  13184. (if (org-at-heading-p)
  13185. (org-set-tags t)
  13186. (message "No headings"))))
  13187. (defvar org-indent-indentation-per-level)
  13188. (defun org-set-tags (&optional arg just-align)
  13189. "Set the tags for the current headline.
  13190. With prefix ARG, realign all tags in headings in the current buffer.
  13191. When JUST-ALIGN is non-nil, only align tags."
  13192. (interactive "P")
  13193. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13194. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13195. 'region-start-level
  13196. 'region))
  13197. org-loop-over-headlines-in-active-region)
  13198. (org-map-entries
  13199. ;; We don't use ARG and JUST-ALIGN here because these args
  13200. ;; are not useful when looping over headlines.
  13201. #'org-set-tags
  13202. org-loop-over-headlines-in-active-region
  13203. cl
  13204. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13205. (let ((org-setting-tags t))
  13206. (if arg
  13207. (save-excursion
  13208. (goto-char (point-min))
  13209. (while (re-search-forward org-outline-regexp-bol nil t)
  13210. (org-set-tags nil t)
  13211. (end-of-line))
  13212. (message "All tags realigned to column %d" org-tags-column))
  13213. (let* ((current (org-get-tags-string))
  13214. (tags
  13215. (if just-align current
  13216. ;; Get a new set of tags from the user.
  13217. (save-excursion
  13218. (let* ((seen)
  13219. (table
  13220. (setq
  13221. org-last-tags-completion-table
  13222. ;; Uniquify tags in alists, yet preserve
  13223. ;; structure (i.e., keywords).
  13224. (delq nil
  13225. (mapcar
  13226. (lambda (pair)
  13227. (let ((head (car pair)))
  13228. (cond ((symbolp head) pair)
  13229. ((member head seen) nil)
  13230. (t (push head seen)
  13231. pair))))
  13232. (append
  13233. (or org-current-tag-alist
  13234. (org-get-buffer-tags))
  13235. (and
  13236. org-complete-tags-always-offer-all-agenda-tags
  13237. (org-global-tags-completion-table
  13238. (org-agenda-files))))))))
  13239. (current-tags (org-split-string current ":"))
  13240. (inherited-tags
  13241. (nreverse (nthcdr (length current-tags)
  13242. (nreverse (org-get-tags-at))))))
  13243. (replace-regexp-in-string
  13244. "\\([-+&]+\\|,\\)"
  13245. ":"
  13246. (if (or (eq t org-use-fast-tag-selection)
  13247. (and org-use-fast-tag-selection
  13248. (delq nil (mapcar #'cdr table))))
  13249. (org-fast-tag-selection
  13250. current-tags inherited-tags table
  13251. (and org-fast-tag-selection-include-todo
  13252. org-todo-key-alist))
  13253. (let ((org-add-colon-after-tag-completion
  13254. (< 1 (length table))))
  13255. (org-trim
  13256. (completing-read
  13257. "Tags: "
  13258. #'org-tags-completion-function
  13259. nil nil current 'org-tags-history))))))))))
  13260. (when org-tags-sort-function
  13261. (setq tags
  13262. (mapconcat
  13263. #'identity
  13264. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13265. org-tags-sort-function)
  13266. ":")))
  13267. (if (or (string= ":" tags)
  13268. (string= "::" tags))
  13269. (setq tags ""))
  13270. (if (not (org-string-nw-p tags)) (setq tags "")
  13271. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13272. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13273. ;; Insert new tags at the correct column.
  13274. (unless (equal current tags)
  13275. (save-excursion
  13276. (beginning-of-line)
  13277. (let ((case-fold-search nil))
  13278. (looking-at org-complex-heading-regexp))
  13279. ;; Remove current tags, if any.
  13280. (when (match-end 5) (replace-match "" nil nil nil 5))
  13281. ;; Insert new tags, if any. Otherwise, remove trailing
  13282. ;; white spaces.
  13283. (end-of-line)
  13284. (if (not (equal tags ""))
  13285. ;; When text is being inserted on an invisible
  13286. ;; region boundary, it can be inadvertently sucked
  13287. ;; into invisibility.
  13288. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13289. (skip-chars-backward " \t")
  13290. (delete-region (point) (line-end-position)))))
  13291. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13292. ;; is on.
  13293. (unless (equal tags "")
  13294. (let* ((level (save-excursion
  13295. (beginning-of-line)
  13296. (skip-chars-forward "\\*")))
  13297. (offset (if (bound-and-true-p org-indent-mode)
  13298. (* (1- org-indent-indentation-per-level)
  13299. (1- level))
  13300. 0))
  13301. (tags-column
  13302. (+ org-tags-column
  13303. (if (> org-tags-column 0) (- offset) offset))))
  13304. (org--align-tags-here tags-column))))
  13305. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13306. (defun org-change-tag-in-region (beg end tag off)
  13307. "Add or remove TAG for each entry in the region.
  13308. This works in the agenda, and also in an Org buffer."
  13309. (interactive
  13310. (list (region-beginning) (region-end)
  13311. (let ((org-last-tags-completion-table
  13312. (if (derived-mode-p 'org-mode)
  13313. (org-uniquify
  13314. (delq nil (append (org-get-buffer-tags)
  13315. (org-global-tags-completion-table))))
  13316. (org-global-tags-completion-table))))
  13317. (completing-read
  13318. "Tag: " 'org-tags-completion-function nil nil nil
  13319. 'org-tags-history))
  13320. (progn
  13321. (message "[s]et or [r]emove? ")
  13322. (equal (read-char-exclusive) ?r))))
  13323. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13324. (let ((agendap (equal major-mode 'org-agenda-mode))
  13325. l1 l2 m buf pos newhead (cnt 0))
  13326. (goto-char end)
  13327. (setq l2 (1- (org-current-line)))
  13328. (goto-char beg)
  13329. (setq l1 (org-current-line))
  13330. (cl-loop for l from l1 to l2 do
  13331. (org-goto-line l)
  13332. (setq m (get-text-property (point) 'org-hd-marker))
  13333. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13334. (and agendap m))
  13335. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13336. pos (if agendap m (point)))
  13337. (with-current-buffer buf
  13338. (save-excursion
  13339. (save-restriction
  13340. (goto-char pos)
  13341. (setq cnt (1+ cnt))
  13342. (org-toggle-tag tag (if off 'off 'on))
  13343. (setq newhead (org-get-heading)))))
  13344. (and agendap (org-agenda-change-all-lines newhead m))))
  13345. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13346. (defun org-tags-completion-function (string _predicate &optional flag)
  13347. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13348. (confirm (lambda (x) (stringp (car x)))))
  13349. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13350. (setq s1 (match-string 1 string)
  13351. s2 (match-string 2 string))
  13352. (setq s1 "" s2 string))
  13353. (cond
  13354. ((eq flag nil)
  13355. ;; try completion
  13356. (setq rtn (try-completion s2 ctable confirm))
  13357. (when (stringp rtn)
  13358. (setq rtn
  13359. (concat s1 s2 (substring rtn (length s2))
  13360. (if (and org-add-colon-after-tag-completion
  13361. (assoc rtn ctable))
  13362. ":" ""))))
  13363. rtn)
  13364. ((eq flag t)
  13365. ;; all-completions
  13366. (all-completions s2 ctable confirm))
  13367. ((eq flag 'lambda)
  13368. ;; exact match?
  13369. (assoc s2 ctable)))))
  13370. (defun org-fast-tag-insert (kwd tags face &optional end)
  13371. "Insert KDW, and the TAGS, the latter with face FACE.
  13372. Also insert END."
  13373. (insert (format "%-12s" (concat kwd ":"))
  13374. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13375. (or end "")))
  13376. (defun org-fast-tag-show-exit (flag)
  13377. (save-excursion
  13378. (org-goto-line 3)
  13379. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13380. (replace-match ""))
  13381. (when flag
  13382. (end-of-line 1)
  13383. (org-move-to-column (- (window-width) 19) t)
  13384. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13385. (defun org-set-current-tags-overlay (current prefix)
  13386. "Add an overlay to CURRENT tag with PREFIX."
  13387. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13388. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13389. (org-overlay-display org-tags-overlay (concat prefix s))))
  13390. (defvar org-last-tag-selection-key nil)
  13391. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13392. "Fast tag selection with single keys.
  13393. CURRENT is the current list of tags in the headline, INHERITED is the
  13394. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13395. possibly with grouping information. TODO-TABLE is a similar table with
  13396. TODO keywords, should these have keys assigned to them.
  13397. If the keys are nil, a-z are automatically assigned.
  13398. Returns the new tags string, or nil to not change the current settings."
  13399. (let* ((fulltable (append table todo-table))
  13400. (maxlen (apply 'max (mapcar
  13401. (lambda (x)
  13402. (if (stringp (car x)) (string-width (car x)) 0))
  13403. fulltable)))
  13404. (buf (current-buffer))
  13405. (expert (eq org-fast-tag-selection-single-key 'expert))
  13406. (buffer-tags nil)
  13407. (fwidth (+ maxlen 3 1 3))
  13408. (ncol (/ (- (window-width) 4) fwidth))
  13409. (i-face 'org-done)
  13410. (c-face 'org-todo)
  13411. tg cnt e c char c1 c2 ntable tbl rtn
  13412. ov-start ov-end ov-prefix
  13413. (exit-after-next org-fast-tag-selection-single-key)
  13414. (done-keywords org-done-keywords)
  13415. groups ingroup intaggroup)
  13416. (save-excursion
  13417. (beginning-of-line 1)
  13418. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13419. (setq ov-start (match-beginning 1)
  13420. ov-end (match-end 1)
  13421. ov-prefix "")
  13422. (setq ov-start (1- (point-at-eol))
  13423. ov-end (1+ ov-start))
  13424. (skip-chars-forward "^\n\r")
  13425. (setq ov-prefix
  13426. (concat
  13427. (buffer-substring (1- (point)) (point))
  13428. (if (> (current-column) org-tags-column)
  13429. " "
  13430. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13431. (move-overlay org-tags-overlay ov-start ov-end)
  13432. (save-window-excursion
  13433. (if expert
  13434. (set-buffer (get-buffer-create " *Org tags*"))
  13435. (delete-other-windows)
  13436. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13437. (org-switch-to-buffer-other-window " *Org tags*"))
  13438. (erase-buffer)
  13439. (setq-local org-done-keywords done-keywords)
  13440. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13441. (org-fast-tag-insert "Current" current c-face "\n\n")
  13442. (org-fast-tag-show-exit exit-after-next)
  13443. (org-set-current-tags-overlay current ov-prefix)
  13444. (setq tbl fulltable char ?a cnt 0)
  13445. (while (setq e (pop tbl))
  13446. (cond
  13447. ((eq (car e) :startgroup)
  13448. (push '() groups) (setq ingroup t)
  13449. (unless (zerop cnt)
  13450. (setq cnt 0)
  13451. (insert "\n"))
  13452. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13453. ((eq (car e) :endgroup)
  13454. (setq ingroup nil cnt 0)
  13455. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13456. ((eq (car e) :startgrouptag)
  13457. (setq intaggroup t)
  13458. (unless (zerop cnt)
  13459. (setq cnt 0)
  13460. (insert "\n"))
  13461. (insert "[ "))
  13462. ((eq (car e) :endgrouptag)
  13463. (setq intaggroup nil cnt 0)
  13464. (insert "]\n"))
  13465. ((equal e '(:newline))
  13466. (unless (zerop cnt)
  13467. (setq cnt 0)
  13468. (insert "\n")
  13469. (setq e (car tbl))
  13470. (while (equal (car tbl) '(:newline))
  13471. (insert "\n")
  13472. (setq tbl (cdr tbl)))))
  13473. ((equal e '(:grouptags)) (insert " : "))
  13474. (t
  13475. (setq tg (copy-sequence (car e)) c2 nil)
  13476. (if (cdr e)
  13477. (setq c (cdr e))
  13478. ;; automatically assign a character.
  13479. (setq c1 (string-to-char
  13480. (downcase (substring
  13481. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13482. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13483. (while (or (rassoc char ntable) (rassoc char table))
  13484. (setq char (1+ char)))
  13485. (setq c2 c1))
  13486. (setq c (or c2 char)))
  13487. (when ingroup (push tg (car groups)))
  13488. (setq tg (org-add-props tg nil 'face
  13489. (cond
  13490. ((not (assoc tg table))
  13491. (org-get-todo-face tg))
  13492. ((member tg current) c-face)
  13493. ((member tg inherited) i-face))))
  13494. (when (equal (caar tbl) :grouptags)
  13495. (org-add-props tg nil 'face 'org-tag-group))
  13496. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13497. (insert "[" c "] " tg (make-string
  13498. (- fwidth 4 (length tg)) ?\ ))
  13499. (push (cons tg c) ntable)
  13500. (when (= (cl-incf cnt) ncol)
  13501. (insert "\n")
  13502. (when (or ingroup intaggroup) (insert " "))
  13503. (setq cnt 0)))))
  13504. (setq ntable (nreverse ntable))
  13505. (insert "\n")
  13506. (goto-char (point-min))
  13507. (unless expert (org-fit-window-to-buffer))
  13508. (setq rtn
  13509. (catch 'exit
  13510. (while t
  13511. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13512. (if (not groups) "no " "")
  13513. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13514. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13515. (setq org-last-tag-selection-key c)
  13516. (cond
  13517. ((= c ?\r) (throw 'exit t))
  13518. ((= c ?!)
  13519. (setq groups (not groups))
  13520. (goto-char (point-min))
  13521. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13522. ((= c ?\C-c)
  13523. (if (not expert)
  13524. (org-fast-tag-show-exit
  13525. (setq exit-after-next (not exit-after-next)))
  13526. (setq expert nil)
  13527. (delete-other-windows)
  13528. (set-window-buffer (split-window-vertically) " *Org tags*")
  13529. (org-switch-to-buffer-other-window " *Org tags*")
  13530. (org-fit-window-to-buffer)))
  13531. ((or (= c ?\C-g)
  13532. (and (= c ?q) (not (rassoc c ntable))))
  13533. (delete-overlay org-tags-overlay)
  13534. (setq quit-flag t))
  13535. ((= c ?\ )
  13536. (setq current nil)
  13537. (when exit-after-next (setq exit-after-next 'now)))
  13538. ((= c ?\t)
  13539. (condition-case nil
  13540. (setq tg (completing-read
  13541. "Tag: "
  13542. (or buffer-tags
  13543. (with-current-buffer buf
  13544. (setq buffer-tags
  13545. (org-get-buffer-tags))))))
  13546. (quit (setq tg "")))
  13547. (when (string-match "\\S-" tg)
  13548. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13549. (if (member tg current)
  13550. (setq current (delete tg current))
  13551. (push tg current)))
  13552. (when exit-after-next (setq exit-after-next 'now)))
  13553. ((setq e (rassoc c todo-table) tg (car e))
  13554. (with-current-buffer buf
  13555. (save-excursion (org-todo tg)))
  13556. (when exit-after-next (setq exit-after-next 'now)))
  13557. ((setq e (rassoc c ntable) tg (car e))
  13558. (if (member tg current)
  13559. (setq current (delete tg current))
  13560. (cl-loop for g in groups do
  13561. (when (member tg g)
  13562. (dolist (x g) (setq current (delete x current)))))
  13563. (push tg current))
  13564. (when exit-after-next (setq exit-after-next 'now))))
  13565. ;; Create a sorted list
  13566. (setq current
  13567. (sort current
  13568. (lambda (a b)
  13569. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13570. (when (eq exit-after-next 'now) (throw 'exit t))
  13571. (goto-char (point-min))
  13572. (beginning-of-line 2)
  13573. (delete-region (point) (point-at-eol))
  13574. (org-fast-tag-insert "Current" current c-face)
  13575. (org-set-current-tags-overlay current ov-prefix)
  13576. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13577. (setq tg (match-string 1))
  13578. (add-text-properties
  13579. (match-beginning 1) (match-end 1)
  13580. (list 'face
  13581. (cond
  13582. ((member tg current) c-face)
  13583. ((member tg inherited) i-face)
  13584. (t (get-text-property (match-beginning 1) 'face))))))
  13585. (goto-char (point-min)))))
  13586. (delete-overlay org-tags-overlay)
  13587. (if rtn
  13588. (mapconcat 'identity current ":")
  13589. nil))))
  13590. (defun org-get-tags-string ()
  13591. "Get the TAGS string in the current headline."
  13592. (unless (org-at-heading-p t)
  13593. (user-error "Not on a heading"))
  13594. (save-excursion
  13595. (beginning-of-line 1)
  13596. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13597. (match-string-no-properties 1)
  13598. "")))
  13599. (defun org-get-tags ()
  13600. "Get the list of tags specified in the current headline."
  13601. (org-split-string (org-get-tags-string) ":"))
  13602. (defun org-get-buffer-tags ()
  13603. "Get a table of all tags used in the buffer, for completion."
  13604. (org-with-wide-buffer
  13605. (goto-char (point-min))
  13606. (let ((tag-re (concat org-outline-regexp-bol
  13607. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13608. tags)
  13609. (while (re-search-forward tag-re nil t)
  13610. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13611. (push tag tags)))
  13612. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13613. ;;;; The mapping API
  13614. (defvar org-agenda-skip-comment-trees)
  13615. (defvar org-agenda-skip-function)
  13616. (defun org-map-entries (func &optional match scope &rest skip)
  13617. "Call FUNC at each headline selected by MATCH in SCOPE.
  13618. FUNC is a function or a lisp form. The function will be called without
  13619. arguments, with the cursor positioned at the beginning of the headline.
  13620. The return values of all calls to the function will be collected and
  13621. returned as a list.
  13622. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13623. does not need to preserve point. After evaluation, the cursor will be
  13624. moved to the end of the line (presumably of the headline of the
  13625. processed entry) and search continues from there. Under some
  13626. circumstances, this may not produce the wanted results. For example,
  13627. if you have removed (e.g. archived) the current (sub)tree it could
  13628. mean that the next entry will be skipped entirely. In such cases, you
  13629. can specify the position from where search should continue by making
  13630. FUNC set the variable `org-map-continue-from' to the desired buffer
  13631. position.
  13632. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13633. Only headlines that are matched by this query will be considered during
  13634. the iteration. When MATCH is nil or t, all headlines will be
  13635. visited by the iteration.
  13636. SCOPE determines the scope of this command. It can be any of:
  13637. nil The current buffer, respecting the restriction if any
  13638. tree The subtree started with the entry at point
  13639. region The entries within the active region, if any
  13640. region-start-level
  13641. The entries within the active region, but only those at
  13642. the same level than the first one.
  13643. file The current buffer, without restriction
  13644. file-with-archives
  13645. The current buffer, and any archives associated with it
  13646. agenda All agenda files
  13647. agenda-with-archives
  13648. All agenda files with any archive files associated with them
  13649. \(file1 file2 ...)
  13650. If this is a list, all files in the list will be scanned
  13651. The remaining args are treated as settings for the skipping facilities of
  13652. the scanner. The following items can be given here:
  13653. archive skip trees with the archive tag
  13654. comment skip trees with the COMMENT keyword
  13655. function or Emacs Lisp form:
  13656. will be used as value for `org-agenda-skip-function', so
  13657. whenever the function returns a position, FUNC will not be
  13658. called for that entry and search will continue from the
  13659. position returned
  13660. If your function needs to retrieve the tags including inherited tags
  13661. at the *current* entry, you can use the value of the variable
  13662. `org-scanner-tags' which will be much faster than getting the value
  13663. with `org-get-tags-at'. If your function gets properties with
  13664. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13665. to t around the call to `org-entry-properties' to get the same speedup.
  13666. Note that if your function moves around to retrieve tags and properties at
  13667. a *different* entry, you cannot use these techniques."
  13668. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13669. (not (org-region-active-p)))
  13670. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13671. (org-agenda-skip-archived-trees (memq 'archive skip))
  13672. (org-agenda-skip-comment-trees (memq 'comment skip))
  13673. (org-agenda-skip-function
  13674. (car (org-delete-all '(comment archive) skip)))
  13675. (org-tags-match-list-sublevels t)
  13676. (start-level (eq scope 'region-start-level))
  13677. matcher res
  13678. org-todo-keywords-for-agenda
  13679. org-done-keywords-for-agenda
  13680. org-todo-keyword-alist-for-agenda
  13681. org-tag-alist-for-agenda
  13682. org--matcher-tags-todo-only)
  13683. (cond
  13684. ((eq match t) (setq matcher t))
  13685. ((eq match nil) (setq matcher t))
  13686. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13687. (save-excursion
  13688. (save-restriction
  13689. (cond ((eq scope 'tree)
  13690. (org-back-to-heading t)
  13691. (org-narrow-to-subtree)
  13692. (setq scope nil))
  13693. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13694. (org-region-active-p))
  13695. ;; If needed, set start-level to a string like "2"
  13696. (when start-level
  13697. (save-excursion
  13698. (goto-char (region-beginning))
  13699. (unless (org-at-heading-p) (outline-next-heading))
  13700. (setq start-level (org-current-level))))
  13701. (narrow-to-region (region-beginning)
  13702. (save-excursion
  13703. (goto-char (region-end))
  13704. (unless (and (bolp) (org-at-heading-p))
  13705. (outline-next-heading))
  13706. (point)))
  13707. (setq scope nil)))
  13708. (if (not scope)
  13709. (progn
  13710. (org-agenda-prepare-buffers
  13711. (and buffer-file-name (list buffer-file-name)))
  13712. (setq res
  13713. (org-scan-tags
  13714. func matcher org--matcher-tags-todo-only start-level)))
  13715. ;; Get the right scope
  13716. (cond
  13717. ((and scope (listp scope) (symbolp (car scope)))
  13718. (setq scope (eval scope)))
  13719. ((eq scope 'agenda)
  13720. (setq scope (org-agenda-files t)))
  13721. ((eq scope 'agenda-with-archives)
  13722. (setq scope (org-agenda-files t))
  13723. (setq scope (org-add-archive-files scope)))
  13724. ((eq scope 'file)
  13725. (setq scope (and buffer-file-name (list buffer-file-name))))
  13726. ((eq scope 'file-with-archives)
  13727. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13728. (org-agenda-prepare-buffers scope)
  13729. (dolist (file scope)
  13730. (with-current-buffer (org-find-base-buffer-visiting file)
  13731. (org-with-wide-buffer
  13732. (goto-char (point-min))
  13733. (setq res
  13734. (append
  13735. res
  13736. (org-scan-tags
  13737. func matcher org--matcher-tags-todo-only)))))))))
  13738. res)))
  13739. ;;; Properties API
  13740. (defconst org-special-properties
  13741. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13742. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13743. "The special properties valid in Org mode.
  13744. These are properties that are not defined in the property drawer,
  13745. but in some other way.")
  13746. (defconst org-default-properties
  13747. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13748. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13749. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13750. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13751. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13752. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13753. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13754. "Some properties that are used by Org mode for various purposes.
  13755. Being in this list makes sure that they are offered for completion.")
  13756. (defun org--valid-property-p (property)
  13757. "Non nil when string PROPERTY is a valid property name."
  13758. (not
  13759. (or (equal property "")
  13760. (string-match-p "\\s-" property))))
  13761. (defun org--update-property-plist (key val props)
  13762. "Associate KEY to VAL in alist PROPS.
  13763. Modifications are made by side-effect. Return new alist."
  13764. (let* ((appending (string= (substring key -1) "+"))
  13765. (key (if appending (substring key 0 -1) key))
  13766. (old (assoc-string key props t)))
  13767. (if (not old) (cons (cons key val) props)
  13768. (setcdr old (if appending (concat (cdr old) " " val) val))
  13769. props)))
  13770. (defun org-get-property-block (&optional beg force)
  13771. "Return the (beg . end) range of the body of the property drawer.
  13772. BEG is the beginning of the current subtree, or of the part
  13773. before the first headline. If it is not given, it will be found.
  13774. If the drawer does not exist, create it if FORCE is non-nil, or
  13775. return nil."
  13776. (org-with-wide-buffer
  13777. (when beg (goto-char beg))
  13778. (unless (org-before-first-heading-p)
  13779. (let ((beg (cond (beg)
  13780. ((or (not (featurep 'org-inlinetask))
  13781. (org-inlinetask-in-task-p))
  13782. (org-back-to-heading t))
  13783. (t (org-with-limited-levels (org-back-to-heading t))))))
  13784. (forward-line)
  13785. (when (looking-at-p org-planning-line-re) (forward-line))
  13786. (cond ((looking-at org-property-drawer-re)
  13787. (forward-line)
  13788. (cons (point) (progn (goto-char (match-end 0))
  13789. (line-beginning-position))))
  13790. (force
  13791. (goto-char beg)
  13792. (org-insert-property-drawer)
  13793. (let ((pos (save-excursion (search-forward ":END:")
  13794. (line-beginning-position))))
  13795. (cons pos pos))))))))
  13796. (defun org-at-property-p ()
  13797. "Non-nil when point is inside a property drawer.
  13798. See `org-property-re' for match data, if applicable."
  13799. (save-excursion
  13800. (beginning-of-line)
  13801. (and (looking-at org-property-re)
  13802. (let ((property-drawer (save-match-data (org-get-property-block))))
  13803. (and property-drawer
  13804. (>= (point) (car property-drawer))
  13805. (< (point) (cdr property-drawer)))))))
  13806. (defun org-property-action ()
  13807. "Do an action on properties."
  13808. (interactive)
  13809. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13810. (let ((c (read-char-exclusive)))
  13811. (cl-case c
  13812. (?s (call-interactively #'org-set-property))
  13813. (?d (call-interactively #'org-delete-property))
  13814. (?D (call-interactively #'org-delete-property-globally))
  13815. (?c (call-interactively #'org-compute-property-at-point))
  13816. (otherwise (user-error "No such property action %c" c)))))
  13817. (defun org-inc-effort ()
  13818. "Increment the value of the effort property in the current entry."
  13819. (interactive)
  13820. (org-set-effort nil t))
  13821. (defvar org-clock-effort) ; Defined in org-clock.el.
  13822. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13823. (defun org-set-effort (&optional value increment)
  13824. "Set the effort property of the current entry.
  13825. With numerical prefix arg, use the nth allowed value, 0 stands for the
  13826. 10th allowed value.
  13827. When INCREMENT is non-nil, set the property to the next allowed value."
  13828. (interactive "P")
  13829. (when (equal value 0) (setq value 10))
  13830. (let* ((completion-ignore-case t)
  13831. (prop org-effort-property)
  13832. (cur (org-entry-get nil prop))
  13833. (allowed (org-property-get-allowed-values nil prop 'table))
  13834. (existing (mapcar 'list (org-property-values prop)))
  13835. (heading (nth 4 (org-heading-components)))
  13836. rpl
  13837. (val (cond
  13838. ((stringp value) value)
  13839. ((and allowed (integerp value))
  13840. (or (car (nth (1- value) allowed))
  13841. (car (org-last allowed))))
  13842. ((and allowed increment)
  13843. (or (cl-caadr (member (list cur) allowed))
  13844. (user-error "Allowed effort values are not set")))
  13845. (allowed
  13846. (message "Select 1-9,0, [RET%s]: %s"
  13847. (if cur (concat "=" cur) "")
  13848. (mapconcat 'car allowed " "))
  13849. (setq rpl (read-char-exclusive))
  13850. (if (equal rpl ?\r)
  13851. cur
  13852. (setq rpl (- rpl ?0))
  13853. (when (equal rpl 0) (setq rpl 10))
  13854. (if (and (> rpl 0) (<= rpl (length allowed)))
  13855. (car (nth (1- rpl) allowed))
  13856. (org-completing-read "Effort: " allowed nil))))
  13857. (t
  13858. (org-completing-read
  13859. (concat "Effort" (and cur (string-match "\\S-" cur)
  13860. (concat " [" cur "]"))
  13861. ": ")
  13862. existing nil nil "" nil cur)))))
  13863. (unless (equal (org-entry-get nil prop) val)
  13864. (org-entry-put nil prop val))
  13865. (org-refresh-property
  13866. '((effort . identity)
  13867. (effort-minutes . org-duration-to-minutes))
  13868. val)
  13869. (when (equal heading (bound-and-true-p org-clock-current-task))
  13870. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  13871. (org-clock-update-mode-line))
  13872. (message "%s is now %s" prop val)))
  13873. (defun org-entry-properties (&optional pom which)
  13874. "Get all properties of the current entry.
  13875. When POM is a buffer position, get all properties from the entry
  13876. there instead.
  13877. This includes the TODO keyword, the tags, time strings for
  13878. deadline, scheduled, and clocking, and any additional properties
  13879. defined in the entry.
  13880. If WHICH is nil or `all', get all properties. If WHICH is
  13881. `special' or `standard', only get that subclass. If WHICH is
  13882. a string, only get that property.
  13883. Return value is an alist. Keys are properties, as upcased
  13884. strings."
  13885. (org-with-point-at pom
  13886. (when (and (derived-mode-p 'org-mode)
  13887. (ignore-errors (org-back-to-heading t)))
  13888. (catch 'exit
  13889. (let* ((beg (point))
  13890. (specific (and (stringp which) (upcase which)))
  13891. (which (cond ((not specific) which)
  13892. ((member specific org-special-properties) 'special)
  13893. (t 'standard)))
  13894. props)
  13895. ;; Get the special properties, like TODO and TAGS.
  13896. (when (memq which '(nil all special))
  13897. (when (or (not specific) (string= specific "CLOCKSUM"))
  13898. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13899. (when clocksum
  13900. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13901. props)))
  13902. (when specific (throw 'exit props)))
  13903. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13904. (let ((clocksumt (get-text-property (point)
  13905. :org-clock-minutes-today)))
  13906. (when clocksumt
  13907. (push (cons "CLOCKSUM_T"
  13908. (org-duration-from-minutes clocksumt))
  13909. props)))
  13910. (when specific (throw 'exit props)))
  13911. (when (or (not specific) (string= specific "ITEM"))
  13912. (let ((case-fold-search nil))
  13913. (when (looking-at org-complex-heading-regexp)
  13914. (push (cons "ITEM"
  13915. (let ((title (match-string-no-properties 4)))
  13916. (if (org-string-nw-p title)
  13917. (org-remove-tabs title)
  13918. "")))
  13919. props)))
  13920. (when specific (throw 'exit props)))
  13921. (when (or (not specific) (string= specific "TODO"))
  13922. (let ((case-fold-search nil))
  13923. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13924. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13925. (when specific (throw 'exit props)))
  13926. (when (or (not specific) (string= specific "PRIORITY"))
  13927. (push (cons "PRIORITY"
  13928. (if (looking-at org-priority-regexp)
  13929. (match-string-no-properties 2)
  13930. (char-to-string org-default-priority)))
  13931. props)
  13932. (when specific (throw 'exit props)))
  13933. (when (or (not specific) (string= specific "FILE"))
  13934. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13935. props)
  13936. (when specific (throw 'exit props)))
  13937. (when (or (not specific) (string= specific "TAGS"))
  13938. (let ((value (org-string-nw-p (org-get-tags-string))))
  13939. (when value (push (cons "TAGS" value) props)))
  13940. (when specific (throw 'exit props)))
  13941. (when (or (not specific) (string= specific "ALLTAGS"))
  13942. (let ((value (org-get-tags-at)))
  13943. (when value
  13944. (push (cons "ALLTAGS"
  13945. (format ":%s:" (mapconcat #'identity value ":")))
  13946. props)))
  13947. (when specific (throw 'exit props)))
  13948. (when (or (not specific) (string= specific "BLOCKED"))
  13949. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13950. (when specific (throw 'exit props)))
  13951. (when (or (not specific)
  13952. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13953. (forward-line)
  13954. (when (looking-at-p org-planning-line-re)
  13955. (end-of-line)
  13956. (let ((bol (line-beginning-position))
  13957. ;; Backward compatibility: time keywords used to
  13958. ;; be configurable (before 8.3). Make sure we
  13959. ;; get the correct keyword.
  13960. (key-assoc `(("CLOSED" . ,org-closed-string)
  13961. ("DEADLINE" . ,org-deadline-string)
  13962. ("SCHEDULED" . ,org-scheduled-string))))
  13963. (dolist (pair (if specific (list (assoc specific key-assoc))
  13964. key-assoc))
  13965. (save-excursion
  13966. (when (search-backward (cdr pair) bol t)
  13967. (goto-char (match-end 0))
  13968. (skip-chars-forward " \t")
  13969. (and (looking-at org-ts-regexp-both)
  13970. (push (cons (car pair)
  13971. (match-string-no-properties 0))
  13972. props)))))))
  13973. (when specific (throw 'exit props)))
  13974. (when (or (not specific)
  13975. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13976. (let ((find-ts
  13977. (lambda (end ts)
  13978. ;; Fix next time-stamp before END. TS is the
  13979. ;; list of time-stamps found so far.
  13980. (let ((ts ts)
  13981. (regexp (cond
  13982. ((string= specific "TIMESTAMP")
  13983. org-ts-regexp)
  13984. ((string= specific "TIMESTAMP_IA")
  13985. org-ts-regexp-inactive)
  13986. ((assoc "TIMESTAMP_IA" ts)
  13987. org-ts-regexp)
  13988. ((assoc "TIMESTAMP" ts)
  13989. org-ts-regexp-inactive)
  13990. (t org-ts-regexp-both))))
  13991. (catch 'next
  13992. (while (re-search-forward regexp end t)
  13993. (backward-char)
  13994. (let ((object (org-element-context)))
  13995. ;; Accept to match timestamps in node
  13996. ;; properties, too.
  13997. (when (memq (org-element-type object)
  13998. '(node-property timestamp))
  13999. (let ((type
  14000. (org-element-property :type object)))
  14001. (cond
  14002. ((and (memq type '(active active-range))
  14003. (not (equal specific "TIMESTAMP_IA")))
  14004. (unless (assoc "TIMESTAMP" ts)
  14005. (push (cons "TIMESTAMP"
  14006. (org-element-property
  14007. :raw-value object))
  14008. ts)
  14009. (when specific (throw 'exit ts))))
  14010. ((and (memq type '(inactive inactive-range))
  14011. (not (string= specific "TIMESTAMP")))
  14012. (unless (assoc "TIMESTAMP_IA" ts)
  14013. (push (cons "TIMESTAMP_IA"
  14014. (org-element-property
  14015. :raw-value object))
  14016. ts)
  14017. (when specific (throw 'exit ts))))))
  14018. ;; Both timestamp types are found,
  14019. ;; move to next part.
  14020. (when (= (length ts) 2) (throw 'next ts)))))
  14021. ts)))))
  14022. (goto-char beg)
  14023. ;; First look for timestamps within headline.
  14024. (let ((ts (funcall find-ts (line-end-position) nil)))
  14025. (if (= (length ts) 2) (setq props (nconc ts props))
  14026. ;; Then find timestamps in the section, skipping
  14027. ;; planning line.
  14028. (let ((end (save-excursion (outline-next-heading))))
  14029. (forward-line)
  14030. (when (looking-at-p org-planning-line-re) (forward-line))
  14031. (setq props (nconc (funcall find-ts end ts) props))))))))
  14032. ;; Get the standard properties, like :PROP:.
  14033. (when (memq which '(nil all standard))
  14034. ;; If we are looking after a specific property, delegate
  14035. ;; to `org-entry-get', which is faster. However, make an
  14036. ;; exception for "CATEGORY", since it can be also set
  14037. ;; through keywords (i.e. #+CATEGORY).
  14038. (if (and specific (not (equal specific "CATEGORY")))
  14039. (let ((value (org-entry-get beg specific nil t)))
  14040. (throw 'exit (and value (list (cons specific value)))))
  14041. (let ((range (org-get-property-block beg)))
  14042. (when range
  14043. (let ((end (cdr range)) seen-base)
  14044. (goto-char (car range))
  14045. ;; Unlike to `org--update-property-plist', we
  14046. ;; handle the case where base values is found
  14047. ;; after its extension. We also forbid standard
  14048. ;; properties to be named as special properties.
  14049. (while (re-search-forward org-property-re end t)
  14050. (let* ((key (upcase (match-string-no-properties 2)))
  14051. (extendp (string-match-p "\\+\\'" key))
  14052. (key-base (if extendp (substring key 0 -1) key))
  14053. (value (match-string-no-properties 3)))
  14054. (cond
  14055. ((member-ignore-case key-base org-special-properties))
  14056. (extendp
  14057. (setq props
  14058. (org--update-property-plist key value props)))
  14059. ((member key seen-base))
  14060. (t (push key seen-base)
  14061. (let ((p (assoc-string key props t)))
  14062. (if p (setcdr p (concat value " " (cdr p)))
  14063. (push (cons key value) props))))))))))))
  14064. (unless (assoc "CATEGORY" props)
  14065. (push (cons "CATEGORY" (org-get-category beg)) props)
  14066. (when (string= specific "CATEGORY") (throw 'exit props)))
  14067. ;; Return value.
  14068. props)))))
  14069. (defun org--property-local-values (property literal-nil)
  14070. "Return value for PROPERTY in current entry.
  14071. Value is a list whose car is the base value for PROPERTY and cdr
  14072. a list of accumulated values. Return nil if neither is found in
  14073. the entry. Also return nil when PROPERTY is set to \"nil\",
  14074. unless LITERAL-NIL is non-nil."
  14075. (let ((range (org-get-property-block)))
  14076. (when range
  14077. (goto-char (car range))
  14078. (let* ((case-fold-search t)
  14079. (end (cdr range))
  14080. (value
  14081. ;; Base value.
  14082. (save-excursion
  14083. (let ((v (and (re-search-forward
  14084. (org-re-property property nil t) end t)
  14085. (match-string-no-properties 3))))
  14086. (list (if literal-nil v (org-not-nil v)))))))
  14087. ;; Find additional values.
  14088. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14089. (while (re-search-forward property+ end t)
  14090. (push (match-string-no-properties 3) value)))
  14091. ;; Return final values.
  14092. (and (not (equal value '(nil))) (nreverse value))))))
  14093. (defun org--property-global-value (property literal-nil)
  14094. "Return value for PROPERTY in current buffer.
  14095. Return value is a string. Return nil if property is not set
  14096. globally. Also return nil when PROPERTY is set to \"nil\",
  14097. unless LITERAL-NIL is non-nil."
  14098. (let ((global
  14099. (cdr (or (assoc-string property org-file-properties t)
  14100. (assoc-string property org-global-properties t)
  14101. (assoc-string property org-global-properties-fixed t)))))
  14102. (if literal-nil global (org-not-nil global))))
  14103. (defun org-entry-get (pom property &optional inherit literal-nil)
  14104. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14105. If INHERIT is non-nil and the entry does not have the property,
  14106. then also check higher levels of the hierarchy. If INHERIT is
  14107. the symbol `selective', use inheritance only if the setting in
  14108. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14109. If the property is present but empty, the return value is the
  14110. empty string. If the property is not present at all, nil is
  14111. returned. In any other case, return the value as a string.
  14112. Search is case-insensitive.
  14113. If LITERAL-NIL is set, return the string value \"nil\" as
  14114. a string, do not interpret it as the list atom nil. This is used
  14115. for inheritance when a \"nil\" value can supersede a non-nil
  14116. value higher up the hierarchy."
  14117. (org-with-point-at pom
  14118. (cond
  14119. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14120. ;; We need a special property. Use `org-entry-properties' to
  14121. ;; retrieve it, but specify the wanted property.
  14122. (cdr (assoc-string property (org-entry-properties nil property))))
  14123. ((and inherit
  14124. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14125. (org-entry-get-with-inheritance property literal-nil))
  14126. (t
  14127. (let* ((local (org--property-local-values property literal-nil))
  14128. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14129. (if literal-nil value (org-not-nil value)))))))
  14130. (defun org-property-or-variable-value (var &optional inherit)
  14131. "Check if there is a property fixing the value of VAR.
  14132. If yes, return this value. If not, return the current value of the variable."
  14133. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14134. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14135. (read prop)
  14136. (symbol-value var))))
  14137. (defun org-entry-delete (pom property)
  14138. "Delete PROPERTY from entry at point-or-marker POM.
  14139. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14140. non-nil when a property was removed."
  14141. (org-with-point-at pom
  14142. (pcase (org-get-property-block)
  14143. (`(,begin . ,origin)
  14144. (let* ((end (copy-marker origin))
  14145. (re (org-re-property
  14146. (concat (regexp-quote property) "\\+?") t t)))
  14147. (goto-char begin)
  14148. (while (re-search-forward re end t)
  14149. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14150. ;; If drawer is empty, remove it altogether.
  14151. (when (= begin end)
  14152. (delete-region (line-beginning-position 0)
  14153. (line-beginning-position 2)))
  14154. ;; Return non-nil if some property was removed.
  14155. (prog1 (/= end origin) (set-marker end nil))))
  14156. (_ nil))))
  14157. ;; Multi-values properties are properties that contain multiple values
  14158. ;; These values are assumed to be single words, separated by whitespace.
  14159. (defun org-entry-add-to-multivalued-property (pom property value)
  14160. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14161. (let* ((old (org-entry-get pom property))
  14162. (values (and old (split-string old))))
  14163. (setq value (org-entry-protect-space value))
  14164. (unless (member value values)
  14165. (setq values (append values (list value)))
  14166. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14167. (defun org-entry-remove-from-multivalued-property (pom property value)
  14168. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14169. (let* ((old (org-entry-get pom property))
  14170. (values (and old (split-string old))))
  14171. (setq value (org-entry-protect-space value))
  14172. (when (member value values)
  14173. (setq values (delete value values))
  14174. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14175. (defun org-entry-member-in-multivalued-property (pom property value)
  14176. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14177. (let* ((old (org-entry-get pom property))
  14178. (values (and old (split-string old))))
  14179. (setq value (org-entry-protect-space value))
  14180. (member value values)))
  14181. (defun org-entry-get-multivalued-property (pom property)
  14182. "Return a list of values in a multivalued property."
  14183. (let* ((value (org-entry-get pom property))
  14184. (values (and value (split-string value))))
  14185. (mapcar #'org-entry-restore-space values)))
  14186. (defun org-entry-put-multivalued-property (pom property &rest values)
  14187. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14188. VALUES should be a list of strings. Spaces will be protected."
  14189. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  14190. (let* ((value (org-entry-get pom property))
  14191. (values (and value (split-string value))))
  14192. (mapcar #'org-entry-restore-space values)))
  14193. (defun org-entry-protect-space (s)
  14194. "Protect spaces and newline in string S."
  14195. (while (string-match " " s)
  14196. (setq s (replace-match "%20" t t s)))
  14197. (while (string-match "\n" s)
  14198. (setq s (replace-match "%0A" t t s)))
  14199. s)
  14200. (defun org-entry-restore-space (s)
  14201. "Restore spaces and newline in string S."
  14202. (while (string-match "%20" s)
  14203. (setq s (replace-match " " t t s)))
  14204. (while (string-match "%0A" s)
  14205. (setq s (replace-match "\n" t t s)))
  14206. s)
  14207. (defvar org-entry-property-inherited-from (make-marker)
  14208. "Marker pointing to the entry from where a property was inherited.
  14209. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14210. location of the entry where the inheritance search matched. If there was
  14211. no match, the marker will point nowhere.
  14212. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14213. is set.")
  14214. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14215. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14216. The search will stop at the first ancestor which has the property defined.
  14217. If the value found is \"nil\", return nil to show that the property
  14218. should be considered as undefined (this is the meaning of nil here).
  14219. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14220. (move-marker org-entry-property-inherited-from nil)
  14221. (org-with-wide-buffer
  14222. (let (value)
  14223. (catch 'exit
  14224. (while t
  14225. (let ((v (org--property-local-values property literal-nil)))
  14226. (when v
  14227. (setq value
  14228. (concat (mapconcat #'identity (delq nil v) " ")
  14229. (and value " ")
  14230. value)))
  14231. (cond
  14232. ((car v)
  14233. (org-back-to-heading t)
  14234. (move-marker org-entry-property-inherited-from (point))
  14235. (throw 'exit nil))
  14236. ((org-up-heading-safe))
  14237. (t
  14238. (let ((global (org--property-global-value property literal-nil)))
  14239. (cond ((not global))
  14240. (value (setq value (concat global " " value)))
  14241. (t (setq value global))))
  14242. (throw 'exit nil))))))
  14243. (if literal-nil value (org-not-nil value)))))
  14244. (defvar org-property-changed-functions nil
  14245. "Hook called when the value of a property has changed.
  14246. Each hook function should accept two arguments, the name of the property
  14247. and the new value.")
  14248. (defun org-entry-put (pom property value)
  14249. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14250. If the value is nil, it is converted to the empty string. If it
  14251. is not a string, an error is raised. Also raise an error on
  14252. invalid property names.
  14253. PROPERTY can be any regular property (see
  14254. `org-special-properties'). It can also be \"TODO\",
  14255. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14256. For the last two properties, VALUE may have any of the special
  14257. values \"earlier\" and \"later\". The function then increases or
  14258. decreases scheduled or deadline date by one day."
  14259. (cond ((null value) (setq value ""))
  14260. ((not (stringp value)) (error "Properties values should be strings"))
  14261. ((not (org--valid-property-p property))
  14262. (user-error "Invalid property name: \"%s\"" property)))
  14263. (org-with-point-at pom
  14264. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14265. (org-back-to-heading t)
  14266. (org-with-limited-levels (org-back-to-heading t)))
  14267. (let ((beg (point)))
  14268. (cond
  14269. ((equal property "TODO")
  14270. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14271. ((not (member value org-todo-keywords-1))
  14272. (user-error "\"%s\" is not a valid TODO state" value)))
  14273. (org-todo value)
  14274. (org-set-tags nil 'align))
  14275. ((equal property "PRIORITY")
  14276. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14277. (org-set-tags nil 'align))
  14278. ((equal property "SCHEDULED")
  14279. (forward-line)
  14280. (if (and (looking-at-p org-planning-line-re)
  14281. (re-search-forward
  14282. org-scheduled-time-regexp (line-end-position) t))
  14283. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14284. ((string= value "later") (org-timestamp-change 1 'day))
  14285. ((string= value "") (org-schedule '(4)))
  14286. (t (org-schedule nil value)))
  14287. (if (member value '("earlier" "later" ""))
  14288. (call-interactively #'org-schedule)
  14289. (org-schedule nil value))))
  14290. ((equal property "DEADLINE")
  14291. (forward-line)
  14292. (if (and (looking-at-p org-planning-line-re)
  14293. (re-search-forward
  14294. org-deadline-time-regexp (line-end-position) t))
  14295. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14296. ((string= value "later") (org-timestamp-change 1 'day))
  14297. ((string= value "") (org-deadline '(4)))
  14298. (t (org-deadline nil value)))
  14299. (if (member value '("earlier" "later" ""))
  14300. (call-interactively #'org-deadline)
  14301. (org-deadline nil value))))
  14302. ((member property org-special-properties)
  14303. (error "The %s property cannot be set with `org-entry-put'" property))
  14304. (t
  14305. (let* ((range (org-get-property-block beg 'force))
  14306. (end (cdr range))
  14307. (case-fold-search t))
  14308. (goto-char (car range))
  14309. (if (re-search-forward (org-re-property property nil t) end t)
  14310. (progn (delete-region (match-beginning 0) (match-end 0))
  14311. (goto-char (match-beginning 0)))
  14312. (goto-char end)
  14313. (insert "\n")
  14314. (backward-char))
  14315. (insert ":" property ":")
  14316. (when value (insert " " value))
  14317. (org-indent-line)))))
  14318. (run-hook-with-args 'org-property-changed-functions property value)))
  14319. (defun org-buffer-property-keys (&optional specials defaults columns)
  14320. "Get all property keys in the current buffer.
  14321. When SPECIALS is non-nil, also list the special properties that
  14322. reflect things like tags and TODO state.
  14323. When DEFAULTS is non-nil, also include properties that has
  14324. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14325. DESCRIPTION, LOCATION, and LOGGING and others.
  14326. When COLUMNS in non-nil, also include property names given in
  14327. COLUMN formats in the current buffer."
  14328. (let ((case-fold-search t)
  14329. (props (append
  14330. (and specials org-special-properties)
  14331. (and defaults (cons org-effort-property org-default-properties))
  14332. nil)))
  14333. (org-with-wide-buffer
  14334. (goto-char (point-min))
  14335. (while (re-search-forward org-property-start-re nil t)
  14336. (catch :skip
  14337. (let ((range (org-get-property-block)))
  14338. (unless range (throw :skip nil))
  14339. (goto-char (car range))
  14340. (let ((begin (car range))
  14341. (end (cdr range)))
  14342. ;; Make sure that found property block is not located
  14343. ;; before current point, as it would generate an infloop.
  14344. ;; It can happen, for example, in the following
  14345. ;; situation:
  14346. ;;
  14347. ;; * Headline
  14348. ;; :PROPERTIES:
  14349. ;; ...
  14350. ;; :END:
  14351. ;; *************** Inlinetask
  14352. ;; #+BEGIN_EXAMPLE
  14353. ;; :PROPERTIES:
  14354. ;; #+END_EXAMPLE
  14355. ;;
  14356. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14357. (while (< (point) end)
  14358. (let ((p (progn (looking-at org-property-re)
  14359. (match-string-no-properties 2))))
  14360. ;; Only add true property name, not extension symbol.
  14361. (push (if (not (string-match-p "\\+\\'" p)) p
  14362. (substring p 0 -1))
  14363. props))
  14364. (forward-line))))
  14365. (outline-next-heading)))
  14366. (when columns
  14367. (goto-char (point-min))
  14368. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14369. (let ((element (org-element-at-point)))
  14370. (when (memq (org-element-type element) '(keyword node-property))
  14371. (let ((value (org-element-property :value element))
  14372. (start 0))
  14373. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14374. \\(?:{[^}]+}\\)?"
  14375. value start)
  14376. (setq start (match-end 0))
  14377. (let ((p (match-string-no-properties 1 value)))
  14378. (unless (member-ignore-case p org-special-properties)
  14379. (push p props))))))))))
  14380. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14381. (defun org-property-values (key)
  14382. "List all non-nil values of property KEY in current buffer."
  14383. (org-with-wide-buffer
  14384. (goto-char (point-min))
  14385. (let ((case-fold-search t)
  14386. (re (org-re-property key))
  14387. values)
  14388. (while (re-search-forward re nil t)
  14389. (push (org-entry-get (point) key) values))
  14390. (delete-dups values))))
  14391. (defun org-insert-property-drawer ()
  14392. "Insert a property drawer into the current entry."
  14393. (org-with-wide-buffer
  14394. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14395. (org-back-to-heading t)
  14396. (org-with-limited-levels (org-back-to-heading t)))
  14397. (forward-line)
  14398. (when (looking-at-p org-planning-line-re) (forward-line))
  14399. (unless (looking-at-p org-property-drawer-re)
  14400. ;; Make sure we start editing a line from current entry, not from
  14401. ;; next one. It prevents extending text properties or overlays
  14402. ;; belonging to the latter.
  14403. (when (bolp) (backward-char))
  14404. (let ((begin (1+ (point)))
  14405. (inhibit-read-only t))
  14406. (insert "\n:PROPERTIES:\n:END:")
  14407. (when (eobp) (insert "\n"))
  14408. (org-indent-region begin (point))))))
  14409. (defun org-insert-drawer (&optional arg drawer)
  14410. "Insert a drawer at point.
  14411. When optional argument ARG is non-nil, insert a property drawer.
  14412. Optional argument DRAWER, when non-nil, is a string representing
  14413. drawer's name. Otherwise, the user is prompted for a name.
  14414. If a region is active, insert the drawer around that region
  14415. instead.
  14416. Point is left between drawer's boundaries."
  14417. (interactive "P")
  14418. (let* ((drawer (if arg "PROPERTIES"
  14419. (or drawer (read-from-minibuffer "Drawer: ")))))
  14420. (cond
  14421. ;; With C-u, fall back on `org-insert-property-drawer'
  14422. (arg (org-insert-property-drawer))
  14423. ;; Check validity of suggested drawer's name.
  14424. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14425. (user-error "Invalid drawer name"))
  14426. ;; With an active region, insert a drawer at point.
  14427. ((not (org-region-active-p))
  14428. (progn
  14429. (unless (bolp) (insert "\n"))
  14430. (insert (format ":%s:\n\n:END:\n" drawer))
  14431. (forward-line -2)))
  14432. ;; Otherwise, insert the drawer at point
  14433. (t
  14434. (let ((rbeg (region-beginning))
  14435. (rend (copy-marker (region-end))))
  14436. (unwind-protect
  14437. (progn
  14438. (goto-char rbeg)
  14439. (beginning-of-line)
  14440. (when (save-excursion
  14441. (re-search-forward org-outline-regexp-bol rend t))
  14442. (user-error "Drawers cannot contain headlines"))
  14443. ;; Position point at the beginning of the first
  14444. ;; non-blank line in region. Insert drawer's opening
  14445. ;; there, then indent it.
  14446. (org-skip-whitespace)
  14447. (beginning-of-line)
  14448. (insert ":" drawer ":\n")
  14449. (forward-line -1)
  14450. (indent-for-tab-command)
  14451. ;; Move point to the beginning of the first blank line
  14452. ;; after the last non-blank line in region. Insert
  14453. ;; drawer's closing, then indent it.
  14454. (goto-char rend)
  14455. (skip-chars-backward " \r\t\n")
  14456. (insert "\n:END:")
  14457. (deactivate-mark t)
  14458. (indent-for-tab-command)
  14459. (unless (eolp) (insert "\n")))
  14460. ;; Clear marker, whatever the outcome of insertion is.
  14461. (set-marker rend nil)))))))
  14462. (defvar org-property-set-functions-alist nil
  14463. "Property set function alist.
  14464. Each entry should have the following format:
  14465. (PROPERTY . READ-FUNCTION)
  14466. The read function will be called with the same argument as
  14467. `org-completing-read'.")
  14468. (defun org-set-property-function (property)
  14469. "Get the function that should be used to set PROPERTY.
  14470. This is computed according to `org-property-set-functions-alist'."
  14471. (or (cdr (assoc property org-property-set-functions-alist))
  14472. 'org-completing-read))
  14473. (defun org-read-property-value (property)
  14474. "Read PROPERTY value from user."
  14475. (let* ((completion-ignore-case t)
  14476. (allowed (org-property-get-allowed-values nil property 'table))
  14477. (cur (org-entry-get nil property))
  14478. (prompt (concat property " value"
  14479. (if (and cur (string-match "\\S-" cur))
  14480. (concat " [" cur "]") "") ": "))
  14481. (set-function (org-set-property-function property))
  14482. (val (if allowed
  14483. (funcall set-function prompt allowed nil
  14484. (not (get-text-property 0 'org-unrestricted
  14485. (caar allowed))))
  14486. (funcall set-function prompt
  14487. (mapcar 'list (org-property-values property))
  14488. nil nil "" nil cur))))
  14489. (org-trim val)))
  14490. (defvar org-last-set-property nil)
  14491. (defvar org-last-set-property-value nil)
  14492. (defun org-read-property-name ()
  14493. "Read a property name."
  14494. (let ((completion-ignore-case t)
  14495. (default-prop (or (and (org-at-property-p)
  14496. (match-string-no-properties 2))
  14497. org-last-set-property)))
  14498. (org-completing-read
  14499. (concat "Property"
  14500. (if default-prop (concat " [" default-prop "]") "")
  14501. ": ")
  14502. (mapcar #'list (org-buffer-property-keys nil t t))
  14503. nil nil nil nil default-prop)))
  14504. (defun org-set-property-and-value (use-last)
  14505. "Allow to set [PROPERTY]: [value] direction from prompt.
  14506. When use-default, don't even ask, just use the last
  14507. \"[PROPERTY]: [value]\" string from the history."
  14508. (interactive "P")
  14509. (let* ((completion-ignore-case t)
  14510. (pv (or (and use-last org-last-set-property-value)
  14511. (org-completing-read
  14512. "Enter a \"[Property]: [value]\" pair: "
  14513. nil nil nil nil nil
  14514. org-last-set-property-value)))
  14515. prop val)
  14516. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14517. (setq prop (match-string 1 pv)
  14518. val (match-string 2 pv))
  14519. (org-set-property prop val))))
  14520. (defun org-set-property (property value)
  14521. "In the current entry, set PROPERTY to VALUE.
  14522. When called interactively, this will prompt for a property name, offering
  14523. completion on existing and default properties. And then it will prompt
  14524. for a value, offering completion either on allowed values (via an inherited
  14525. xxx_ALL property) or on existing values in other instances of this property
  14526. in the current file.
  14527. Throw an error when trying to set a property with an invalid name."
  14528. (interactive (list nil nil))
  14529. (let ((property (or property (org-read-property-name))))
  14530. ;; `org-entry-put' also makes the following check, but this one
  14531. ;; avoids polluting `org-last-set-property' and
  14532. ;; `org-last-set-property-value' needlessly.
  14533. (unless (org--valid-property-p property)
  14534. (user-error "Invalid property name: \"%s\"" property))
  14535. (let ((value (or value (org-read-property-value property)))
  14536. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14537. (setq org-last-set-property property)
  14538. (setq org-last-set-property-value (concat property ": " value))
  14539. ;; Possibly postprocess the inserted value:
  14540. (when fn (setq value (funcall fn value)))
  14541. (unless (equal (org-entry-get nil property) value)
  14542. (org-entry-put nil property value)))))
  14543. (defun org-find-property (property &optional value)
  14544. "Find first entry in buffer that sets PROPERTY.
  14545. When optional argument VALUE is non-nil, only consider an entry
  14546. if it contains PROPERTY set to this value. If PROPERTY should be
  14547. explicitly set to nil, use string \"nil\" for VALUE.
  14548. Return position where the entry begins, or nil if there is no
  14549. such entry. If narrowing is in effect, only search the visible
  14550. part of the buffer."
  14551. (save-excursion
  14552. (goto-char (point-min))
  14553. (let ((case-fold-search t)
  14554. (re (org-re-property property nil (not value) value)))
  14555. (catch 'exit
  14556. (while (re-search-forward re nil t)
  14557. (when (if value (org-at-property-p)
  14558. (org-entry-get (point) property nil t))
  14559. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14560. (defun org-delete-property (property)
  14561. "In the current entry, delete PROPERTY."
  14562. (interactive
  14563. (let* ((completion-ignore-case t)
  14564. (cat (org-entry-get (point) "CATEGORY"))
  14565. (props0 (org-entry-properties nil 'standard))
  14566. (props (if cat props0
  14567. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14568. (prop (if (< 1 (length props))
  14569. (completing-read "Property: " props nil t)
  14570. (caar props))))
  14571. (list prop)))
  14572. (if (not property)
  14573. (message "No property to delete in this entry")
  14574. (org-entry-delete nil property)
  14575. (message "Property \"%s\" deleted" property)))
  14576. (defun org-delete-property-globally (property)
  14577. "Remove PROPERTY globally, from all entries.
  14578. This function ignores narrowing, if any."
  14579. (interactive
  14580. (let* ((completion-ignore-case t)
  14581. (prop (completing-read
  14582. "Globally remove property: "
  14583. (mapcar #'list (org-buffer-property-keys)))))
  14584. (list prop)))
  14585. (org-with-wide-buffer
  14586. (goto-char (point-min))
  14587. (let ((count 0)
  14588. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14589. (while (re-search-forward re nil t)
  14590. (when (org-entry-delete (point) property) (cl-incf count)))
  14591. (message "Property \"%s\" removed from %d entries" property count))))
  14592. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14593. (defun org-compute-property-at-point ()
  14594. "Compute the property at point.
  14595. This looks for an enclosing column format, extracts the operator and
  14596. then applies it to the property in the column format's scope."
  14597. (interactive)
  14598. (unless (org-at-property-p)
  14599. (user-error "Not at a property"))
  14600. (let ((prop (match-string-no-properties 2)))
  14601. (org-columns-get-format-and-top-level)
  14602. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14603. (user-error "No operator defined for property %s" prop))
  14604. (org-columns-compute prop)))
  14605. (defvar org-property-allowed-value-functions nil
  14606. "Hook for functions supplying allowed values for a specific property.
  14607. The functions must take a single argument, the name of the property, and
  14608. return a flat list of allowed values. If \":ETC\" is one of
  14609. the values, this means that these values are intended as defaults for
  14610. completion, but that other values should be allowed too.
  14611. The functions must return nil if they are not responsible for this
  14612. property.")
  14613. (defun org-property-get-allowed-values (pom property &optional table)
  14614. "Get allowed values for the property PROPERTY.
  14615. When TABLE is non-nil, return an alist that can directly be used for
  14616. completion."
  14617. (let (vals)
  14618. (cond
  14619. ((equal property "TODO")
  14620. (setq vals (org-with-point-at pom
  14621. (append org-todo-keywords-1 '("")))))
  14622. ((equal property "PRIORITY")
  14623. (let ((n org-lowest-priority))
  14624. (while (>= n org-highest-priority)
  14625. (push (char-to-string n) vals)
  14626. (setq n (1- n)))))
  14627. ((equal property "CATEGORY"))
  14628. ((member property org-special-properties))
  14629. ((setq vals (run-hook-with-args-until-success
  14630. 'org-property-allowed-value-functions property)))
  14631. (t
  14632. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14633. (when (and vals (string-match "\\S-" vals))
  14634. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14635. (setq vals (mapcar (lambda (x)
  14636. (cond ((stringp x) x)
  14637. ((numberp x) (number-to-string x))
  14638. ((symbolp x) (symbol-name x))
  14639. (t "???")))
  14640. vals)))))
  14641. (when (member ":ETC" vals)
  14642. (setq vals (remove ":ETC" vals))
  14643. (org-add-props (car vals) '(org-unrestricted t)))
  14644. (if table (mapcar 'list vals) vals)))
  14645. (defun org-property-previous-allowed-value (&optional _previous)
  14646. "Switch to the next allowed value for this property."
  14647. (interactive)
  14648. (org-property-next-allowed-value t))
  14649. (defun org-property-next-allowed-value (&optional previous)
  14650. "Switch to the next allowed value for this property."
  14651. (interactive)
  14652. (unless (org-at-property-p)
  14653. (user-error "Not at a property"))
  14654. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14655. (key (match-string 2))
  14656. (value (match-string 3))
  14657. (allowed (or (org-property-get-allowed-values (point) key)
  14658. (and (member value '("[ ]" "[-]" "[X]"))
  14659. '("[ ]" "[X]"))))
  14660. (heading (save-match-data (nth 4 (org-heading-components))))
  14661. nval)
  14662. (unless allowed
  14663. (user-error "Allowed values for this property have not been defined"))
  14664. (when previous (setq allowed (reverse allowed)))
  14665. (when (member value allowed)
  14666. (setq nval (car (cdr (member value allowed)))))
  14667. (setq nval (or nval (car allowed)))
  14668. (when (equal nval value)
  14669. (user-error "Only one allowed value for this property"))
  14670. (org-at-property-p)
  14671. (replace-match (concat " :" key ": " nval) t t)
  14672. (org-indent-line)
  14673. (beginning-of-line 1)
  14674. (skip-chars-forward " \t")
  14675. (when (equal prop org-effort-property)
  14676. (org-refresh-property
  14677. '((effort . identity)
  14678. (effort-minutes . org-duration-to-minutes))
  14679. nval)
  14680. (when (string= org-clock-current-task heading)
  14681. (setq org-clock-effort nval)
  14682. (org-clock-update-mode-line)))
  14683. (run-hook-with-args 'org-property-changed-functions key nval)))
  14684. (defun org-find-olp (path &optional this-buffer)
  14685. "Return a marker pointing to the entry at outline path OLP.
  14686. If anything goes wrong, throw an error.
  14687. You can wrap this call to catch the error like this:
  14688. (condition-case msg
  14689. (org-mobile-locate-entry (match-string 4))
  14690. (error (nth 1 msg)))
  14691. The return value will then be either a string with the error message,
  14692. or a marker if everything is OK.
  14693. If THIS-BUFFER is set, the outline path does not contain a file,
  14694. only headings."
  14695. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14696. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14697. (level 1)
  14698. (lmin 1)
  14699. (lmax 1)
  14700. end found flevel)
  14701. (unless buffer (error "File not found :%s" file))
  14702. (with-current-buffer buffer
  14703. (unless (derived-mode-p 'org-mode)
  14704. (error "Buffer %s needs to be in Org mode" buffer))
  14705. (org-with-wide-buffer
  14706. (goto-char (point-min))
  14707. (dolist (heading path)
  14708. (let ((re (format org-complex-heading-regexp-format
  14709. (regexp-quote heading)))
  14710. (cnt 0))
  14711. (while (re-search-forward re end t)
  14712. (setq level (- (match-end 1) (match-beginning 1)))
  14713. (when (and (>= level lmin) (<= level lmax))
  14714. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14715. (when (= cnt 0)
  14716. (error "Heading not found on level %d: %s" lmax heading))
  14717. (when (> cnt 1)
  14718. (error "Heading not unique on level %d: %s" lmax heading))
  14719. (goto-char found)
  14720. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14721. (setq end (save-excursion (org-end-of-subtree t t)))))
  14722. (when (org-at-heading-p)
  14723. (point-marker))))))
  14724. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14725. "Find node HEADING in BUFFER.
  14726. Return a marker to the heading if it was found, or nil if not.
  14727. If POS-ONLY is set, return just the position instead of a marker.
  14728. The heading text must match exact, but it may have a TODO keyword,
  14729. a priority cookie and tags in the standard locations."
  14730. (with-current-buffer (or buffer (current-buffer))
  14731. (org-with-wide-buffer
  14732. (goto-char (point-min))
  14733. (let (case-fold-search)
  14734. (when (re-search-forward
  14735. (format org-complex-heading-regexp-format
  14736. (regexp-quote heading)) nil t)
  14737. (if pos-only
  14738. (match-beginning 0)
  14739. (move-marker (make-marker) (match-beginning 0))))))))
  14740. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14741. "Find Org node headline HEADING in all .org files in directory DIR.
  14742. When the target headline is found, return a marker to this location."
  14743. (let ((files (directory-files (or dir default-directory)
  14744. t "\\`[^.#].*\\.org\\'"))
  14745. visiting m buffer)
  14746. (catch 'found
  14747. (dolist (file files)
  14748. (message "trying %s" file)
  14749. (setq visiting (org-find-base-buffer-visiting file))
  14750. (setq buffer (or visiting (find-file-noselect file)))
  14751. (setq m (org-find-exact-headline-in-buffer
  14752. heading buffer))
  14753. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14754. (and m (throw 'found m))))))
  14755. (defun org-find-entry-with-id (ident)
  14756. "Locate the entry that contains the ID property with exact value IDENT.
  14757. IDENT can be a string, a symbol or a number, this function will search for
  14758. the string representation of it.
  14759. Return the position where this entry starts, or nil if there is no such entry."
  14760. (interactive "sID: ")
  14761. (let ((id (cond
  14762. ((stringp ident) ident)
  14763. ((symbolp ident) (symbol-name ident))
  14764. ((numberp ident) (number-to-string ident))
  14765. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14766. (org-with-wide-buffer (org-find-property "ID" id))))
  14767. ;;;; Timestamps
  14768. (defvar org-last-changed-timestamp nil)
  14769. (defvar org-last-inserted-timestamp nil
  14770. "The last time stamp inserted with `org-insert-time-stamp'.")
  14771. (defun org-time-stamp (arg &optional inactive)
  14772. "Prompt for a date/time and insert a time stamp.
  14773. If the user specifies a time like HH:MM or if this command is
  14774. called with at least one prefix argument, the time stamp contains
  14775. the date and the time. Otherwise, only the date is included.
  14776. All parts of a date not specified by the user are filled in from
  14777. the timestamp at point, if any, or the current date/time
  14778. otherwise.
  14779. If there is already a timestamp at the cursor, it is replaced.
  14780. With two universal prefix arguments, insert an active timestamp
  14781. with the current time without prompting the user.
  14782. When called from lisp, the timestamp is inactive if INACTIVE is
  14783. non-nil."
  14784. (interactive "P")
  14785. (let* ((ts (cond
  14786. ((org-at-date-range-p t)
  14787. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14788. ((org-at-timestamp-p 'lax) (match-string 0))))
  14789. ;; Default time is either the timestamp at point or today.
  14790. ;; When entering a range, only the range start is considered.
  14791. (default-time (if (not ts) (current-time)
  14792. (apply #'encode-time (org-parse-time-string ts))))
  14793. (default-input (and ts (org-get-compact-tod ts)))
  14794. (repeater (and ts
  14795. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14796. (match-string 0 ts)))
  14797. org-time-was-given
  14798. org-end-time-was-given
  14799. (time
  14800. (and (if (equal arg '(16)) (current-time)
  14801. ;; Preserve `this-command' and `last-command'.
  14802. (let ((this-command this-command)
  14803. (last-command last-command))
  14804. (org-read-date
  14805. arg 'totime nil nil default-time default-input
  14806. inactive))))))
  14807. (cond
  14808. ((and ts
  14809. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14810. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14811. (insert "--")
  14812. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14813. (ts
  14814. ;; Make sure we're on a timestamp. When in the middle of a date
  14815. ;; range, move arbitrarily to range end.
  14816. (unless (org-at-timestamp-p 'lax)
  14817. (skip-chars-forward "-")
  14818. (org-at-timestamp-p 'lax))
  14819. (replace-match "")
  14820. (setq org-last-changed-timestamp
  14821. (org-insert-time-stamp
  14822. time (or org-time-was-given arg)
  14823. inactive nil nil (list org-end-time-was-given)))
  14824. (when repeater
  14825. (backward-char)
  14826. (insert " " repeater)
  14827. (setq org-last-changed-timestamp
  14828. (concat (substring org-last-inserted-timestamp 0 -1)
  14829. " " repeater ">")))
  14830. (message "Timestamp updated"))
  14831. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14832. (t (org-insert-time-stamp
  14833. time (or org-time-was-given arg) inactive nil nil
  14834. (list org-end-time-was-given))))))
  14835. ;; FIXME: can we use this for something else, like computing time differences?
  14836. (defun org-get-compact-tod (s)
  14837. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14838. (let* ((t1 (match-string 1 s))
  14839. (h1 (string-to-number (match-string 2 s)))
  14840. (m1 (string-to-number (match-string 3 s)))
  14841. (t2 (and (match-end 4) (match-string 5 s)))
  14842. (h2 (and t2 (string-to-number (match-string 6 s))))
  14843. (m2 (and t2 (string-to-number (match-string 7 s))))
  14844. dh dm)
  14845. (if (not t2)
  14846. t1
  14847. (setq dh (- h2 h1) dm (- m2 m1))
  14848. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14849. (concat t1 "+" (number-to-string dh)
  14850. (and (/= 0 dm) (format ":%02d" dm)))))))
  14851. (defun org-time-stamp-inactive (&optional arg)
  14852. "Insert an inactive time stamp.
  14853. An inactive time stamp is enclosed in square brackets instead of angle
  14854. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14855. does not link to the calendar and cannot be changed with the S-cursor keys.
  14856. So these are more for recording a certain time/date."
  14857. (interactive "P")
  14858. (org-time-stamp arg 'inactive))
  14859. (defvar org-date-ovl (make-overlay 1 1))
  14860. (overlay-put org-date-ovl 'face 'org-date-selected)
  14861. (delete-overlay org-date-ovl)
  14862. (defvar org-ans1) ; dynamically scoped parameter
  14863. (defvar org-ans2) ; dynamically scoped parameter
  14864. (defvar org-plain-time-of-day-regexp) ; defined below
  14865. (defvar org-overriding-default-time nil) ; dynamically scoped
  14866. (defvar org-read-date-overlay nil)
  14867. (defvar org-dcst nil) ; dynamically scoped
  14868. (defvar org-read-date-history nil)
  14869. (defvar org-read-date-final-answer nil)
  14870. (defvar org-read-date-analyze-futurep nil)
  14871. (defvar org-read-date-analyze-forced-year nil)
  14872. (defvar org-read-date-inactive)
  14873. (defvar org-read-date-minibuffer-local-map
  14874. (let* ((map (make-sparse-keymap)))
  14875. (set-keymap-parent map minibuffer-local-map)
  14876. (org-defkey map (kbd ".")
  14877. (lambda () (interactive)
  14878. ;; Are we at the beginning of the prompt?
  14879. (if (looking-back "^[^:]+: "
  14880. (let ((inhibit-field-text-motion t))
  14881. (line-beginning-position)))
  14882. (org-eval-in-calendar '(calendar-goto-today))
  14883. (insert "."))))
  14884. (org-defkey map (kbd "C-.")
  14885. (lambda () (interactive)
  14886. (org-eval-in-calendar '(calendar-goto-today))))
  14887. (org-defkey map [(meta shift left)]
  14888. (lambda () (interactive)
  14889. (org-eval-in-calendar '(calendar-backward-month 1))))
  14890. (org-defkey map [(meta shift right)]
  14891. (lambda () (interactive)
  14892. (org-eval-in-calendar '(calendar-forward-month 1))))
  14893. (org-defkey map [(meta shift up)]
  14894. (lambda () (interactive)
  14895. (org-eval-in-calendar '(calendar-backward-year 1))))
  14896. (org-defkey map [(meta shift down)]
  14897. (lambda () (interactive)
  14898. (org-eval-in-calendar '(calendar-forward-year 1))))
  14899. (org-defkey map [?\e (shift left)]
  14900. (lambda () (interactive)
  14901. (org-eval-in-calendar '(calendar-backward-month 1))))
  14902. (org-defkey map [?\e (shift right)]
  14903. (lambda () (interactive)
  14904. (org-eval-in-calendar '(calendar-forward-month 1))))
  14905. (org-defkey map [?\e (shift up)]
  14906. (lambda () (interactive)
  14907. (org-eval-in-calendar '(calendar-backward-year 1))))
  14908. (org-defkey map [?\e (shift down)]
  14909. (lambda () (interactive)
  14910. (org-eval-in-calendar '(calendar-forward-year 1))))
  14911. (org-defkey map [(shift up)]
  14912. (lambda () (interactive)
  14913. (org-eval-in-calendar '(calendar-backward-week 1))))
  14914. (org-defkey map [(shift down)]
  14915. (lambda () (interactive)
  14916. (org-eval-in-calendar '(calendar-forward-week 1))))
  14917. (org-defkey map [(shift left)]
  14918. (lambda () (interactive)
  14919. (org-eval-in-calendar '(calendar-backward-day 1))))
  14920. (org-defkey map [(shift right)]
  14921. (lambda () (interactive)
  14922. (org-eval-in-calendar '(calendar-forward-day 1))))
  14923. (org-defkey map "!"
  14924. (lambda () (interactive)
  14925. (org-eval-in-calendar '(diary-view-entries))
  14926. (message "")))
  14927. (org-defkey map ">"
  14928. (lambda () (interactive)
  14929. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14930. (org-defkey map "<"
  14931. (lambda () (interactive)
  14932. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14933. (org-defkey map "\C-v"
  14934. (lambda () (interactive)
  14935. (org-eval-in-calendar
  14936. '(calendar-scroll-left-three-months 1))))
  14937. (org-defkey map "\M-v"
  14938. (lambda () (interactive)
  14939. (org-eval-in-calendar
  14940. '(calendar-scroll-right-three-months 1))))
  14941. map)
  14942. "Keymap for minibuffer commands when using `org-read-date'.")
  14943. (defvar org-def)
  14944. (defvar org-defdecode)
  14945. (defvar org-with-time)
  14946. (defvar calendar-setup) ; Dynamically scoped.
  14947. (defun org-read-date (&optional with-time to-time from-string prompt
  14948. default-time default-input inactive)
  14949. "Read a date, possibly a time, and make things smooth for the user.
  14950. The prompt will suggest to enter an ISO date, but you can also enter anything
  14951. which will at least partially be understood by `parse-time-string'.
  14952. Unrecognized parts of the date will default to the current day, month, year,
  14953. hour and minute. If this command is called to replace a timestamp at point,
  14954. or to enter the second timestamp of a range, the default time is taken
  14955. from the existing stamp. Furthermore, the command prefers the future,
  14956. so if you are giving a date where the year is not given, and the day-month
  14957. combination is already past in the current year, it will assume you
  14958. mean next year. For details, see the manual. A few examples:
  14959. 3-2-5 --> 2003-02-05
  14960. feb 15 --> currentyear-02-15
  14961. 2/15 --> currentyear-02-15
  14962. sep 12 9 --> 2009-09-12
  14963. 12:45 --> today 12:45
  14964. 22 sept 0:34 --> currentyear-09-22 0:34
  14965. 12 --> currentyear-currentmonth-12
  14966. Fri --> nearest Friday after today
  14967. -Tue --> last Tuesday
  14968. etc.
  14969. Furthermore you can specify a relative date by giving, as the *first* thing
  14970. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14971. change in days weeks, months, years.
  14972. With a single plus or minus, the date is relative to today. With a double
  14973. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14974. +4d --> four days from today
  14975. +4 --> same as above
  14976. +2w --> two weeks from today
  14977. ++5 --> five days from default date
  14978. The function understands only English month and weekday abbreviations.
  14979. While prompting, a calendar is popped up - you can also select the
  14980. date with the mouse (button 1). The calendar shows a period of three
  14981. months. To scroll it to other months, use the keys `>' and `<'.
  14982. If you don't like the calendar, turn it off with
  14983. (setq org-read-date-popup-calendar nil)
  14984. With optional argument TO-TIME, the date will immediately be converted
  14985. to an internal time.
  14986. With an optional argument WITH-TIME, the prompt will suggest to
  14987. also insert a time. Note that when WITH-TIME is not set, you can
  14988. still enter a time, and this function will inform the calling routine
  14989. about this change. The calling routine may then choose to change the
  14990. format used to insert the time stamp into the buffer to include the time.
  14991. With optional argument FROM-STRING, read from this string instead from
  14992. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14993. the time/date that is used for everything that is not specified by the
  14994. user."
  14995. (require 'parse-time)
  14996. (let* ((org-with-time with-time)
  14997. (org-time-stamp-rounding-minutes
  14998. (if (equal org-with-time '(16))
  14999. '(0 0)
  15000. org-time-stamp-rounding-minutes))
  15001. (org-dcst org-display-custom-times)
  15002. (ct (org-current-time))
  15003. (org-def (or org-overriding-default-time default-time ct))
  15004. (org-defdecode (decode-time org-def))
  15005. (cur-frame (selected-frame))
  15006. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15007. (calendar-setup
  15008. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15009. (calendar-move-hook nil)
  15010. (calendar-view-diary-initially-flag nil)
  15011. (calendar-view-holidays-initially-flag nil)
  15012. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15013. ;; Rationalize `org-def' and `org-defdecode', if required.
  15014. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15015. (setf (nth 2 org-defdecode) -1)
  15016. (setf (nth 1 org-defdecode) 59)
  15017. (setq org-def (apply #'encode-time org-defdecode))
  15018. (setq org-defdecode (decode-time org-def)))
  15019. (let* ((timestr (format-time-string
  15020. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15021. org-def))
  15022. (prompt (concat (if prompt (concat prompt " ") "")
  15023. (format "Date+time [%s]: " timestr))))
  15024. (cond
  15025. (from-string (setq ans from-string))
  15026. (org-read-date-popup-calendar
  15027. (save-excursion
  15028. (save-window-excursion
  15029. (calendar)
  15030. (when (eq calendar-setup 'calendar-only)
  15031. (setq cal-frame
  15032. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15033. (select-frame cal-frame))
  15034. (org-eval-in-calendar '(setq cursor-type nil) t)
  15035. (unwind-protect
  15036. (progn
  15037. (calendar-forward-day (- (time-to-days org-def)
  15038. (calendar-absolute-from-gregorian
  15039. (calendar-current-date))))
  15040. (org-eval-in-calendar nil t)
  15041. (let* ((old-map (current-local-map))
  15042. (map (copy-keymap calendar-mode-map))
  15043. (minibuffer-local-map
  15044. (copy-keymap org-read-date-minibuffer-local-map)))
  15045. (org-defkey map (kbd "RET") 'org-calendar-select)
  15046. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15047. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15048. (unwind-protect
  15049. (progn
  15050. (use-local-map map)
  15051. (setq org-read-date-inactive inactive)
  15052. (add-hook 'post-command-hook 'org-read-date-display)
  15053. (setq org-ans0
  15054. (read-string prompt
  15055. default-input
  15056. 'org-read-date-history
  15057. nil))
  15058. ;; org-ans0: from prompt
  15059. ;; org-ans1: from mouse click
  15060. ;; org-ans2: from calendar motion
  15061. (setq ans
  15062. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15063. (remove-hook 'post-command-hook 'org-read-date-display)
  15064. (use-local-map old-map)
  15065. (when org-read-date-overlay
  15066. (delete-overlay org-read-date-overlay)
  15067. (setq org-read-date-overlay nil)))))
  15068. (bury-buffer "*Calendar*")
  15069. (when cal-frame
  15070. (delete-frame cal-frame)
  15071. (select-frame-set-input-focus cur-frame))))))
  15072. (t ; Naked prompt only
  15073. (unwind-protect
  15074. (setq ans (read-string prompt default-input
  15075. 'org-read-date-history timestr))
  15076. (when org-read-date-overlay
  15077. (delete-overlay org-read-date-overlay)
  15078. (setq org-read-date-overlay nil))))))
  15079. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15080. (when org-read-date-analyze-forced-year
  15081. (message "Year was forced into %s"
  15082. (if org-read-date-force-compatible-dates
  15083. "compatible range (1970-2037)"
  15084. "range representable on this machine"))
  15085. (ding))
  15086. ;; One round trip to get rid of 34th of August and stuff like that....
  15087. (setq final (decode-time (apply 'encode-time final)))
  15088. (setq org-read-date-final-answer ans)
  15089. (if to-time
  15090. (apply 'encode-time final)
  15091. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15092. (format "%04d-%02d-%02d %02d:%02d"
  15093. (nth 5 final) (nth 4 final) (nth 3 final)
  15094. (nth 2 final) (nth 1 final))
  15095. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15096. (defun org-read-date-display ()
  15097. "Display the current date prompt interpretation in the minibuffer."
  15098. (when org-read-date-display-live
  15099. (when org-read-date-overlay
  15100. (delete-overlay org-read-date-overlay))
  15101. (when (minibufferp (current-buffer))
  15102. (save-excursion
  15103. (end-of-line 1)
  15104. (while (not (equal (buffer-substring
  15105. (max (point-min) (- (point) 4)) (point))
  15106. " "))
  15107. (insert " ")))
  15108. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15109. " " (or org-ans1 org-ans2)))
  15110. (org-end-time-was-given nil)
  15111. (f (org-read-date-analyze ans org-def org-defdecode))
  15112. (fmts (if org-dcst
  15113. org-time-stamp-custom-formats
  15114. org-time-stamp-formats))
  15115. (fmt (if (or org-with-time
  15116. (and (boundp 'org-time-was-given) org-time-was-given))
  15117. (cdr fmts)
  15118. (car fmts)))
  15119. (txt (format-time-string fmt (apply 'encode-time f)))
  15120. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15121. (txt (concat "=> " txt)))
  15122. (when (and org-end-time-was-given
  15123. (string-match org-plain-time-of-day-regexp txt))
  15124. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15125. org-end-time-was-given
  15126. (substring txt (match-end 0)))))
  15127. (when org-read-date-analyze-futurep
  15128. (setq txt (concat txt " (=>F)")))
  15129. (setq org-read-date-overlay
  15130. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15131. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15132. (defun org-read-date-analyze (ans def defdecode)
  15133. "Analyze the combined answer of the date prompt."
  15134. ;; FIXME: cleanup and comment
  15135. ;; Pass `current-time' result to `decode-time' (instead of calling
  15136. ;; without arguments) so that only `current-time' has to be
  15137. ;; overridden in tests.
  15138. (let ((org-def def)
  15139. (org-defdecode defdecode)
  15140. (nowdecode (decode-time (current-time)))
  15141. delta deltan deltaw deltadef year month day
  15142. hour minute second wday pm h2 m2 tl wday1
  15143. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15144. (setq org-read-date-analyze-futurep nil
  15145. org-read-date-analyze-forced-year nil)
  15146. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15147. (setq ans "+0"))
  15148. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15149. (setq ans (replace-match "" t t ans)
  15150. deltan (car delta)
  15151. deltaw (nth 1 delta)
  15152. deltadef (nth 2 delta)))
  15153. ;; Check if there is an iso week date in there. If yes, store the
  15154. ;; info and postpone interpreting it until the rest of the parsing
  15155. ;; is done.
  15156. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15157. (setq iso-year (when (match-end 1)
  15158. (org-small-year-to-year
  15159. (string-to-number (match-string 1 ans))))
  15160. iso-weekday (when (match-end 3)
  15161. (string-to-number (match-string 3 ans)))
  15162. iso-week (string-to-number (match-string 2 ans)))
  15163. (setq ans (replace-match "" t t ans)))
  15164. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15165. (when (string-match
  15166. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15167. (setq year (if (match-end 2)
  15168. (string-to-number (match-string 2 ans))
  15169. (progn (setq kill-year t)
  15170. (string-to-number (format-time-string "%Y"))))
  15171. month (string-to-number (match-string 3 ans))
  15172. day (string-to-number (match-string 4 ans)))
  15173. (setq year (org-small-year-to-year year))
  15174. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15175. t nil ans)))
  15176. ;; Help matching dotted european dates
  15177. (when (string-match
  15178. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15179. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15180. (setq kill-year t)
  15181. (string-to-number (format-time-string "%Y")))
  15182. day (string-to-number (match-string 1 ans))
  15183. month (string-to-number (match-string 2 ans))
  15184. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15185. t nil ans)))
  15186. ;; Help matching american dates, like 5/30 or 5/30/7
  15187. (when (string-match
  15188. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15189. (setq year (if (match-end 4)
  15190. (string-to-number (match-string 4 ans))
  15191. (progn (setq kill-year t)
  15192. (string-to-number (format-time-string "%Y"))))
  15193. month (string-to-number (match-string 1 ans))
  15194. day (string-to-number (match-string 2 ans)))
  15195. (setq year (org-small-year-to-year year))
  15196. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15197. t nil ans)))
  15198. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15199. ;; If there is a time with am/pm, and *no* time without it, we convert
  15200. ;; so that matching will be successful.
  15201. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15202. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15203. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15204. (setq hour (string-to-number (match-string 1 ans))
  15205. minute (if (match-end 3)
  15206. (string-to-number (match-string 3 ans))
  15207. 0)
  15208. pm (equal ?p
  15209. (string-to-char (downcase (match-string 4 ans)))))
  15210. (if (and (= hour 12) (not pm))
  15211. (setq hour 0)
  15212. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15213. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15214. t t ans))))
  15215. ;; Check if a time range is given as a duration
  15216. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15217. (setq hour (string-to-number (match-string 1 ans))
  15218. h2 (+ hour (string-to-number (match-string 3 ans)))
  15219. minute (string-to-number (match-string 2 ans))
  15220. m2 (+ minute (if (match-end 5) (string-to-number
  15221. (match-string 5 ans))0)))
  15222. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15223. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15224. t t ans)))
  15225. ;; Check if there is a time range
  15226. (when (boundp 'org-end-time-was-given)
  15227. (setq org-time-was-given nil)
  15228. (when (and (string-match org-plain-time-of-day-regexp ans)
  15229. (match-end 8))
  15230. (setq org-end-time-was-given (match-string 8 ans))
  15231. (setq ans (concat (substring ans 0 (match-beginning 7))
  15232. (substring ans (match-end 7))))))
  15233. (setq tl (parse-time-string ans)
  15234. day (or (nth 3 tl) (nth 3 org-defdecode))
  15235. month
  15236. (cond ((nth 4 tl))
  15237. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15238. ;; Day was specified. Make sure DAY+MONTH
  15239. ;; combination happens in the future.
  15240. ((nth 3 tl)
  15241. (setq futurep t)
  15242. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15243. (nth 4 nowdecode)))
  15244. (t (nth 4 org-defdecode)))
  15245. year
  15246. (cond ((and (not kill-year) (nth 5 tl)))
  15247. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15248. ;; Month was guessed in the future and is at least
  15249. ;; equal to NOWDECODE's. Fix year accordingly.
  15250. (futurep
  15251. (if (or (> month (nth 4 nowdecode))
  15252. (>= day (nth 3 nowdecode)))
  15253. (nth 5 nowdecode)
  15254. (1+ (nth 5 nowdecode))))
  15255. ;; Month was specified. Make sure MONTH+YEAR
  15256. ;; combination happens in the future.
  15257. ((nth 4 tl)
  15258. (setq futurep t)
  15259. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15260. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15261. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15262. (t (nth 5 nowdecode))))
  15263. (t (nth 5 org-defdecode)))
  15264. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15265. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15266. second (or (nth 0 tl) 0)
  15267. wday (nth 6 tl))
  15268. (when (and (eq org-read-date-prefer-future 'time)
  15269. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15270. (equal day (nth 3 nowdecode))
  15271. (equal month (nth 4 nowdecode))
  15272. (equal year (nth 5 nowdecode))
  15273. (nth 2 tl)
  15274. (or (< (nth 2 tl) (nth 2 nowdecode))
  15275. (and (= (nth 2 tl) (nth 2 nowdecode))
  15276. (nth 1 tl)
  15277. (< (nth 1 tl) (nth 1 nowdecode)))))
  15278. (setq day (1+ day)
  15279. futurep t))
  15280. ;; Special date definitions below
  15281. (cond
  15282. (iso-week
  15283. ;; There was an iso week
  15284. (require 'cal-iso)
  15285. (setq futurep nil)
  15286. (setq year (or iso-year year)
  15287. day (or iso-weekday wday 1)
  15288. wday nil ; to make sure that the trigger below does not match
  15289. iso-date (calendar-gregorian-from-absolute
  15290. (calendar-iso-to-absolute
  15291. (list iso-week day year))))
  15292. ; FIXME: Should we also push ISO weeks into the future?
  15293. ; (when (and org-read-date-prefer-future
  15294. ; (not iso-year)
  15295. ; (< (calendar-absolute-from-gregorian iso-date)
  15296. ; (time-to-days (current-time))))
  15297. ; (setq year (1+ year)
  15298. ; iso-date (calendar-gregorian-from-absolute
  15299. ; (calendar-iso-to-absolute
  15300. ; (list iso-week day year)))))
  15301. (setq month (car iso-date)
  15302. year (nth 2 iso-date)
  15303. day (nth 1 iso-date)))
  15304. (deltan
  15305. (setq futurep nil)
  15306. (unless deltadef
  15307. ;; Pass `current-time' result to `decode-time' (instead of
  15308. ;; calling without arguments) so that only `current-time' has
  15309. ;; to be overridden in tests.
  15310. (let ((now (decode-time (current-time))))
  15311. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15312. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15313. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15314. ((equal deltaw "m") (setq month (+ month deltan)))
  15315. ((equal deltaw "y") (setq year (+ year deltan)))))
  15316. ((and wday (not (nth 3 tl)))
  15317. ;; Weekday was given, but no day, so pick that day in the week
  15318. ;; on or after the derived date.
  15319. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15320. (unless (equal wday wday1)
  15321. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15322. (when (and (boundp 'org-time-was-given)
  15323. (nth 2 tl))
  15324. (setq org-time-was-given t))
  15325. (when (< year 100) (setq year (+ 2000 year)))
  15326. ;; Check of the date is representable
  15327. (if org-read-date-force-compatible-dates
  15328. (progn
  15329. (when (< year 1970)
  15330. (setq year 1970 org-read-date-analyze-forced-year t))
  15331. (when (> year 2037)
  15332. (setq year 2037 org-read-date-analyze-forced-year t)))
  15333. (condition-case nil
  15334. (ignore (encode-time second minute hour day month year))
  15335. (error
  15336. (setq year (nth 5 org-defdecode))
  15337. (setq org-read-date-analyze-forced-year t))))
  15338. (setq org-read-date-analyze-futurep futurep)
  15339. (list second minute hour day month year)))
  15340. (defvar parse-time-weekdays)
  15341. (defun org-read-date-get-relative (s today default)
  15342. "Check string S for special relative date string.
  15343. TODAY and DEFAULT are internal times, for today and for a default.
  15344. Return shift list (N what def-flag)
  15345. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15346. N is the number of WHATs to shift.
  15347. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15348. the DEFAULT date rather than TODAY."
  15349. (require 'parse-time)
  15350. (when (and
  15351. (string-match
  15352. (concat
  15353. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15354. "\\([0-9]+\\)?"
  15355. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15356. "\\([ \t]\\|$\\)") s)
  15357. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15358. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15359. (string-to-char (substring (match-string 1 s) -1))
  15360. ?+))
  15361. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15362. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15363. (what (if (match-end 3) (match-string 3 s) "d"))
  15364. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15365. (date (if rel default today))
  15366. (wday (nth 6 (decode-time date)))
  15367. delta)
  15368. (if wday1
  15369. (progn
  15370. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15371. (when (= delta 0) (setq delta 7))
  15372. (when (= dir ?-)
  15373. (setq delta (- delta 7))
  15374. (when (= delta 0) (setq delta -7)))
  15375. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15376. (list delta "d" rel))
  15377. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15378. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15379. "Turn a user-specified date into the internal representation.
  15380. The internal representation needed by the calendar is (month day year).
  15381. This is a wrapper to handle the brain-dead convention in calendar that
  15382. user function argument order change dependent on argument order."
  15383. (pcase calendar-date-style
  15384. (`american (list arg1 arg2 arg3))
  15385. (`european (list arg2 arg1 arg3))
  15386. (`iso (list arg2 arg3 arg1))))
  15387. (defun org-eval-in-calendar (form &optional keepdate)
  15388. "Eval FORM in the calendar window and return to current window.
  15389. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15390. (let ((sf (selected-frame))
  15391. (sw (selected-window)))
  15392. (select-window (get-buffer-window "*Calendar*" t))
  15393. (eval form)
  15394. (when (and (not keepdate) (calendar-cursor-to-date))
  15395. (let* ((date (calendar-cursor-to-date))
  15396. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15397. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15398. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15399. (select-window sw)
  15400. (select-frame-set-input-focus sf)))
  15401. (defun org-calendar-select ()
  15402. "Return to `org-read-date' with the date currently selected.
  15403. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15404. (interactive)
  15405. (when (calendar-cursor-to-date)
  15406. (let* ((date (calendar-cursor-to-date))
  15407. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15408. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15409. (when (active-minibuffer-window) (exit-minibuffer))))
  15410. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15411. "Insert a date stamp for the date given by the internal TIME.
  15412. See `format-time-string' for the format of TIME.
  15413. WITH-HM means use the stamp format that includes the time of the day.
  15414. INACTIVE means use square brackets instead of angular ones, so that the
  15415. stamp will not contribute to the agenda.
  15416. PRE and POST are optional strings to be inserted before and after the
  15417. stamp.
  15418. The command returns the inserted time stamp."
  15419. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15420. stamp)
  15421. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15422. (insert-before-markers (or pre ""))
  15423. (when (listp extra)
  15424. (setq extra (car extra))
  15425. (if (and (stringp extra)
  15426. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15427. (setq extra (format "-%02d:%02d"
  15428. (string-to-number (match-string 1 extra))
  15429. (string-to-number (match-string 2 extra))))
  15430. (setq extra nil)))
  15431. (when extra
  15432. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15433. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15434. (insert-before-markers (or post ""))
  15435. (setq org-last-inserted-timestamp stamp)))
  15436. (defun org-toggle-time-stamp-overlays ()
  15437. "Toggle the use of custom time stamp formats."
  15438. (interactive)
  15439. (setq org-display-custom-times (not org-display-custom-times))
  15440. (unless org-display-custom-times
  15441. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15442. (while (setq p (next-single-property-change p 'display))
  15443. (when (and (get-text-property p 'display)
  15444. (eq (get-text-property p 'face) 'org-date))
  15445. (remove-text-properties
  15446. p (setq p (next-single-property-change p 'display))
  15447. '(display t))))
  15448. (set-buffer-modified-p bmp)))
  15449. (org-restart-font-lock)
  15450. (setq org-table-may-need-update t)
  15451. (if org-display-custom-times
  15452. (message "Time stamps are overlaid with custom format")
  15453. (message "Time stamp overlays removed")))
  15454. (defun org-display-custom-time (beg end)
  15455. "Overlay modified time stamp format over timestamp between BEG and END."
  15456. (let* ((ts (buffer-substring beg end))
  15457. t1 with-hm tf time str (off 0))
  15458. (save-match-data
  15459. (setq t1 (org-parse-time-string ts t))
  15460. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15461. (setq off (- (match-end 0) (match-beginning 0)))))
  15462. (setq end (- end off))
  15463. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15464. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15465. time (org-fix-decoded-time t1)
  15466. str (org-add-props
  15467. (format-time-string
  15468. (substring tf 1 -1) (apply 'encode-time time))
  15469. nil 'mouse-face 'highlight))
  15470. (put-text-property beg end 'display str)))
  15471. (defun org-fix-decoded-time (time)
  15472. "Set 0 instead of nil for the first 6 elements of time.
  15473. Don't touch the rest."
  15474. (let ((n 0))
  15475. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15476. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15477. "Difference between TIMESTAMP-STRING and now in days.
  15478. If SECONDS is non-nil, return the difference in seconds."
  15479. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15480. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15481. (funcall fdiff (current-time)))))
  15482. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15483. "Is the time in TIMESTAMP-STRING close to the current date?"
  15484. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15485. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15486. (not (org-entry-is-done-p))))
  15487. (defun org-get-wdays (ts &optional delay zero-delay)
  15488. "Get the deadline lead time appropriate for timestring TS.
  15489. When DELAY is non-nil, get the delay time for scheduled items
  15490. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15491. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15492. don't try to find the delay cookie in the scheduled timestamp."
  15493. (let ((tv (if delay org-scheduled-delay-days
  15494. org-deadline-warning-days)))
  15495. (cond
  15496. ((or (and delay (< tv 0))
  15497. (and delay zero-delay (<= tv 0))
  15498. (and (not delay) (<= tv 0)))
  15499. ;; Enforce this value no matter what
  15500. (- tv))
  15501. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15502. ;; lead time is specified.
  15503. (floor (* (string-to-number (match-string 1 ts))
  15504. (cdr (assoc (match-string 2 ts)
  15505. '(("d" . 1) ("w" . 7)
  15506. ("m" . 30.4) ("y" . 365.25)
  15507. ("h" . 0.041667)))))))
  15508. ;; go for the default.
  15509. (t tv))))
  15510. (defun org-calendar-select-mouse (ev)
  15511. "Return to `org-read-date' with the date currently selected.
  15512. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15513. (interactive "e")
  15514. (mouse-set-point ev)
  15515. (when (calendar-cursor-to-date)
  15516. (let* ((date (calendar-cursor-to-date))
  15517. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15518. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15519. (when (active-minibuffer-window) (exit-minibuffer))))
  15520. (defun org-check-deadlines (ndays)
  15521. "Check if there are any deadlines due or past due.
  15522. A deadline is considered due if it happens within `org-deadline-warning-days'
  15523. days from today's date. If the deadline appears in an entry marked DONE,
  15524. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15525. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15526. are shown."
  15527. (interactive "P")
  15528. (let* ((org-warn-days
  15529. (cond
  15530. ((equal ndays '(4)) 100000)
  15531. (ndays (prefix-numeric-value ndays))
  15532. (t (abs org-deadline-warning-days))))
  15533. (case-fold-search nil)
  15534. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15535. (callback
  15536. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15537. (message "%d deadlines past-due or due within %d days"
  15538. (org-occur regexp nil callback)
  15539. org-warn-days)))
  15540. (defsubst org-re-timestamp (type)
  15541. "Return a regexp for timestamp TYPE.
  15542. Allowed values for TYPE are:
  15543. all: all timestamps
  15544. active: only active timestamps (<...>)
  15545. inactive: only inactive timestamps ([...])
  15546. scheduled: only scheduled timestamps
  15547. deadline: only deadline timestamps
  15548. closed: only closed time-stamps
  15549. When TYPE is nil, fall back on returning a regexp that matches
  15550. both scheduled and deadline timestamps."
  15551. (cl-case type
  15552. (all org-ts-regexp-both)
  15553. (active org-ts-regexp)
  15554. (inactive org-ts-regexp-inactive)
  15555. (scheduled org-scheduled-time-regexp)
  15556. (deadline org-deadline-time-regexp)
  15557. (closed org-closed-time-regexp)
  15558. (otherwise
  15559. (concat "\\<"
  15560. (regexp-opt (list org-deadline-string org-scheduled-string))
  15561. " *<\\([^>]+\\)>"))))
  15562. (defun org-check-before-date (d)
  15563. "Check if there are deadlines or scheduled entries before date D."
  15564. (interactive (list (org-read-date)))
  15565. (let* ((case-fold-search nil)
  15566. (regexp (org-re-timestamp org-ts-type))
  15567. (ts-type org-ts-type)
  15568. (callback
  15569. (lambda ()
  15570. (let ((match (match-string 1)))
  15571. (and (if (memq ts-type '(active inactive all))
  15572. (eq (org-element-type (save-excursion
  15573. (backward-char)
  15574. (org-element-context)))
  15575. 'timestamp)
  15576. (org-at-planning-p))
  15577. (time-less-p
  15578. (org-time-string-to-time match t)
  15579. (org-time-string-to-time d t)))))))
  15580. (message "%d entries before %s"
  15581. (org-occur regexp nil callback)
  15582. d)))
  15583. (defun org-check-after-date (d)
  15584. "Check if there are deadlines or scheduled entries after date D."
  15585. (interactive (list (org-read-date)))
  15586. (let* ((case-fold-search nil)
  15587. (regexp (org-re-timestamp org-ts-type))
  15588. (ts-type org-ts-type)
  15589. (callback
  15590. (lambda ()
  15591. (let ((match (match-string 1)))
  15592. (and (if (memq ts-type '(active inactive all))
  15593. (eq (org-element-type (save-excursion
  15594. (backward-char)
  15595. (org-element-context)))
  15596. 'timestamp)
  15597. (org-at-planning-p))
  15598. (not (time-less-p
  15599. (org-time-string-to-time match t)
  15600. (org-time-string-to-time d t))))))))
  15601. (message "%d entries after %s"
  15602. (org-occur regexp nil callback)
  15603. d)))
  15604. (defun org-check-dates-range (start-date end-date)
  15605. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15606. (interactive (list (org-read-date nil nil nil "Range starts")
  15607. (org-read-date nil nil nil "Range end")))
  15608. (let ((case-fold-search nil)
  15609. (regexp (org-re-timestamp org-ts-type))
  15610. (callback
  15611. (let ((type org-ts-type))
  15612. (lambda ()
  15613. (let ((match (match-string 1)))
  15614. (and
  15615. (if (memq 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 t)
  15623. (org-time-string-to-time start-date t)))
  15624. (time-less-p
  15625. (org-time-string-to-time match t)
  15626. (org-time-string-to-time end-date t))))))))
  15627. (message "%d entries between %s and %s"
  15628. (org-occur regexp nil callback) start-date end-date)))
  15629. (defun org-evaluate-time-range (&optional to-buffer)
  15630. "Evaluate a time range by computing the difference between start and end.
  15631. Normally the result is just printed in the echo area, but with prefix arg
  15632. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15633. If the time range is actually in a table, the result is inserted into the
  15634. next column.
  15635. For time difference computation, a year is assumed to be exactly 365
  15636. days in order to avoid rounding problems."
  15637. (interactive "P")
  15638. (or
  15639. (org-clock-update-time-maybe)
  15640. (save-excursion
  15641. (unless (org-at-date-range-p t)
  15642. (goto-char (point-at-bol))
  15643. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15644. (unless (org-at-date-range-p t)
  15645. (user-error "Not at a time-stamp range, and none found in current line")))
  15646. (let* ((ts1 (match-string 1))
  15647. (ts2 (match-string 2))
  15648. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15649. (match-end (match-end 0))
  15650. (time1 (org-time-string-to-time ts1))
  15651. (time2 (org-time-string-to-time ts2))
  15652. (t1 (float-time time1))
  15653. (t2 (float-time time2))
  15654. (diff (abs (- t2 t1)))
  15655. (negative (< (- t2 t1) 0))
  15656. ;; (ys (floor (* 365 24 60 60)))
  15657. (ds (* 24 60 60))
  15658. (hs (* 60 60))
  15659. (fy "%dy %dd %02d:%02d")
  15660. (fy1 "%dy %dd")
  15661. (fd "%dd %02d:%02d")
  15662. (fd1 "%dd")
  15663. (fh "%02d:%02d")
  15664. y d h m align)
  15665. (if havetime
  15666. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15667. y 0
  15668. d (floor (/ diff ds)) diff (mod diff ds)
  15669. h (floor (/ diff hs)) diff (mod diff hs)
  15670. m (floor (/ diff 60)))
  15671. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15672. y 0
  15673. d (floor (+ (/ diff ds) 0.5))
  15674. h 0 m 0))
  15675. (if (not to-buffer)
  15676. (message "%s" (org-make-tdiff-string y d h m))
  15677. (if (org-at-table-p)
  15678. (progn
  15679. (goto-char match-end)
  15680. (setq align t)
  15681. (and (looking-at " *|") (goto-char (match-end 0))))
  15682. (goto-char match-end))
  15683. (when (looking-at
  15684. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15685. (replace-match ""))
  15686. (when negative (insert " -"))
  15687. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15688. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15689. (insert " " (format fh h m))))
  15690. (when align (org-table-align))
  15691. (message "Time difference inserted")))))
  15692. (defun org-make-tdiff-string (y d h m)
  15693. (let ((fmt "")
  15694. (l nil))
  15695. (when (> y 0)
  15696. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15697. (push y l))
  15698. (when (> d 0)
  15699. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15700. (push d l))
  15701. (when (> h 0)
  15702. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15703. (push h l))
  15704. (when (> m 0)
  15705. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15706. (push m l))
  15707. (apply 'format fmt (nreverse l))))
  15708. (defun org-time-string-to-time (s &optional zone)
  15709. "Convert timestamp string S into internal time.
  15710. The optional ZONE is omitted or nil for Emacs local time, t for
  15711. Universal Time, ‘wall’ for system wall clock time, or a string as
  15712. in the TZ environment variable."
  15713. (apply #'encode-time (org-parse-time-string s nil zone)))
  15714. (defun org-time-string-to-seconds (s &optional zone)
  15715. "Convert a timestamp string S into a number of seconds.
  15716. The optional ZONE is omitted or nil for Emacs local time, t for
  15717. Universal Time, ‘wall’ for system wall clock time, or a string as
  15718. in the TZ environment variable."
  15719. (float-time (org-time-string-to-time s zone)))
  15720. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15721. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15722. "Convert time stamp S to an absolute day number.
  15723. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15724. stamp, get the closest date to DAYNR. If PREFER is
  15725. `past' (respectively `future') return a date past (respectively
  15726. after) or equal to DAYNR.
  15727. POS is the location of time stamp S, as a buffer position in
  15728. BUFFER.
  15729. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15730. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15731. signaled."
  15732. (cond
  15733. ((string-match "\\`%%\\((.*)\\)" s)
  15734. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15735. ;; only able to match individual dates. If it fails, raise an
  15736. ;; error.
  15737. (if (and daynr
  15738. (org-diary-sexp-entry
  15739. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15740. daynr
  15741. (signal 'org-diary-sexp-no-match (list s))))
  15742. (daynr (org-closest-date s daynr prefer))
  15743. (t (time-to-days
  15744. (condition-case errdata
  15745. (apply #'encode-time (org-parse-time-string s))
  15746. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15747. s
  15748. (if (not (and buffer pos)) ""
  15749. (format-message " at %d in buffer `%s'" pos buffer))
  15750. (cdr errdata))))))))
  15751. (defun org-days-to-iso-week (days)
  15752. "Return the iso week number."
  15753. (require 'cal-iso)
  15754. (car (calendar-iso-from-absolute days)))
  15755. (defun org-small-year-to-year (year)
  15756. "Convert 2-digit years into 4-digit years.
  15757. YEAR is expanded into one of the 30 next years, if possible, or
  15758. into a past one. Any year larger than 99 is returned unchanged."
  15759. (if (>= year 100) year
  15760. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15761. (century (/ current 100))
  15762. (offset (- year (% current 100))))
  15763. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15764. ((> offset -70) (+ (* century 100) year))
  15765. (t (+ (* (1+ century) 100) year))))))
  15766. (defun org-time-from-absolute (d)
  15767. "Return the time corresponding to date D.
  15768. D may be an absolute day number, or a calendar-type list (month day year)."
  15769. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15770. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15771. (defvar org-agenda-current-date)
  15772. (defun org-calendar-holiday ()
  15773. "List of holidays, for Diary display in Org mode."
  15774. (require 'holidays)
  15775. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15776. (and hl (mapconcat #'identity hl "; "))))
  15777. (defun org-diary-sexp-entry (sexp entry d)
  15778. "Process a SEXP diary ENTRY for date D."
  15779. (require 'diary-lib)
  15780. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15781. ;; dynamically.
  15782. (let* ((sexp `(let ((entry ,entry)
  15783. (date ',d))
  15784. ,(car (read-from-string sexp))))
  15785. (result (if calendar-debug-sexp (eval sexp)
  15786. (condition-case nil
  15787. (eval sexp)
  15788. (error
  15789. (beep)
  15790. (message "Bad sexp at line %d in %s: %s"
  15791. (org-current-line)
  15792. (buffer-file-name) sexp)
  15793. (sleep-for 2))))))
  15794. (cond ((stringp result) (split-string result "; "))
  15795. ((and (consp result)
  15796. (not (consp (cdr result)))
  15797. (stringp (cdr result))) (cdr result))
  15798. ((and (consp result)
  15799. (stringp (car result))) result)
  15800. (result entry))))
  15801. (defun org-diary-to-ical-string (frombuf)
  15802. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15803. This uses the icalendar.el library."
  15804. (let* ((tmpdir temporary-file-directory)
  15805. (tmpfile (make-temp-name
  15806. (expand-file-name "orgics" tmpdir)))
  15807. buf rtn b e)
  15808. (with-current-buffer frombuf
  15809. (icalendar-export-region (point-min) (point-max) tmpfile)
  15810. (setq buf (find-buffer-visiting tmpfile))
  15811. (set-buffer buf)
  15812. (goto-char (point-min))
  15813. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15814. (setq b (match-beginning 0)))
  15815. (goto-char (point-max))
  15816. (when (re-search-backward "^END:VEVENT" nil t)
  15817. (setq e (match-end 0)))
  15818. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15819. (kill-buffer buf)
  15820. (delete-file tmpfile)
  15821. rtn))
  15822. (defun org-closest-date (start current prefer)
  15823. "Return closest date to CURRENT starting from START.
  15824. CURRENT and START are both time stamps.
  15825. When PREFER is `past', return a date that is either CURRENT or
  15826. past. When PREFER is `future', return a date that is either
  15827. CURRENT or future.
  15828. Only time stamps with a repeater are modified. Any other time
  15829. stamp stay unchanged. In any case, return value is an absolute
  15830. day number."
  15831. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15832. ;; No repeater. Do not shift time stamp.
  15833. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15834. (let ((value (string-to-number (match-string 1 start)))
  15835. (type (match-string 2 start)))
  15836. (if (= 0 value)
  15837. ;; Repeater with a 0-value is considered as void.
  15838. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15839. (let* ((base (org-date-to-gregorian start))
  15840. (target (org-date-to-gregorian current))
  15841. (sday (calendar-absolute-from-gregorian base))
  15842. (cday (calendar-absolute-from-gregorian target))
  15843. n1 n2)
  15844. ;; If START is already past CURRENT, just return START.
  15845. (if (<= cday sday) sday
  15846. ;; Compute closest date before (N1) and closest date past
  15847. ;; (N2) CURRENT.
  15848. (pcase type
  15849. ("h"
  15850. (let ((missing-hours
  15851. (mod (+ (- (* 24 (- cday sday))
  15852. (nth 2 (org-parse-time-string start)))
  15853. org-extend-today-until)
  15854. value)))
  15855. (setf n1 (if (= missing-hours 0) cday
  15856. (- cday (1+ (/ missing-hours 24)))))
  15857. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15858. ((or "d" "w")
  15859. (let ((value (if (equal type "w") (* 7 value) value)))
  15860. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15861. (setf n2 (+ n1 value))))
  15862. ("m"
  15863. (let* ((add-months
  15864. (lambda (d n)
  15865. ;; Add N months to gregorian date D, i.e.,
  15866. ;; a list (MONTH DAY YEAR). Return a valid
  15867. ;; gregorian date.
  15868. (let ((m (+ (nth 0 d) n)))
  15869. (list (mod m 12)
  15870. (nth 1 d)
  15871. (+ (/ m 12) (nth 2 d))))))
  15872. (months ; Complete months to TARGET.
  15873. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15874. (- (nth 0 target) (nth 0 base))
  15875. ;; If START's day is greater than
  15876. ;; TARGET's, remove incomplete month.
  15877. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15878. value)
  15879. value))
  15880. (before (funcall add-months base months)))
  15881. (setf n1 (calendar-absolute-from-gregorian before))
  15882. (setf n2
  15883. (calendar-absolute-from-gregorian
  15884. (funcall add-months before value)))))
  15885. (_
  15886. (let* ((d (nth 1 base))
  15887. (m (nth 0 base))
  15888. (y (nth 2 base))
  15889. (years ; Complete years to TARGET.
  15890. (* (/ (- (nth 2 target)
  15891. y
  15892. ;; If START's month and day are
  15893. ;; greater than TARGET's, remove
  15894. ;; incomplete year.
  15895. (if (or (> (nth 0 target) m)
  15896. (and (= (nth 0 target) m)
  15897. (> (nth 1 target) d)))
  15898. 0
  15899. 1))
  15900. value)
  15901. value))
  15902. (before (list m d (+ y years))))
  15903. (setf n1 (calendar-absolute-from-gregorian before))
  15904. (setf n2 (calendar-absolute-from-gregorian
  15905. (list m d (+ (nth 2 before) value)))))))
  15906. ;; Handle PREFER parameter, if any.
  15907. (cond
  15908. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15909. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15910. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15911. (defun org-date-to-gregorian (d)
  15912. "Turn any specification of date D into a Gregorian date for the calendar."
  15913. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15914. ((and (listp d) (= (length d) 3)) d)
  15915. ((stringp d)
  15916. (let ((d (org-parse-time-string d)))
  15917. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15918. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15919. (defun org-parse-time-string (s &optional nodefault zone)
  15920. "Parse the standard Org time string.
  15921. This should be a lot faster than the normal `parse-time-string'.
  15922. If time is not given, defaults to 0:00. However, with optional
  15923. NODEFAULT, hour and minute fields will be nil if not given.
  15924. The optional ZONE is omitted or nil for Emacs local time, t for
  15925. Universal Time, ‘wall’ for system wall clock time, or a string as
  15926. in the TZ environment variable."
  15927. (cond ((string-match org-ts-regexp0 s)
  15928. (list 0
  15929. (when (or (match-beginning 8) (not nodefault))
  15930. (string-to-number (or (match-string 8 s) "0")))
  15931. (when (or (match-beginning 7) (not nodefault))
  15932. (string-to-number (or (match-string 7 s) "0")))
  15933. (string-to-number (match-string 4 s))
  15934. (string-to-number (match-string 3 s))
  15935. (string-to-number (match-string 2 s))
  15936. nil nil zone))
  15937. ((string-match "^<[^>]+>$" s)
  15938. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15939. ;; second argument. However, this requires at least Emacs
  15940. ;; 25.1. We can do it when we switch to this version as our
  15941. ;; minimal requirement.
  15942. (decode-time (seconds-to-time (org-matcher-time s))))
  15943. (t (error "Not a standard Org time string: %s" s))))
  15944. (defun org-timestamp-up (&optional arg)
  15945. "Increase the date item at the cursor by one.
  15946. If the cursor is on the year, change the year. If it is on the month,
  15947. the day or the time, change that.
  15948. With prefix ARG, change by that many units."
  15949. (interactive "p")
  15950. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15951. (defun org-timestamp-down (&optional arg)
  15952. "Decrease the date item at the cursor by one.
  15953. If the cursor is on the year, change the year. If it is on the month,
  15954. the day or the time, change that.
  15955. With prefix ARG, change by that many units."
  15956. (interactive "p")
  15957. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15958. (defun org-timestamp-up-day (&optional arg)
  15959. "Increase the date in the time stamp by one day.
  15960. With prefix ARG, change that many days."
  15961. (interactive "p")
  15962. (if (and (not (org-at-timestamp-p 'lax))
  15963. (org-at-heading-p))
  15964. (org-todo 'up)
  15965. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15966. (defun org-timestamp-down-day (&optional arg)
  15967. "Decrease the date in the time stamp by one day.
  15968. With prefix ARG, change that many days."
  15969. (interactive "p")
  15970. (if (and (not (org-at-timestamp-p 'lax))
  15971. (org-at-heading-p))
  15972. (org-todo 'down)
  15973. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15974. (defun org-at-timestamp-p (&optional extended)
  15975. "Non-nil if point is inside a timestamp.
  15976. By default, the function only consider syntactically valid active
  15977. timestamps. However, the caller may have a broader definition
  15978. for timestamps. As a consequence, optional argument EXTENDED can
  15979. be set to the following values
  15980. `inactive'
  15981. Include also syntactically valid inactive timestamps.
  15982. `agenda'
  15983. Include timestamps allowed in Agenda, i.e., those in
  15984. properties drawers, planning lines and clock lines.
  15985. `lax'
  15986. Ignore context. The function matches any part of the
  15987. document looking like a timestamp. This includes comments,
  15988. example blocks...
  15989. For backward-compatibility with Org 9.0, every other non-nil
  15990. value is equivalent to `inactive'.
  15991. When at a timestamp, return the position of the point as a symbol
  15992. among `bracket', `after', `year', `month', `hour', `minute',
  15993. `day' or a number of character from the last know part of the
  15994. time stamp.
  15995. When matching, the match groups are the following:
  15996. group 1: year
  15997. group 2: month
  15998. group 3: day number
  15999. group 4: day name
  16000. group 5: hours, if any
  16001. group 6: minutes, if any"
  16002. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16003. (pos (point))
  16004. (match?
  16005. (let ((boundaries (org-in-regexp regexp)))
  16006. (save-match-data
  16007. (cond ((null boundaries) nil)
  16008. ((eq extended 'lax) t)
  16009. (t
  16010. (or (and (eq extended 'agenda)
  16011. (or (org-at-planning-p)
  16012. (org-at-property-p)
  16013. (and (bound-and-true-p
  16014. org-agenda-include-inactive-timestamps)
  16015. (org-at-clock-log-p))))
  16016. (eq 'timestamp
  16017. (save-excursion
  16018. (when (= pos (cdr boundaries)) (forward-char -1))
  16019. (org-element-type (org-element-context)))))))))))
  16020. (cond
  16021. ((not match?) nil)
  16022. ((= pos (match-beginning 0)) 'bracket)
  16023. ;; Distinguish location right before the closing bracket from
  16024. ;; right after it.
  16025. ((= pos (1- (match-end 0))) 'bracket)
  16026. ((= pos (match-end 0)) 'after)
  16027. ((org-pos-in-match-range pos 2) 'year)
  16028. ((org-pos-in-match-range pos 3) 'month)
  16029. ((org-pos-in-match-range pos 7) 'hour)
  16030. ((org-pos-in-match-range pos 8) 'minute)
  16031. ((or (org-pos-in-match-range pos 4)
  16032. (org-pos-in-match-range pos 5)) 'day)
  16033. ((and (> pos (or (match-end 8) (match-end 5)))
  16034. (< pos (match-end 0)))
  16035. (- pos (or (match-end 8) (match-end 5))))
  16036. (t 'day))))
  16037. (defun org-toggle-timestamp-type ()
  16038. "Toggle the type (<active> or [inactive]) of a time stamp."
  16039. (interactive)
  16040. (when (org-at-timestamp-p 'lax)
  16041. (let ((beg (match-beginning 0)) (end (match-end 0))
  16042. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16043. (save-excursion
  16044. (goto-char beg)
  16045. (while (re-search-forward "[][<>]" end t)
  16046. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16047. t t)))
  16048. (message "Timestamp is now %sactive"
  16049. (if (equal (char-after beg) ?<) "" "in")))))
  16050. (defun org-at-clock-log-p ()
  16051. "Non-nil if point is on a clock log line."
  16052. (and (org-match-line org-clock-line-re)
  16053. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16054. (defvar org-clock-history) ; defined in org-clock.el
  16055. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16056. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16057. "Change the date in the time stamp at point.
  16058. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16059. `year', `minute', `second'. If WHAT is not given, the cursor position
  16060. in the timestamp determines what will be changed.
  16061. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16062. (let ((origin (point))
  16063. (timestamp? (org-at-timestamp-p 'lax))
  16064. origin-cat
  16065. with-hm inactive
  16066. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16067. extra rem
  16068. ts time time0 fixnext clrgx)
  16069. (unless timestamp? (user-error "Not at a timestamp"))
  16070. (if (and (not what) (eq timestamp? 'bracket))
  16071. (org-toggle-timestamp-type)
  16072. ;; Point isn't on brackets. Remember the part of the time-stamp
  16073. ;; the point was in. Indeed, size of time-stamps may change,
  16074. ;; but point must be kept in the same category nonetheless.
  16075. (setq origin-cat timestamp?)
  16076. (when (and (not what) (not (eq timestamp? 'day))
  16077. org-display-custom-times
  16078. (get-text-property (point) 'display)
  16079. (not (get-text-property (1- (point)) 'display)))
  16080. (setq timestamp? 'day))
  16081. (setq timestamp? (or what timestamp?)
  16082. inactive (= (char-after (match-beginning 0)) ?\[)
  16083. ts (match-string 0))
  16084. (replace-match "")
  16085. (when (string-match
  16086. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16087. ts)
  16088. (setq extra (match-string 1 ts))
  16089. (when suppress-tmp-delay
  16090. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16091. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16092. (setq with-hm t))
  16093. (setq time0 (org-parse-time-string ts))
  16094. (when (and updown
  16095. (eq timestamp? 'minute)
  16096. (not current-prefix-arg))
  16097. ;; This looks like s-up and s-down. Change by one rounding step.
  16098. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16099. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16100. (setcar (cdr time0) (+ (nth 1 time0)
  16101. (if (> n 0) (- rem) (- dm rem))))))
  16102. (setq time
  16103. (apply #'encode-time
  16104. (or (car time0) 0)
  16105. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16106. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16107. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16108. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16109. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16110. (nthcdr 6 time0)))
  16111. (when (and (memq timestamp? '(hour minute))
  16112. extra
  16113. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16114. (setq extra (org-modify-ts-extra
  16115. extra
  16116. (if (eq timestamp? 'hour) 2 5)
  16117. n dm)))
  16118. (when (integerp timestamp?)
  16119. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16120. (when (eq what 'calendar)
  16121. (let ((cal-date (org-get-date-from-calendar)))
  16122. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16123. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16124. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16125. (setcar time0 (or (car time0) 0))
  16126. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16127. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16128. (setq time (apply 'encode-time time0))))
  16129. ;; Insert the new time-stamp, and ensure point stays in the same
  16130. ;; category as before (i.e. not after the last position in that
  16131. ;; category).
  16132. (let ((pos (point)))
  16133. ;; Stay before inserted string. `save-excursion' is of no use.
  16134. (setq org-last-changed-timestamp
  16135. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16136. (goto-char pos))
  16137. (save-match-data
  16138. (looking-at org-ts-regexp3)
  16139. (goto-char
  16140. (pcase origin-cat
  16141. ;; `day' category ends before `hour' if any, or at the end
  16142. ;; of the day name.
  16143. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16144. (`hour (min (match-end 7) origin))
  16145. (`minute (min (1- (match-end 8)) origin))
  16146. ((pred integerp) (min (1- (match-end 0)) origin))
  16147. ;; Point was right after the time-stamp. However, the
  16148. ;; time-stamp length might have changed, so refer to
  16149. ;; (match-end 0) instead.
  16150. (`after (match-end 0))
  16151. ;; `year' and `month' have both fixed size: point couldn't
  16152. ;; have moved into another part.
  16153. (_ origin))))
  16154. ;; Update clock if on a CLOCK line.
  16155. (org-clock-update-time-maybe)
  16156. ;; Maybe adjust the closest clock in `org-clock-history'
  16157. (when org-clock-adjust-closest
  16158. (if (not (and (org-at-clock-log-p)
  16159. (< 1 (length (delq nil (mapcar 'marker-position
  16160. org-clock-history))))))
  16161. (message "No clock to adjust")
  16162. (cond ((save-excursion ; fix previous clock?
  16163. (re-search-backward org-ts-regexp0 nil t)
  16164. (looking-back (concat org-clock-string " \\[")
  16165. (line-beginning-position)))
  16166. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16167. ((save-excursion ; fix next clock?
  16168. (re-search-backward org-ts-regexp0 nil t)
  16169. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16170. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16171. (save-window-excursion
  16172. ;; Find closest clock to point, adjust the previous/next one in history
  16173. (let* ((p (save-excursion (org-back-to-heading t)))
  16174. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16175. (clfixnth
  16176. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16177. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16178. (if (not clfixpos)
  16179. (message "No clock to adjust")
  16180. (save-excursion
  16181. (org-goto-marker-or-bmk clfixpos)
  16182. (org-show-subtree)
  16183. (when (re-search-forward clrgx nil t)
  16184. (goto-char (match-beginning 1))
  16185. (let (org-clock-adjust-closest)
  16186. (org-timestamp-change n timestamp? updown))
  16187. (message "Clock adjusted in %s for heading: %s"
  16188. (file-name-nondirectory (buffer-file-name))
  16189. (org-get-heading t t)))))))))
  16190. ;; Try to recenter the calendar window, if any.
  16191. (when (and org-calendar-follow-timestamp-change
  16192. (get-buffer-window "*Calendar*" t)
  16193. (memq timestamp? '(day month year)))
  16194. (org-recenter-calendar (time-to-days time))))))
  16195. (defun org-modify-ts-extra (s pos n dm)
  16196. "Change the different parts of the lead-time and repeat fields in timestamp."
  16197. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16198. ng h m new rem)
  16199. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16200. (cond
  16201. ((or (org-pos-in-match-range pos 2)
  16202. (org-pos-in-match-range pos 3))
  16203. (setq m (string-to-number (match-string 3 s))
  16204. h (string-to-number (match-string 2 s)))
  16205. (if (org-pos-in-match-range pos 2)
  16206. (setq h (+ h n))
  16207. (setq n (* dm (with-no-warnings (signum n))))
  16208. (unless (= 0 (setq rem (% m dm)))
  16209. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16210. (setq m (+ m n)))
  16211. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16212. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16213. (setq h (mod h 24))
  16214. (setq ng 1 new (format "-%02d:%02d" h m)))
  16215. ((org-pos-in-match-range pos 6)
  16216. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16217. ((org-pos-in-match-range pos 5)
  16218. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16219. ((org-pos-in-match-range pos 9)
  16220. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16221. ((org-pos-in-match-range pos 8)
  16222. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16223. (when ng
  16224. (setq s (concat
  16225. (substring s 0 (match-beginning ng))
  16226. new
  16227. (substring s (match-end ng))))))
  16228. s))
  16229. (defun org-recenter-calendar (d)
  16230. "If the calendar is visible, recenter it to date D."
  16231. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16232. (when cwin
  16233. (let ((calendar-move-hook nil))
  16234. (with-selected-window cwin
  16235. (calendar-goto-date
  16236. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16237. (defun org-goto-calendar (&optional arg)
  16238. "Go to the Emacs calendar at the current date.
  16239. If there is a time stamp in the current line, go to that date.
  16240. A prefix ARG can be used to force the current date."
  16241. (interactive "P")
  16242. (let ((calendar-move-hook nil)
  16243. (calendar-view-holidays-initially-flag nil)
  16244. (calendar-view-diary-initially-flag nil)
  16245. diff)
  16246. (when (or (org-at-timestamp-p 'lax)
  16247. (org-match-line (concat ".*" org-ts-regexp)))
  16248. (let ((d1 (time-to-days (current-time)))
  16249. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16250. (setq diff (- d2 d1))))
  16251. (calendar)
  16252. (calendar-goto-today)
  16253. (when (and diff (not arg)) (calendar-forward-day diff))))
  16254. (defun org-get-date-from-calendar ()
  16255. "Return a list (month day year) of date at point in calendar."
  16256. (with-current-buffer "*Calendar*"
  16257. (save-match-data
  16258. (calendar-cursor-to-date))))
  16259. (defun org-date-from-calendar ()
  16260. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16261. If there is already a time stamp at the cursor position, update it."
  16262. (interactive)
  16263. (if (org-at-timestamp-p 'lax)
  16264. (org-timestamp-change 0 'calendar)
  16265. (let ((cal-date (org-get-date-from-calendar)))
  16266. (org-insert-time-stamp
  16267. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16268. (defcustom org-effort-durations
  16269. `(("min" . 1)
  16270. ("h" . 60)
  16271. ("d" . ,(* 60 8))
  16272. ("w" . ,(* 60 8 5))
  16273. ("m" . ,(* 60 8 5 4))
  16274. ("y" . ,(* 60 8 5 40)))
  16275. "Conversion factor to minutes for an effort modifier.
  16276. Each entry has the form (MODIFIER . MINUTES).
  16277. In an effort string, a number followed by MODIFIER is multiplied
  16278. by the specified number of MINUTES to obtain an effort in
  16279. minutes.
  16280. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16281. effort string \"2hours\" is equivalent to 120 minutes."
  16282. :group 'org-agenda
  16283. :version "26.1"
  16284. :package-version '(Org . "8.3")
  16285. :type '(alist :key-type (string :tag "Modifier")
  16286. :value-type (number :tag "Minutes")))
  16287. (defcustom org-image-actual-width t
  16288. "Should we use the actual width of images when inlining them?
  16289. When set to t, always use the image width.
  16290. When set to a number, use imagemagick (when available) to set
  16291. the image's width to this value.
  16292. When set to a number in a list, try to get the width from any
  16293. #+ATTR.* keyword if it matches a width specification like
  16294. #+ATTR_HTML: :width 300px
  16295. and fall back on that number if none is found.
  16296. When set to nil, try to get the width from an #+ATTR.* keyword
  16297. and fall back on the original width if none is found.
  16298. This requires Emacs >= 24.1, build with imagemagick support."
  16299. :group 'org-appearance
  16300. :version "24.4"
  16301. :package-version '(Org . "8.0")
  16302. :type '(choice
  16303. (const :tag "Use the image width" t)
  16304. (integer :tag "Use a number of pixels")
  16305. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16306. (const :tag "Use #+ATTR* or don't resize" nil)))
  16307. (defcustom org-agenda-inhibit-startup nil
  16308. "Inhibit startup when preparing agenda buffers.
  16309. When this variable is t, the initialization of the Org agenda
  16310. buffers is inhibited: e.g. the visibility state is not set, the
  16311. tables are not re-aligned, etc."
  16312. :type 'boolean
  16313. :version "24.3"
  16314. :group 'org-agenda)
  16315. (defcustom org-agenda-ignore-properties nil
  16316. "Avoid updating text properties when building the agenda.
  16317. Properties are used to prepare buffers for effort estimates,
  16318. appointments, statistics and subtree-local categories.
  16319. If you don't use these in the agenda, you can add them to this
  16320. list and agenda building will be a bit faster.
  16321. The value is a list, with zero or more of the symbols `effort', `appt',
  16322. `stats' or `category'."
  16323. :type '(set :greedy t
  16324. (const effort)
  16325. (const appt)
  16326. (const stats)
  16327. (const category))
  16328. :version "26.1"
  16329. :package-version '(Org . "8.3")
  16330. :group 'org-agenda)
  16331. ;;;; Files
  16332. (defun org-save-all-org-buffers ()
  16333. "Save all Org buffers without user confirmation."
  16334. (interactive)
  16335. (message "Saving all Org buffers...")
  16336. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16337. (when (featurep 'org-id) (org-id-locations-save))
  16338. (message "Saving all Org buffers... done"))
  16339. (defun org-revert-all-org-buffers ()
  16340. "Revert all Org buffers.
  16341. Prompt for confirmation when there are unsaved changes.
  16342. Be sure you know what you are doing before letting this function
  16343. overwrite your changes.
  16344. This function is useful in a setup where one tracks org files
  16345. with a version control system, to revert on one machine after pulling
  16346. changes from another. I believe the procedure must be like this:
  16347. 1. M-x org-save-all-org-buffers
  16348. 2. Pull changes from the other machine, resolve conflicts
  16349. 3. M-x org-revert-all-org-buffers"
  16350. (interactive)
  16351. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16352. (user-error "Abort"))
  16353. (save-excursion
  16354. (save-window-excursion
  16355. (dolist (b (buffer-list))
  16356. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16357. (with-current-buffer b buffer-file-name))
  16358. (pop-to-buffer-same-window b)
  16359. (revert-buffer t 'no-confirm)))
  16360. (when (and (featurep 'org-id) org-id-track-globally)
  16361. (org-id-locations-load)))))
  16362. ;;;; Agenda files
  16363. ;;;###autoload
  16364. (defun org-switchb (&optional arg)
  16365. "Switch between Org buffers.
  16366. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16367. With `\\[universal-argument] \\[universal-argument]' \
  16368. prefix, restrict available buffers to agenda files."
  16369. (interactive "P")
  16370. (let ((blist (org-buffer-list
  16371. (cond ((equal arg '(4)) 'files)
  16372. ((equal arg '(16)) 'agenda)))))
  16373. (pop-to-buffer-same-window
  16374. (completing-read "Org buffer: "
  16375. (mapcar #'list (mapcar #'buffer-name blist))
  16376. nil t))))
  16377. (defun org-buffer-list (&optional predicate exclude-tmp)
  16378. "Return a list of Org buffers.
  16379. PREDICATE can be `export', `files' or `agenda'.
  16380. export restrict the list to Export buffers.
  16381. files restrict the list to buffers visiting Org files.
  16382. agenda restrict the list to buffers visiting agenda files.
  16383. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16384. (let* ((bfn nil)
  16385. (agenda-files (and (eq predicate 'agenda)
  16386. (mapcar 'file-truename (org-agenda-files t))))
  16387. (filter
  16388. (cond
  16389. ((eq predicate 'files)
  16390. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16391. ((eq predicate 'export)
  16392. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16393. ((eq predicate 'agenda)
  16394. (lambda (b)
  16395. (with-current-buffer b
  16396. (and (derived-mode-p 'org-mode)
  16397. (setq bfn (buffer-file-name b))
  16398. (member (file-truename bfn) agenda-files)))))
  16399. (t (lambda (b) (with-current-buffer b
  16400. (or (derived-mode-p 'org-mode)
  16401. (string-match "\\*Org .*Export"
  16402. (buffer-name b)))))))))
  16403. (delq nil
  16404. (mapcar
  16405. (lambda(b)
  16406. (if (and (funcall filter b)
  16407. (or (not exclude-tmp)
  16408. (not (string-match "tmp" (buffer-name b)))))
  16409. b
  16410. nil))
  16411. (buffer-list)))))
  16412. (defun org-agenda-files (&optional unrestricted archives)
  16413. "Get the list of agenda files.
  16414. Optional UNRESTRICTED means return the full list even if a restriction
  16415. is currently in place.
  16416. When ARCHIVES is t, include all archive files that are really being
  16417. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16418. `org-agenda-archives-mode' is t."
  16419. (let ((files
  16420. (cond
  16421. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16422. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16423. ((listp org-agenda-files) org-agenda-files)
  16424. (t (error "Invalid value of `org-agenda-files'")))))
  16425. (setq files (apply 'append
  16426. (mapcar (lambda (f)
  16427. (if (file-directory-p f)
  16428. (directory-files
  16429. f t org-agenda-file-regexp)
  16430. (list f)))
  16431. files)))
  16432. (when org-agenda-skip-unavailable-files
  16433. (setq files (delq nil
  16434. (mapcar (function
  16435. (lambda (file)
  16436. (and (file-readable-p file) file)))
  16437. files))))
  16438. (when (or (eq archives t)
  16439. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16440. (setq files (org-add-archive-files files)))
  16441. files))
  16442. (defun org-agenda-file-p (&optional file)
  16443. "Return non-nil, if FILE is an agenda file.
  16444. If FILE is omitted, use the file associated with the current
  16445. buffer."
  16446. (let ((fname (or file (buffer-file-name))))
  16447. (and fname
  16448. (member (file-truename fname)
  16449. (mapcar #'file-truename (org-agenda-files t))))))
  16450. (defun org-edit-agenda-file-list ()
  16451. "Edit the list of agenda files.
  16452. Depending on setup, this either uses customize to edit the variable
  16453. `org-agenda-files', or it visits the file that is holding the list. In the
  16454. latter case, the buffer is set up in a way that saving it automatically kills
  16455. the buffer and restores the previous window configuration."
  16456. (interactive)
  16457. (if (stringp org-agenda-files)
  16458. (let ((cw (current-window-configuration)))
  16459. (find-file org-agenda-files)
  16460. (setq-local org-window-configuration cw)
  16461. (add-hook 'after-save-hook
  16462. (lambda ()
  16463. (set-window-configuration
  16464. (prog1 org-window-configuration
  16465. (kill-buffer (current-buffer))))
  16466. (org-install-agenda-files-menu)
  16467. (message "New agenda file list installed"))
  16468. nil 'local)
  16469. (message "%s" (substitute-command-keys
  16470. "Edit list and finish with \\[save-buffer]")))
  16471. (customize-variable 'org-agenda-files)))
  16472. (defun org-store-new-agenda-file-list (list)
  16473. "Set new value for the agenda file list and save it correctly."
  16474. (if (stringp org-agenda-files)
  16475. (let ((fe (org-read-agenda-file-list t)) b u)
  16476. (while (setq b (find-buffer-visiting org-agenda-files))
  16477. (kill-buffer b))
  16478. (with-temp-file org-agenda-files
  16479. (insert
  16480. (mapconcat
  16481. (lambda (f) ;; Keep un-expanded entries.
  16482. (if (setq u (assoc f fe))
  16483. (cdr u)
  16484. f))
  16485. list "\n")
  16486. "\n")))
  16487. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16488. (org-insert-mode-line-in-empty-file nil))
  16489. (setq org-agenda-files list)
  16490. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16491. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16492. "Read the list of agenda files from a file.
  16493. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16494. filenames, used by `org-store-new-agenda-file-list' to write back
  16495. un-expanded file names."
  16496. (when (file-directory-p org-agenda-files)
  16497. (error "`org-agenda-files' cannot be a single directory"))
  16498. (when (stringp org-agenda-files)
  16499. (with-temp-buffer
  16500. (insert-file-contents org-agenda-files)
  16501. (mapcar
  16502. (lambda (f)
  16503. (let ((e (expand-file-name (substitute-in-file-name f)
  16504. org-directory)))
  16505. (if pair-with-expansion
  16506. (cons e f)
  16507. e)))
  16508. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16509. ;;;###autoload
  16510. (defun org-cycle-agenda-files ()
  16511. "Cycle through the files in `org-agenda-files'.
  16512. If the current buffer visits an agenda file, find the next one in the list.
  16513. If the current buffer does not, find the first agenda file."
  16514. (interactive)
  16515. (let* ((fs (or (org-agenda-files t)
  16516. (user-error "No agenda files")))
  16517. (files (copy-sequence fs))
  16518. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16519. file)
  16520. (when tcf
  16521. (while (and (setq file (pop files))
  16522. (not (equal (file-truename file) tcf)))))
  16523. (find-file (car (or files fs)))
  16524. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16525. (defun org-agenda-file-to-front (&optional to-end)
  16526. "Move/add the current file to the top of the agenda file list.
  16527. If the file is not present in the list, it is added to the front. If it is
  16528. present, it is moved there. With optional argument TO-END, add/move to the
  16529. end of the list."
  16530. (interactive "P")
  16531. (let ((org-agenda-skip-unavailable-files nil)
  16532. (file-alist (mapcar (lambda (x)
  16533. (cons (file-truename x) x))
  16534. (org-agenda-files t)))
  16535. (ctf (file-truename
  16536. (or buffer-file-name
  16537. (user-error "Please save the current buffer to a file"))))
  16538. x had)
  16539. (setq x (assoc ctf file-alist) had x)
  16540. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16541. (if to-end
  16542. (setq file-alist (append (delq x file-alist) (list x)))
  16543. (setq file-alist (cons x (delq x file-alist))))
  16544. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16545. (org-install-agenda-files-menu)
  16546. (message "File %s to %s of agenda file list"
  16547. (if had "moved" "added") (if to-end "end" "front"))))
  16548. (defun org-remove-file (&optional file)
  16549. "Remove current file from the list of files in variable `org-agenda-files'.
  16550. These are the files which are being checked for agenda entries.
  16551. Optional argument FILE means use this file instead of the current."
  16552. (interactive)
  16553. (let* ((org-agenda-skip-unavailable-files nil)
  16554. (file (or file buffer-file-name
  16555. (user-error "Current buffer does not visit a file")))
  16556. (true-file (file-truename file))
  16557. (afile (abbreviate-file-name file))
  16558. (files (delq nil (mapcar
  16559. (lambda (x)
  16560. (unless (equal true-file
  16561. (file-truename x))
  16562. x))
  16563. (org-agenda-files t)))))
  16564. (if (not (= (length files) (length (org-agenda-files t))))
  16565. (progn
  16566. (org-store-new-agenda-file-list files)
  16567. (org-install-agenda-files-menu)
  16568. (message "Removed from Org Agenda list: %s" afile))
  16569. (message "File was not in list: %s (not removed)" afile))))
  16570. (defun org-file-menu-entry (file)
  16571. (vector file (list 'find-file file) t))
  16572. (defun org-check-agenda-file (file)
  16573. "Make sure FILE exists. If not, ask user what to do."
  16574. (unless (file-exists-p file)
  16575. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16576. (abbreviate-file-name file))
  16577. (let ((r (downcase (read-char-exclusive))))
  16578. (cond
  16579. ((equal r ?r)
  16580. (org-remove-file file)
  16581. (throw 'nextfile t))
  16582. (t (user-error "Abort"))))))
  16583. (defun org-get-agenda-file-buffer (file)
  16584. "Get an agenda buffer visiting FILE.
  16585. If the buffer needs to be created, add it to the list of buffers
  16586. which might be released later."
  16587. (let ((buf (org-find-base-buffer-visiting file)))
  16588. (if buf
  16589. buf ; just return it
  16590. ;; Make a new buffer and remember it
  16591. (setq buf (find-file-noselect file))
  16592. (when buf (push buf org-agenda-new-buffers))
  16593. buf)))
  16594. (defun org-release-buffers (blist)
  16595. "Release all buffers in list, asking the user for confirmation when needed.
  16596. When a buffer is unmodified, it is just killed. When modified, it is saved
  16597. \(if the user agrees) and then killed."
  16598. (let (file)
  16599. (dolist (buf blist)
  16600. (setq file (buffer-file-name buf))
  16601. (when (and (buffer-modified-p buf)
  16602. file
  16603. (y-or-n-p (format "Save file %s? " file)))
  16604. (with-current-buffer buf (save-buffer)))
  16605. (kill-buffer buf))))
  16606. (defun org-agenda-prepare-buffers (files)
  16607. "Create buffers for all agenda files, protect archived trees and comments."
  16608. (interactive)
  16609. (let ((pa '(:org-archived t))
  16610. (pc '(:org-comment t))
  16611. (pall '(:org-archived t :org-comment t))
  16612. (inhibit-read-only t)
  16613. (org-inhibit-startup org-agenda-inhibit-startup)
  16614. (rea (concat ":" org-archive-tag ":"))
  16615. re pos)
  16616. (setq org-tag-alist-for-agenda nil
  16617. org-tag-groups-alist-for-agenda nil)
  16618. (save-excursion
  16619. (save-restriction
  16620. (dolist (file files)
  16621. (catch 'nextfile
  16622. (if (bufferp file)
  16623. (set-buffer file)
  16624. (org-check-agenda-file file)
  16625. (set-buffer (org-get-agenda-file-buffer file)))
  16626. (widen)
  16627. (org-set-regexps-and-options 'tags-only)
  16628. (setq pos (point))
  16629. (or (memq 'category org-agenda-ignore-properties)
  16630. (org-refresh-category-properties))
  16631. (or (memq 'stats org-agenda-ignore-properties)
  16632. (org-refresh-stats-properties))
  16633. (or (memq 'effort org-agenda-ignore-properties)
  16634. (org-refresh-effort-properties))
  16635. (or (memq 'appt org-agenda-ignore-properties)
  16636. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16637. (setq org-todo-keywords-for-agenda
  16638. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16639. (setq org-done-keywords-for-agenda
  16640. (append org-done-keywords-for-agenda org-done-keywords))
  16641. (setq org-todo-keyword-alist-for-agenda
  16642. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16643. (setq org-tag-alist-for-agenda
  16644. (org-uniquify
  16645. (append org-tag-alist-for-agenda
  16646. org-current-tag-alist)))
  16647. ;; Merge current file's tag groups into global
  16648. ;; `org-tag-groups-alist-for-agenda'.
  16649. (when org-group-tags
  16650. (dolist (alist org-tag-groups-alist)
  16651. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16652. (if old
  16653. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16654. (push alist org-tag-groups-alist-for-agenda)))))
  16655. (org-with-silent-modifications
  16656. (save-excursion
  16657. (remove-text-properties (point-min) (point-max) pall)
  16658. (when org-agenda-skip-archived-trees
  16659. (goto-char (point-min))
  16660. (while (re-search-forward rea nil t)
  16661. (when (org-at-heading-p t)
  16662. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16663. (goto-char (point-min))
  16664. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16665. (while (re-search-forward re nil t)
  16666. (when (save-match-data (org-in-commented-heading-p t))
  16667. (add-text-properties
  16668. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16669. (goto-char pos)))))
  16670. (setq org-todo-keywords-for-agenda
  16671. (org-uniquify org-todo-keywords-for-agenda))
  16672. (setq org-todo-keyword-alist-for-agenda
  16673. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16674. ;;;; CDLaTeX minor mode
  16675. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16676. "Keymap for the minor `org-cdlatex-mode'.")
  16677. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16678. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16679. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16680. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16681. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16682. (defvar org-cdlatex-texmathp-advice-is-done nil
  16683. "Flag remembering if we have applied the advice to texmathp already.")
  16684. (define-minor-mode org-cdlatex-mode
  16685. "Toggle the minor `org-cdlatex-mode'.
  16686. This mode supports entering LaTeX environment and math in LaTeX fragments
  16687. in Org mode.
  16688. \\{org-cdlatex-mode-map}"
  16689. nil " OCDL" nil
  16690. (when org-cdlatex-mode
  16691. (require 'cdlatex)
  16692. (run-hooks 'cdlatex-mode-hook)
  16693. (cdlatex-compute-tables))
  16694. (unless org-cdlatex-texmathp-advice-is-done
  16695. (setq org-cdlatex-texmathp-advice-is-done t)
  16696. (defadvice texmathp (around org-math-always-on activate)
  16697. "Always return t in Org buffers.
  16698. This is because we want to insert math symbols without dollars even outside
  16699. the LaTeX math segments. If Org mode thinks that point is actually inside
  16700. an embedded LaTeX fragment, let `texmathp' do its job.
  16701. `\\[org-cdlatex-mode-map]'"
  16702. (interactive)
  16703. (let (p)
  16704. (cond
  16705. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16706. ((eq this-command 'cdlatex-math-symbol)
  16707. (setq ad-return-value t
  16708. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16709. (t
  16710. (let ((p (org-inside-LaTeX-fragment-p)))
  16711. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16712. (setq ad-return-value t
  16713. texmathp-why '("Org mode embedded math" . 0))
  16714. (when p ad-do-it)))))))))
  16715. (defun turn-on-org-cdlatex ()
  16716. "Unconditionally turn on `org-cdlatex-mode'."
  16717. (org-cdlatex-mode 1))
  16718. (defun org-try-cdlatex-tab ()
  16719. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16720. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16721. - inside a LaTeX fragment, or
  16722. - after the first word in a line, where an abbreviation expansion could
  16723. insert a LaTeX environment."
  16724. (when org-cdlatex-mode
  16725. (cond
  16726. ;; Before any word on the line: No expansion possible.
  16727. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16728. ;; Just after first word on the line: Expand it. Make sure it
  16729. ;; cannot happen on headlines, though.
  16730. ((save-excursion
  16731. (skip-chars-backward "a-zA-Z0-9*")
  16732. (skip-chars-backward " \t")
  16733. (and (bolp) (not (org-at-heading-p))))
  16734. (cdlatex-tab) t)
  16735. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16736. (defun org-cdlatex-underscore-caret (&optional _arg)
  16737. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16738. Revert to the normal definition outside of these fragments."
  16739. (interactive "P")
  16740. (if (org-inside-LaTeX-fragment-p)
  16741. (call-interactively 'cdlatex-sub-superscript)
  16742. (let (org-cdlatex-mode)
  16743. (call-interactively (key-binding (vector last-input-event))))))
  16744. (defun org-cdlatex-math-modify (&optional _arg)
  16745. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16746. Revert to the normal definition outside of these fragments."
  16747. (interactive "P")
  16748. (if (org-inside-LaTeX-fragment-p)
  16749. (call-interactively 'cdlatex-math-modify)
  16750. (let (org-cdlatex-mode)
  16751. (call-interactively (key-binding (vector last-input-event))))))
  16752. (defun org-cdlatex-environment-indent (&optional environment item)
  16753. "Execute `cdlatex-environment' and indent the inserted environment.
  16754. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16755. The inserted environment is indented to current indentation
  16756. unless point is at the beginning of the line, in which the
  16757. environment remains unintended."
  16758. (interactive)
  16759. ;; cdlatex-environment always return nil. Therefore, capture output
  16760. ;; first and determine if an environment was selected.
  16761. (let* ((beg (point-marker))
  16762. (end (copy-marker (point) t))
  16763. (inserted (progn
  16764. (ignore-errors (cdlatex-environment environment item))
  16765. (< beg end)))
  16766. ;; Figure out how many lines to move forward after the
  16767. ;; environment has been inserted.
  16768. (lines (when inserted
  16769. (save-excursion
  16770. (- (cl-loop while (< beg (point))
  16771. with x = 0
  16772. do (forward-line -1)
  16773. (cl-incf x)
  16774. finally return x)
  16775. (if (progn (goto-char beg)
  16776. (and (progn (skip-chars-forward " \t") (eolp))
  16777. (progn (skip-chars-backward " \t") (bolp))))
  16778. 1 0)))))
  16779. (env (org-trim (delete-and-extract-region beg end))))
  16780. (when inserted
  16781. ;; Get indentation of next line unless at column 0.
  16782. (let ((ind (if (bolp) 0
  16783. (save-excursion
  16784. (org-return-indent)
  16785. (prog1 (org-get-indentation)
  16786. (when (progn (skip-chars-forward " \t") (eolp))
  16787. (delete-region beg (point)))))))
  16788. (bol (progn (skip-chars-backward " \t") (bolp))))
  16789. ;; Insert a newline before environment unless at column zero
  16790. ;; to "escape" the current line. Insert a newline if
  16791. ;; something is one the same line as \end{ENVIRONMENT}.
  16792. (insert
  16793. (concat (unless bol "\n") env
  16794. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16795. (unless (zerop ind)
  16796. (save-excursion
  16797. (goto-char beg)
  16798. (while (< (point) end)
  16799. (unless (eolp) (indent-line-to ind))
  16800. (forward-line))))
  16801. (goto-char beg)
  16802. (forward-line lines)
  16803. (indent-line-to ind)))
  16804. (set-marker beg nil)
  16805. (set-marker end nil)))
  16806. ;;;; LaTeX fragments
  16807. (defun org-inside-LaTeX-fragment-p ()
  16808. "Test if point is inside a LaTeX fragment.
  16809. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16810. sequence appearing also before point.
  16811. Even though the matchers for math are configurable, this function assumes
  16812. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16813. delimiters are skipped when they have been removed by customization.
  16814. The return value is nil, or a cons cell with the delimiter and the
  16815. position of this delimiter.
  16816. This function does a reasonably good job, but can locally be fooled by
  16817. for example currency specifications. For example it will assume being in
  16818. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16819. fragments that are properly closed, but during editing, we have to live
  16820. with the uncertainty caused by missing closing delimiters. This function
  16821. looks only before point, not after."
  16822. (catch 'exit
  16823. (let ((pos (point))
  16824. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16825. (lim (save-excursion (org-backward-paragraph) (point)))
  16826. dd-on str (start 0) m re)
  16827. (goto-char pos)
  16828. (when dodollar
  16829. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16830. re (nth 1 (assoc "$" org-latex-regexps)))
  16831. (while (string-match re str start)
  16832. (cond
  16833. ((= (match-end 0) (length str))
  16834. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16835. ((= (match-end 0) (- (length str) 5))
  16836. (throw 'exit nil))
  16837. (t (setq start (match-end 0))))))
  16838. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16839. (goto-char pos)
  16840. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16841. (and (match-beginning 2) (throw 'exit nil))
  16842. ;; count $$
  16843. (while (re-search-backward "\\$\\$" lim t)
  16844. (setq dd-on (not dd-on)))
  16845. (goto-char pos)
  16846. (when dd-on (cons "$$" m))))))
  16847. (defun org-inside-latex-macro-p ()
  16848. "Is point inside a LaTeX macro or its arguments?"
  16849. (save-match-data
  16850. (org-in-regexp
  16851. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16852. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16853. "Build an overlay between BEG and END using IMAGE file.
  16854. Argument IMAGETYPE is the extension of the displayed image,
  16855. as a string. It defaults to \"png\"."
  16856. (let ((ov (make-overlay beg end))
  16857. (imagetype (or (intern imagetype) 'png)))
  16858. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16859. (overlay-put ov 'evaporate t)
  16860. (overlay-put ov
  16861. 'modification-hooks
  16862. (list (lambda (o _flag _beg _end &optional _l)
  16863. (delete-overlay o))))
  16864. (overlay-put ov
  16865. 'display
  16866. (list 'image :type imagetype :file image :ascent 'center))))
  16867. (defun org--list-latex-overlays (&optional beg end)
  16868. "List all Org LaTeX overlays in current buffer.
  16869. Limit to overlays between BEG and END when those are provided."
  16870. (cl-remove-if-not
  16871. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16872. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16873. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16874. "Remove all overlays with LaTeX fragment images in current buffer.
  16875. When optional arguments BEG and END are non-nil, remove all
  16876. overlays between them instead. Return a non-nil value when some
  16877. overlays were removed, nil otherwise."
  16878. (let ((overlays (org--list-latex-overlays beg end)))
  16879. (mapc #'delete-overlay overlays)
  16880. overlays))
  16881. (defun org-toggle-latex-fragment (&optional arg)
  16882. "Preview the LaTeX fragment at point, or all locally or globally.
  16883. If the cursor is on a LaTeX fragment, create the image and overlay
  16884. it over the source code, if there is none. Remove it otherwise.
  16885. If there is no fragment at point, display all fragments in the
  16886. current section.
  16887. With prefix ARG, preview or clear image for all fragments in the
  16888. current subtree or in the whole buffer when used before the first
  16889. headline. With a prefix ARG `\\[universal-argument] \
  16890. \\[universal-argument]' preview or clear images
  16891. for all fragments in the buffer."
  16892. (interactive "P")
  16893. (when (display-graphic-p)
  16894. (catch 'exit
  16895. (save-excursion
  16896. (let (beg end msg)
  16897. (cond
  16898. ((or (equal arg '(16))
  16899. (and (equal arg '(4))
  16900. (org-with-limited-levels (org-before-first-heading-p))))
  16901. (if (org-remove-latex-fragment-image-overlays)
  16902. (progn (message "LaTeX fragments images removed from buffer")
  16903. (throw 'exit nil))
  16904. (setq msg "Creating images for buffer...")))
  16905. ((equal arg '(4))
  16906. (org-with-limited-levels (org-back-to-heading t))
  16907. (setq beg (point))
  16908. (setq end (progn (org-end-of-subtree t) (point)))
  16909. (if (org-remove-latex-fragment-image-overlays beg end)
  16910. (progn
  16911. (message "LaTeX fragment images removed from subtree")
  16912. (throw 'exit nil))
  16913. (setq msg "Creating images for subtree...")))
  16914. ((let ((datum (org-element-context)))
  16915. (when (memq (org-element-type datum)
  16916. '(latex-environment latex-fragment))
  16917. (setq beg (org-element-property :begin datum))
  16918. (setq end (org-element-property :end datum))
  16919. (if (org-remove-latex-fragment-image-overlays beg end)
  16920. (progn (message "LaTeX fragment image removed")
  16921. (throw 'exit nil))
  16922. (setq msg "Creating image...")))))
  16923. (t
  16924. (org-with-limited-levels
  16925. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16926. (outline-previous-heading)
  16927. (point)))
  16928. (setq end (progn (outline-next-heading) (point)))
  16929. (if (org-remove-latex-fragment-image-overlays beg end)
  16930. (progn
  16931. (message "LaTeX fragment images removed from section")
  16932. (throw 'exit nil))
  16933. (setq msg "Creating images for section...")))))
  16934. (let ((file (buffer-file-name (buffer-base-buffer))))
  16935. (org-format-latex
  16936. (concat org-preview-latex-image-directory "org-ltximg")
  16937. beg end
  16938. ;; Emacs cannot overlay images from remote hosts. Create
  16939. ;; it in `temporary-file-directory' instead.
  16940. (if (or (not file) (file-remote-p file))
  16941. temporary-file-directory
  16942. default-directory)
  16943. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16944. (message (concat msg "done")))))))
  16945. (defun org-format-latex
  16946. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16947. "Replace LaTeX fragments with links to an image.
  16948. The function takes care of creating the replacement image.
  16949. Only consider fragments between BEG and END when those are
  16950. provided.
  16951. When optional argument OVERLAYS is non-nil, display the image on
  16952. top of the fragment instead of replacing it.
  16953. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16954. Some of the options can be changed using the variable
  16955. `org-format-latex-options', which see."
  16956. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16957. (unless (eq processing-type 'verbatim)
  16958. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16959. (cnt 0)
  16960. checkdir-flag)
  16961. (goto-char (or beg (point-min)))
  16962. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16963. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16964. (overlay-recenter (or end (point-max))))
  16965. (while (re-search-forward math-regexp end t)
  16966. (unless (and overlays
  16967. (eq (get-char-property (point) 'org-overlay-type)
  16968. 'org-latex-overlay))
  16969. (let* ((context (org-element-context))
  16970. (type (org-element-type context)))
  16971. (when (memq type '(latex-environment latex-fragment))
  16972. (let ((block-type (eq type 'latex-environment))
  16973. (value (org-element-property :value context))
  16974. (beg (org-element-property :begin context))
  16975. (end (save-excursion
  16976. (goto-char (org-element-property :end context))
  16977. (skip-chars-backward " \r\t\n")
  16978. (point))))
  16979. (cond
  16980. ((eq processing-type 'mathjax)
  16981. ;; Prepare for MathJax processing.
  16982. (if (not (string-match "\\`\\$\\$?" value))
  16983. (goto-char end)
  16984. (delete-region beg end)
  16985. (if (string= (match-string 0 value) "$$")
  16986. (insert "\\[" (substring value 2 -2) "\\]")
  16987. (insert "\\(" (substring value 1 -1) "\\)"))))
  16988. ((assq processing-type org-preview-latex-process-alist)
  16989. ;; Process to an image.
  16990. (cl-incf cnt)
  16991. (goto-char beg)
  16992. (let* ((processing-info
  16993. (cdr (assq processing-type org-preview-latex-process-alist)))
  16994. (face (face-at-point))
  16995. ;; Get the colors from the face at point.
  16996. (fg
  16997. (let ((color (plist-get org-format-latex-options
  16998. :foreground)))
  16999. (if (and forbuffer (eq color 'auto))
  17000. (face-attribute face :foreground nil 'default)
  17001. color)))
  17002. (bg
  17003. (let ((color (plist-get org-format-latex-options
  17004. :background)))
  17005. (if (and forbuffer (eq color 'auto))
  17006. (face-attribute face :background nil 'default)
  17007. color)))
  17008. (hash (sha1 (prin1-to-string
  17009. (list org-format-latex-header
  17010. org-latex-default-packages-alist
  17011. org-latex-packages-alist
  17012. org-format-latex-options
  17013. forbuffer value fg bg))))
  17014. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17015. (absprefix (expand-file-name prefix dir))
  17016. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17017. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17018. (sep (and block-type "\n\n"))
  17019. (link (concat sep "[[file:" linkfile "]]" sep))
  17020. (options
  17021. (org-combine-plists
  17022. org-format-latex-options
  17023. `(:foreground ,fg :background ,bg))))
  17024. (when msg (message msg cnt))
  17025. (unless checkdir-flag ; Ensure the directory exists.
  17026. (setq checkdir-flag t)
  17027. (let ((todir (file-name-directory absprefix)))
  17028. (unless (file-directory-p todir)
  17029. (make-directory todir t))))
  17030. (unless (file-exists-p movefile)
  17031. (org-create-formula-image
  17032. value movefile options forbuffer processing-type))
  17033. (if overlays
  17034. (progn
  17035. (dolist (o (overlays-in beg end))
  17036. (when (eq (overlay-get o 'org-overlay-type)
  17037. 'org-latex-overlay)
  17038. (delete-overlay o)))
  17039. (org--format-latex-make-overlay beg end movefile imagetype)
  17040. (goto-char end))
  17041. (delete-region beg end)
  17042. (insert
  17043. (org-add-props link
  17044. (list 'org-latex-src
  17045. (replace-regexp-in-string "\"" "" value)
  17046. 'org-latex-src-embed-type
  17047. (if block-type 'paragraph 'character)))))))
  17048. ((eq processing-type 'mathml)
  17049. ;; Process to MathML.
  17050. (unless (org-format-latex-mathml-available-p)
  17051. (user-error "LaTeX to MathML converter not configured"))
  17052. (cl-incf cnt)
  17053. (when msg (message msg cnt))
  17054. (goto-char beg)
  17055. (delete-region beg end)
  17056. (insert (org-format-latex-as-mathml
  17057. value block-type prefix dir)))
  17058. (t
  17059. (error "Unknown conversion process %s for LaTeX fragments"
  17060. processing-type)))))))))))
  17061. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17062. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17063. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17064. sucessful, return the portion between \"<math...> </math>\"
  17065. elements otherwise return nil. When MATHML-FILE is specified,
  17066. write the results in to that file. When invoked as an
  17067. interactive command, prompt for LATEX-FRAG, with initial value
  17068. set to the current active region and echo the results for user
  17069. inspection."
  17070. (interactive (list (let ((frag (when (org-region-active-p)
  17071. (buffer-substring-no-properties
  17072. (region-beginning) (region-end)))))
  17073. (read-string "LaTeX Fragment: " frag nil frag))))
  17074. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17075. (let* ((tmp-in-file
  17076. (let ((file (file-relative-name
  17077. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17078. (write-region latex-frag nil file)
  17079. file))
  17080. (tmp-out-file (file-relative-name
  17081. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17082. (cmd (format-spec
  17083. org-latex-to-mathml-convert-command
  17084. `((?j . ,(and org-latex-to-mathml-jar-file
  17085. (shell-quote-argument
  17086. (expand-file-name
  17087. org-latex-to-mathml-jar-file))))
  17088. (?I . ,(shell-quote-argument tmp-in-file))
  17089. (?i . ,latex-frag)
  17090. (?o . ,(shell-quote-argument tmp-out-file)))))
  17091. mathml shell-command-output)
  17092. (when (called-interactively-p 'any)
  17093. (unless (org-format-latex-mathml-available-p)
  17094. (user-error "LaTeX to MathML converter not configured")))
  17095. (message "Running %s" cmd)
  17096. (setq shell-command-output (shell-command-to-string cmd))
  17097. (setq mathml
  17098. (when (file-readable-p tmp-out-file)
  17099. (with-current-buffer (find-file-noselect tmp-out-file t)
  17100. (goto-char (point-min))
  17101. (when (re-search-forward
  17102. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17103. (regexp-quote
  17104. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17105. nil t)
  17106. (prog1 (match-string 0) (kill-buffer))))))
  17107. (cond
  17108. (mathml
  17109. (setq mathml
  17110. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17111. (when mathml-file
  17112. (write-region mathml nil mathml-file))
  17113. (when (called-interactively-p 'any)
  17114. (message mathml)))
  17115. ((message "LaTeX to MathML conversion failed")
  17116. (message shell-command-output)))
  17117. (delete-file tmp-in-file)
  17118. (when (file-exists-p tmp-out-file)
  17119. (delete-file tmp-out-file))
  17120. mathml))
  17121. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17122. prefix &optional dir)
  17123. "Use `org-create-math-formula' but check local cache first."
  17124. (let* ((absprefix (expand-file-name prefix dir))
  17125. (print-length nil) (print-level nil)
  17126. (formula-id (concat
  17127. "formula-"
  17128. (sha1
  17129. (prin1-to-string
  17130. (list latex-frag
  17131. org-latex-to-mathml-convert-command)))))
  17132. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17133. (formula-cache-dir (file-name-directory formula-cache)))
  17134. (unless (file-directory-p formula-cache-dir)
  17135. (make-directory formula-cache-dir t))
  17136. (unless (file-exists-p formula-cache)
  17137. (org-create-math-formula latex-frag formula-cache))
  17138. (if (file-exists-p formula-cache)
  17139. ;; Successful conversion. Return the link to MathML file.
  17140. (org-add-props
  17141. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17142. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17143. 'org-latex-src-embed-type (if latex-frag-type
  17144. 'paragraph 'character)))
  17145. ;; Failed conversion. Return the LaTeX fragment verbatim
  17146. latex-frag)))
  17147. (defun org--get-display-dpi ()
  17148. "Get the DPI of the display.
  17149. The function assumes that the display has the same pixel width in
  17150. the horizontal and vertical directions."
  17151. (if (display-graphic-p)
  17152. (round (/ (display-pixel-height)
  17153. (/ (display-mm-height) 25.4)))
  17154. (error "Attempt to calculate the dpi of a non-graphic display")))
  17155. (defun org-create-formula-image
  17156. (string tofile options buffer &optional processing-type)
  17157. "Create an image from LaTeX source using external processes.
  17158. The LaTeX STRING is saved to a temporary LaTeX file, then
  17159. converted to an image file by process PROCESSING-TYPE defined in
  17160. `org-preview-latex-process-alist'. A nil value defaults to
  17161. `org-preview-latex-default-process'.
  17162. The generated image file is eventually moved to TOFILE.
  17163. The OPTIONS argument controls the size, foreground color and
  17164. background color of the generated image.
  17165. When BUFFER non-nil, this function is used for LaTeX previewing.
  17166. Otherwise, it is used to deal with LaTeX snippets showed in
  17167. a HTML file."
  17168. (let* ((processing-type (or processing-type
  17169. org-preview-latex-default-process))
  17170. (processing-info
  17171. (cdr (assq processing-type org-preview-latex-process-alist)))
  17172. (programs (plist-get processing-info :programs))
  17173. (error-message (or (plist-get processing-info :message) ""))
  17174. (use-xcolor (plist-get processing-info :use-xcolor))
  17175. (image-input-type (plist-get processing-info :image-input-type))
  17176. (image-output-type (plist-get processing-info :image-output-type))
  17177. (post-clean (or (plist-get processing-info :post-clean)
  17178. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17179. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17180. (latex-header
  17181. (or (plist-get processing-info :latex-header)
  17182. (org-latex-make-preamble
  17183. (org-export-get-environment (org-export-get-backend 'latex))
  17184. org-format-latex-header
  17185. 'snippet)))
  17186. (latex-compiler (plist-get processing-info :latex-compiler))
  17187. (image-converter (plist-get processing-info :image-converter))
  17188. (tmpdir temporary-file-directory)
  17189. (texfilebase (make-temp-name
  17190. (expand-file-name "orgtex" tmpdir)))
  17191. (texfile (concat texfilebase ".tex"))
  17192. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17193. '(1.0 . 1.0)))
  17194. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17195. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17196. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17197. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17198. "Black"))
  17199. (bg (or (plist-get options (if buffer :background :html-background))
  17200. "Transparent"))
  17201. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17202. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17203. (dolist (program programs)
  17204. (org-check-external-command program error-message))
  17205. (if use-xcolor
  17206. (progn (if (eq fg 'default)
  17207. (setq fg (org-latex-color :foreground))
  17208. (setq fg (org-latex-color-format fg)))
  17209. (if (eq bg 'default)
  17210. (setq bg (org-latex-color :background))
  17211. (setq bg (org-latex-color-format
  17212. (if (string= bg "Transparent") "white" bg))))
  17213. (with-temp-file texfile
  17214. (insert latex-header)
  17215. (insert "\n\\begin{document}\n"
  17216. "\\definecolor{fg}{rgb}{" fg "}\n"
  17217. "\\definecolor{bg}{rgb}{" bg "}\n"
  17218. "\n\\pagecolor{bg}\n"
  17219. "\n{\\color{fg}\n"
  17220. string
  17221. "\n}\n"
  17222. "\n\\end{document}\n")))
  17223. (if (eq fg 'default)
  17224. (setq fg (org-dvipng-color :foreground))
  17225. (unless (string= fg "Transparent")
  17226. (setq fg (org-dvipng-color-format fg))))
  17227. (if (eq bg 'default)
  17228. (setq bg (org-dvipng-color :background))
  17229. (unless (string= bg "Transparent")
  17230. (setq bg (org-dvipng-color-format bg))))
  17231. (with-temp-file texfile
  17232. (insert latex-header)
  17233. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17234. (let* ((err-msg (format "Please adjust `%s' part of \
  17235. `org-preview-latex-process-alist'."
  17236. processing-type))
  17237. (image-input-file
  17238. (org-compile-file
  17239. texfile latex-compiler image-input-type err-msg log-buf))
  17240. (image-output-file
  17241. (org-compile-file
  17242. image-input-file image-converter image-output-type err-msg log-buf
  17243. `((?F . ,(shell-quote-argument fg))
  17244. (?B . ,(shell-quote-argument bg))
  17245. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17246. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17247. (copy-file image-output-file tofile 'replace)
  17248. (dolist (e post-clean)
  17249. (when (file-exists-p (concat texfilebase e))
  17250. (delete-file (concat texfilebase e))))
  17251. image-output-file)))
  17252. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17253. "Fill a LaTeX header template TPL.
  17254. In the template, the following place holders will be recognized:
  17255. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17256. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17257. [PACKAGES] \\usepackage statements for PKG
  17258. [NO-PACKAGES] do not include PKG
  17259. [EXTRA] the string EXTRA
  17260. [NO-EXTRA] do not include EXTRA
  17261. For backward compatibility, if both the positive and the negative place
  17262. holder is missing, the positive one (without the \"NO-\") will be
  17263. assumed to be present at the end of the template.
  17264. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17265. EXTRA is a string.
  17266. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17267. (let (rpl (end ""))
  17268. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17269. (setq rpl (if (or (match-end 1) (not def-pkg))
  17270. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17271. tpl (replace-match rpl t t tpl))
  17272. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17273. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17274. (setq rpl (if (or (match-end 1) (not pkg))
  17275. "" (org-latex-packages-to-string pkg snippets-p t))
  17276. tpl (replace-match rpl t t tpl))
  17277. (when pkg (setq end
  17278. (concat end "\n"
  17279. (org-latex-packages-to-string pkg snippets-p)))))
  17280. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17281. (setq rpl (if (or (match-end 1) (not extra))
  17282. "" (concat extra "\n"))
  17283. tpl (replace-match rpl t t tpl))
  17284. (when (and extra (string-match "\\S-" extra))
  17285. (setq end (concat end "\n" extra))))
  17286. (if (string-match "\\S-" end)
  17287. (concat tpl "\n" end)
  17288. tpl)))
  17289. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17290. "Turn an alist of packages into a string with the \\usepackage macros."
  17291. (setq pkg (mapconcat (lambda(p)
  17292. (cond
  17293. ((stringp p) p)
  17294. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17295. (format "%% Package %s omitted" (cadr p)))
  17296. ((equal "" (car p))
  17297. (format "\\usepackage{%s}" (cadr p)))
  17298. (t
  17299. (format "\\usepackage[%s]{%s}"
  17300. (car p) (cadr p)))))
  17301. pkg
  17302. "\n"))
  17303. (if newline (concat pkg "\n") pkg))
  17304. (defun org-dvipng-color (attr)
  17305. "Return a RGB color specification for dvipng."
  17306. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17307. (defun org-dvipng-color-format (color-name)
  17308. "Convert COLOR-NAME to a RGB color value for dvipng."
  17309. (apply #'format "rgb %s %s %s"
  17310. (mapcar 'org-normalize-color
  17311. (color-values color-name))))
  17312. (defun org-latex-color (attr)
  17313. "Return a RGB color for the LaTeX color package."
  17314. (org-latex-color-format (face-attribute 'default attr nil)))
  17315. (defun org-latex-color-format (color-name)
  17316. "Convert COLOR-NAME to a RGB color value."
  17317. (apply #'format "%s,%s,%s"
  17318. (mapcar 'org-normalize-color
  17319. (color-values color-name))))
  17320. (defun org-normalize-color (value)
  17321. "Return string to be used as color value for an RGB component."
  17322. (format "%g" (/ value 65535.0)))
  17323. ;; Image display
  17324. (defvar-local org-inline-image-overlays nil)
  17325. (defun org-toggle-inline-images (&optional include-linked)
  17326. "Toggle the display of inline images.
  17327. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17328. (interactive "P")
  17329. (if org-inline-image-overlays
  17330. (progn
  17331. (org-remove-inline-images)
  17332. (when (called-interactively-p 'interactive)
  17333. (message "Inline image display turned off")))
  17334. (org-display-inline-images include-linked)
  17335. (when (called-interactively-p 'interactive)
  17336. (message (if org-inline-image-overlays
  17337. (format "%d images displayed inline"
  17338. (length org-inline-image-overlays))
  17339. "No images to display inline")))))
  17340. (defun org-redisplay-inline-images ()
  17341. "Refresh the display of inline images."
  17342. (interactive)
  17343. (if (not org-inline-image-overlays)
  17344. (org-toggle-inline-images)
  17345. (org-toggle-inline-images)
  17346. (org-toggle-inline-images)))
  17347. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17348. "Display inline images.
  17349. An inline image is a link which follows either of these
  17350. conventions:
  17351. 1. Its path is a file with an extension matching return value
  17352. from `image-file-name-regexp' and it has no contents.
  17353. 2. Its description consists in a single link of the previous
  17354. type.
  17355. When optional argument INCLUDE-LINKED is non-nil, also links with
  17356. a text description part will be inlined. This can be nice for
  17357. a quick look at those images, but it does not reflect what
  17358. exported files will look like.
  17359. When optional argument REFRESH is non-nil, refresh existing
  17360. images between BEG and END. This will create new image displays
  17361. only if necessary. BEG and END default to the buffer
  17362. boundaries."
  17363. (interactive "P")
  17364. (when (display-graphic-p)
  17365. (unless refresh
  17366. (org-remove-inline-images)
  17367. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17368. (org-with-wide-buffer
  17369. (goto-char (or beg (point-min)))
  17370. (let* ((case-fold-search t)
  17371. (file-extension-re (image-file-name-regexp))
  17372. (link-abbrevs (mapcar #'car
  17373. (append org-link-abbrev-alist-local
  17374. org-link-abbrev-alist)))
  17375. ;; Check absolute, relative file names and explicit
  17376. ;; "file:" links. Also check link abbreviations since
  17377. ;; some might expand to "file" links.
  17378. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17379. (if (not link-abbrevs) ""
  17380. (format "\\|\\(?:%s:\\)"
  17381. (regexp-opt link-abbrevs))))))
  17382. (while (re-search-forward file-types-re end t)
  17383. (let ((link (save-match-data (org-element-context))))
  17384. ;; Check if we're at an inline image, i.e., an image file
  17385. ;; link without a description (unless INCLUDE-LINKED is
  17386. ;; non-nil).
  17387. (when (and (equal "file" (org-element-property :type link))
  17388. (or include-linked
  17389. (null (org-element-contents link)))
  17390. (string-match-p file-extension-re
  17391. (org-element-property :path link)))
  17392. (let ((file (expand-file-name
  17393. (org-link-unescape
  17394. (org-element-property :path link)))))
  17395. (when (file-exists-p file)
  17396. (let ((width
  17397. ;; Apply `org-image-actual-width' specifications.
  17398. (cond
  17399. ((not (image-type-available-p 'imagemagick)) nil)
  17400. ((eq org-image-actual-width t) nil)
  17401. ((listp org-image-actual-width)
  17402. (or
  17403. ;; First try to find a width among
  17404. ;; attributes associated to the paragraph
  17405. ;; containing link.
  17406. (let ((paragraph
  17407. (let ((e link))
  17408. (while (and (setq e (org-element-property
  17409. :parent e))
  17410. (not (eq (org-element-type e)
  17411. 'paragraph))))
  17412. e)))
  17413. (when paragraph
  17414. (save-excursion
  17415. (goto-char (org-element-property :begin paragraph))
  17416. (when
  17417. (re-search-forward
  17418. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17419. (org-element-property
  17420. :post-affiliated paragraph)
  17421. t)
  17422. (string-to-number (match-string 1))))))
  17423. ;; Otherwise, fall-back to provided number.
  17424. (car org-image-actual-width)))
  17425. ((numberp org-image-actual-width)
  17426. org-image-actual-width)))
  17427. (old (get-char-property-and-overlay
  17428. (org-element-property :begin link)
  17429. 'org-image-overlay)))
  17430. (if (and (car-safe old) refresh)
  17431. (image-refresh (overlay-get (cdr old) 'display))
  17432. (let ((image (create-image file
  17433. (and width 'imagemagick)
  17434. nil
  17435. :width width)))
  17436. (when image
  17437. (let ((ov (make-overlay
  17438. (org-element-property :begin link)
  17439. (progn
  17440. (goto-char
  17441. (org-element-property :end link))
  17442. (skip-chars-backward " \t")
  17443. (point)))))
  17444. (overlay-put ov 'display image)
  17445. (overlay-put ov 'face 'default)
  17446. (overlay-put ov 'org-image-overlay t)
  17447. (overlay-put
  17448. ov 'modification-hooks
  17449. (list 'org-display-inline-remove-overlay))
  17450. (push ov org-inline-image-overlays)))))))))))))))
  17451. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17452. "Remove inline-display overlay if a corresponding region is modified."
  17453. (let ((inhibit-modification-hooks t))
  17454. (when (and ov after)
  17455. (delete ov org-inline-image-overlays)
  17456. (delete-overlay ov))))
  17457. (defun org-remove-inline-images ()
  17458. "Remove inline display of images."
  17459. (interactive)
  17460. (mapc #'delete-overlay org-inline-image-overlays)
  17461. (setq org-inline-image-overlays nil))
  17462. ;;;; Key bindings
  17463. (defun org-remap (map &rest commands)
  17464. "In MAP, remap the functions given in COMMANDS.
  17465. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17466. (let (new old)
  17467. (while commands
  17468. (setq old (pop commands) new (pop commands))
  17469. (org-defkey map (vector 'remap old) new))))
  17470. ;; Outline functions from `outline-mode-prefix-map'
  17471. ;; that can be remapped in Org:
  17472. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17473. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17474. (define-key org-mode-map [remap outline-forward-same-level]
  17475. 'org-forward-heading-same-level)
  17476. (define-key org-mode-map [remap outline-backward-same-level]
  17477. 'org-backward-heading-same-level)
  17478. (define-key org-mode-map [remap outline-show-branches]
  17479. 'org-kill-note-or-show-branches)
  17480. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17481. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17482. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17483. (define-key org-mode-map [remap outline-next-visible-heading]
  17484. 'org-next-visible-heading)
  17485. (define-key org-mode-map [remap outline-previous-visible-heading]
  17486. 'org-previous-visible-heading)
  17487. (define-key org-mode-map [remap show-children] 'org-show-children)
  17488. ;; Outline functions from `outline-mode-prefix-map' that can not
  17489. ;; be remapped in Org:
  17490. ;; - the column "key binding" shows whether the Outline function is still
  17491. ;; available in Org mode on the same key that it has been bound to in
  17492. ;; Outline mode:
  17493. ;; - "overridden": key used for a different functionality in Org mode
  17494. ;; - else: key still bound to the same Outline function in Org mode
  17495. ;; | Outline function | key binding | Org replacement |
  17496. ;; |------------------------------------+-------------+--------------------------|
  17497. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17498. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17499. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17500. ;; | `show-entry' | overridden | no replacement |
  17501. ;; | `show-branches' | `C-c C-k' | still same function |
  17502. ;; | `show-subtree' | overridden | visibility cycling |
  17503. ;; | `show-all' | overridden | no replacement |
  17504. ;; | `hide-subtree' | overridden | visibility cycling |
  17505. ;; | `hide-body' | overridden | no replacement |
  17506. ;; | `hide-entry' | overridden | visibility cycling |
  17507. ;; | `hide-leaves' | overridden | no replacement |
  17508. ;; | `hide-sublevels' | overridden | no replacement |
  17509. ;; | `hide-other' | overridden | no replacement |
  17510. ;; Make `C-c C-x' a prefix key
  17511. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17512. ;; TAB key with modifiers
  17513. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17514. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17515. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17516. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17517. ;; The following line is necessary under Suse GNU/Linux
  17518. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17519. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17520. (define-key org-mode-map [backtab] 'org-shifttab)
  17521. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17522. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17523. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17524. ;; Cursor keys with modifiers
  17525. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17526. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17527. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17528. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17529. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17530. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17531. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17532. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17533. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17534. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17535. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17536. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17537. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17538. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17539. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17540. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17541. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17542. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17543. ;; Babel keys
  17544. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17545. (dolist (pair org-babel-key-bindings)
  17546. (define-key org-babel-map (car pair) (cdr pair)))
  17547. ;;; Extra keys for tty access.
  17548. ;; We only set them when really needed because otherwise the
  17549. ;; menus don't show the simple keys
  17550. (when (or org-use-extra-keys (not window-system))
  17551. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17552. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17553. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17554. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17555. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17556. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17557. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17558. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17559. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17560. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17561. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17562. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17563. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17564. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17565. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17566. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17567. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17568. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17569. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17570. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17571. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17572. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17573. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17574. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17575. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17576. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17577. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17578. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17579. ;; All the other keys
  17580. (org-remap org-mode-map
  17581. 'self-insert-command 'org-self-insert-command
  17582. 'delete-char 'org-delete-char
  17583. 'delete-backward-char 'org-delete-backward-char)
  17584. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17585. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17586. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17587. (if (boundp 'narrow-map)
  17588. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17589. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17590. (if (boundp 'narrow-map)
  17591. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17592. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17593. (if (boundp 'narrow-map)
  17594. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17595. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17596. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17597. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17598. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17599. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17600. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17601. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17602. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17603. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17604. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17605. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17606. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17607. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17608. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17609. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17610. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17611. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17612. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17613. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17614. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17615. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17616. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17617. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17618. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17619. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17620. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17621. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17622. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17623. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17624. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17625. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17626. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17627. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17628. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17629. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17630. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17631. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17632. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17633. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17634. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17635. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17636. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17637. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17638. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17639. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17640. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17641. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17642. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17643. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17644. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17645. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17646. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17647. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17648. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17649. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17650. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17651. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17652. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17653. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17654. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17655. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17656. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17657. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17658. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17659. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17660. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17661. (org-defkey org-mode-map "\C-m" 'org-return)
  17662. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17663. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17664. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17665. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17666. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17667. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17668. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17669. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17670. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17671. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17672. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17673. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17674. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17675. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17676. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17677. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17678. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17679. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17680. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17681. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17682. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17683. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17684. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17685. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17686. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17687. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17688. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17689. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17690. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17691. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17692. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17693. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17694. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17695. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17696. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17697. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17698. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17699. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17700. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17701. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17702. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17703. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17704. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17705. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17706. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17707. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17708. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17709. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17710. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17711. (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
  17712. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17713. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17714. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17715. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17716. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17717. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17718. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17719. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17720. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17721. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17722. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17723. (defconst org-speed-commands-default
  17724. '(
  17725. ("Outline Navigation")
  17726. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17727. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17728. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17729. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17730. ("F" . org-next-block)
  17731. ("B" . org-previous-block)
  17732. ("u" . (org-speed-move-safe 'outline-up-heading))
  17733. ("j" . org-goto)
  17734. ("g" . (org-refile t))
  17735. ("Outline Visibility")
  17736. ("c" . org-cycle)
  17737. ("C" . org-shifttab)
  17738. (" " . org-display-outline-path)
  17739. ("s" . org-narrow-to-subtree)
  17740. ("=" . org-columns)
  17741. ("Outline Structure Editing")
  17742. ("U" . org-metaup)
  17743. ("D" . org-metadown)
  17744. ("r" . org-metaright)
  17745. ("l" . org-metaleft)
  17746. ("R" . org-shiftmetaright)
  17747. ("L" . org-shiftmetaleft)
  17748. ("i" . (progn (forward-char 1) (call-interactively
  17749. 'org-insert-heading-respect-content)))
  17750. ("^" . org-sort)
  17751. ("w" . org-refile)
  17752. ("a" . org-archive-subtree-default-with-confirmation)
  17753. ("@" . org-mark-subtree)
  17754. ("#" . org-toggle-comment)
  17755. ("Clock Commands")
  17756. ("I" . org-clock-in)
  17757. ("O" . org-clock-out)
  17758. ("Meta Data Editing")
  17759. ("t" . org-todo)
  17760. ("," . (org-priority))
  17761. ("0" . (org-priority ?\ ))
  17762. ("1" . (org-priority ?A))
  17763. ("2" . (org-priority ?B))
  17764. ("3" . (org-priority ?C))
  17765. (":" . org-set-tags-command)
  17766. ("e" . org-set-effort)
  17767. ("E" . org-inc-effort)
  17768. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17769. (org-entry-put (point) "APPT_WARNTIME" m)))
  17770. ("Agenda Views etc")
  17771. ("v" . org-agenda)
  17772. ("/" . org-sparse-tree)
  17773. ("Misc")
  17774. ("o" . org-open-at-point)
  17775. ("?" . org-speed-command-help)
  17776. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17777. (">" . (org-agenda-remove-restriction-lock))
  17778. )
  17779. "The default speed commands.")
  17780. (defun org-print-speed-command (e)
  17781. (if (> (length (car e)) 1)
  17782. (progn
  17783. (princ "\n")
  17784. (princ (car e))
  17785. (princ "\n")
  17786. (princ (make-string (length (car e)) ?-))
  17787. (princ "\n"))
  17788. (princ (car e))
  17789. (princ " ")
  17790. (if (symbolp (cdr e))
  17791. (princ (symbol-name (cdr e)))
  17792. (prin1 (cdr e)))
  17793. (princ "\n")))
  17794. (defun org-speed-command-help ()
  17795. "Show the available speed commands."
  17796. (interactive)
  17797. (if (not org-use-speed-commands)
  17798. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17799. (with-output-to-temp-buffer "*Help*"
  17800. (princ "User-defined Speed commands\n===========================\n")
  17801. (mapc #'org-print-speed-command org-speed-commands-user)
  17802. (princ "\n")
  17803. (princ "Built-in Speed commands\n=======================\n")
  17804. (mapc #'org-print-speed-command org-speed-commands-default))
  17805. (with-current-buffer "*Help*"
  17806. (setq truncate-lines t))))
  17807. (defun org-speed-move-safe (cmd)
  17808. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17809. If not, return to the original position and throw an error."
  17810. (interactive)
  17811. (let ((pos (point)))
  17812. (call-interactively cmd)
  17813. (unless (and (bolp) (org-at-heading-p))
  17814. (goto-char pos)
  17815. (error "Boundary reached while executing %s" cmd))))
  17816. (defvar org-self-insert-command-undo-counter 0)
  17817. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17818. (defvar org-speed-command nil)
  17819. (defun org-speed-command-activate (keys)
  17820. "Hook for activating single-letter speed commands.
  17821. `org-speed-commands-default' specifies a minimal command set.
  17822. Use `org-speed-commands-user' for further customization."
  17823. (when (or (and (bolp) (looking-at org-outline-regexp))
  17824. (and (functionp org-use-speed-commands)
  17825. (funcall org-use-speed-commands)))
  17826. (cdr (assoc keys (append org-speed-commands-user
  17827. org-speed-commands-default)))))
  17828. (defun org-babel-speed-command-activate (keys)
  17829. "Hook for activating single-letter code block commands."
  17830. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17831. (cdr (assoc keys org-babel-key-bindings))))
  17832. (defcustom org-speed-command-hook
  17833. '(org-speed-command-activate org-babel-speed-command-activate)
  17834. "Hook for activating speed commands at strategic locations.
  17835. Hook functions are called in sequence until a valid handler is
  17836. found.
  17837. Each hook takes a single argument, a user-pressed command key
  17838. which is also a `self-insert-command' from the global map.
  17839. Within the hook, examine the cursor position and the command key
  17840. and return nil or a valid handler as appropriate. Handler could
  17841. be one of an interactive command, a function, or a form.
  17842. Set `org-use-speed-commands' to non-nil value to enable this
  17843. hook. The default setting is `org-speed-command-activate'."
  17844. :group 'org-structure
  17845. :version "24.1"
  17846. :type 'hook)
  17847. (defun org-self-insert-command (N)
  17848. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17849. If the cursor is in a table looking at whitespace, the whitespace is
  17850. overwritten, and the table is not marked as requiring realignment."
  17851. (interactive "p")
  17852. (org-check-before-invisible-edit 'insert)
  17853. (cond
  17854. ((and org-use-speed-commands
  17855. (let ((kv (this-command-keys-vector)))
  17856. (setq org-speed-command
  17857. (run-hook-with-args-until-success
  17858. 'org-speed-command-hook
  17859. (make-string 1 (aref kv (1- (length kv))))))))
  17860. (cond
  17861. ((commandp org-speed-command)
  17862. (setq this-command org-speed-command)
  17863. (call-interactively org-speed-command))
  17864. ((functionp org-speed-command)
  17865. (funcall org-speed-command))
  17866. ((and org-speed-command (listp org-speed-command))
  17867. (eval org-speed-command))
  17868. (t (let (org-use-speed-commands)
  17869. (call-interactively 'org-self-insert-command)))))
  17870. ((and
  17871. (org-at-table-p)
  17872. (eq N 1)
  17873. (not (org-region-active-p))
  17874. (progn
  17875. ;; Check if we blank the field, and if that triggers align.
  17876. (and (featurep 'org-table) org-table-auto-blank-field
  17877. (memq last-command
  17878. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17879. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17880. ;; Got extra space, this field does not determine
  17881. ;; column width.
  17882. (let (org-table-may-need-update) (org-table-blank-field))
  17883. ;; No extra space, this field may determine column
  17884. ;; width.
  17885. (org-table-blank-field)))
  17886. t)
  17887. (looking-at "[^|\n]* \\( \\)|"))
  17888. ;; There is room for insertion without re-aligning the table.
  17889. (delete-region (match-beginning 1) (match-end 1))
  17890. (self-insert-command N))
  17891. (t
  17892. (setq org-table-may-need-update t)
  17893. (self-insert-command N)
  17894. (org-fix-tags-on-the-fly)
  17895. (when org-self-insert-cluster-for-undo
  17896. (if (not (eq last-command 'org-self-insert-command))
  17897. (setq org-self-insert-command-undo-counter 1)
  17898. (if (>= org-self-insert-command-undo-counter 20)
  17899. (setq org-self-insert-command-undo-counter 1)
  17900. (and (> org-self-insert-command-undo-counter 0)
  17901. buffer-undo-list (listp buffer-undo-list)
  17902. (not (cadr buffer-undo-list)) ; remove nil entry
  17903. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17904. (setq org-self-insert-command-undo-counter
  17905. (1+ org-self-insert-command-undo-counter))))))))
  17906. (defun org-check-before-invisible-edit (kind)
  17907. "Check is editing if kind KIND would be dangerous with invisible text around.
  17908. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17909. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17910. (when (and org-catch-invisible-edits
  17911. (or (not (boundp 'visible-mode)) (not visible-mode))
  17912. (or (get-char-property (point) 'invisible)
  17913. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17914. ;; OK, we need to take a closer look. Do not consider
  17915. ;; invisibility obtained through text properties (e.g., link
  17916. ;; fontification), as it cannot be toggled.
  17917. (let* ((invisible-at-point
  17918. (pcase (get-char-property-and-overlay (point) 'invisible)
  17919. (`(,_ . ,(and (pred overlayp) o)) o)))
  17920. ;; Assume that point cannot land in the middle of an
  17921. ;; overlay, or between two overlays.
  17922. (invisible-before-point
  17923. (and (not invisible-at-point)
  17924. (not (bobp))
  17925. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17926. (`(,_ . ,(and (pred overlayp) o)) o))))
  17927. (border-and-ok-direction
  17928. (or
  17929. ;; Check if we are acting predictably before invisible
  17930. ;; text.
  17931. (and invisible-at-point
  17932. (memq kind '(insert delete-backward)))
  17933. ;; Check if we are acting predictably after invisible text
  17934. ;; This works not well, and I have turned it off. It seems
  17935. ;; better to always show and stop after invisible text.
  17936. ;; (and (not invisible-at-point) invisible-before-point
  17937. ;; (memq kind '(insert delete)))
  17938. )))
  17939. (when (or invisible-at-point invisible-before-point)
  17940. (when (eq org-catch-invisible-edits 'error)
  17941. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17942. (if (and org-custom-properties-overlays
  17943. (y-or-n-p "Display invisible properties in this buffer? "))
  17944. (org-toggle-custom-properties-visibility)
  17945. ;; Make the area visible
  17946. (save-excursion
  17947. (when invisible-before-point
  17948. (goto-char
  17949. (previous-single-char-property-change (point) 'invisible)))
  17950. ;; Remove whatever overlay is currently making yet-to-be
  17951. ;; edited text invisible. Also remove nested invisibility
  17952. ;; related overlays.
  17953. (delete-overlay (or invisible-at-point invisible-before-point))
  17954. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17955. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17956. (`(,_ . ,(and (pred overlayp) o))
  17957. (delete-overlay o)
  17958. t)))))
  17959. (cond
  17960. ((eq org-catch-invisible-edits 'show)
  17961. ;; That's it, we do the edit after showing
  17962. (message
  17963. "Unfolding invisible region around point before editing")
  17964. (sit-for 1))
  17965. ((and (eq org-catch-invisible-edits 'smart)
  17966. border-and-ok-direction)
  17967. (message "Unfolding invisible region around point before editing"))
  17968. (t
  17969. ;; Don't do the edit, make the user repeat it in full visibility
  17970. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17971. (defun org-fix-tags-on-the-fly ()
  17972. "Align tags in headline at point.
  17973. Unlike to `org-set-tags', it ignores region and sorting."
  17974. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17975. (org-at-heading-p))
  17976. (let ((org-ignore-region t)
  17977. (org-tags-sort-function nil))
  17978. (org-set-tags nil t))))
  17979. (defun org-delete-backward-char (N)
  17980. "Like `delete-backward-char', insert whitespace at field end in tables.
  17981. When deleting backwards, in tables this function will insert whitespace in
  17982. front of the next \"|\" separator, to keep the table aligned. The table will
  17983. still be marked for re-alignment if the field did fill the entire column,
  17984. because, in this case the deletion might narrow the column."
  17985. (interactive "p")
  17986. (save-match-data
  17987. (org-check-before-invisible-edit 'delete-backward)
  17988. (if (and (org-at-table-p)
  17989. (eq N 1)
  17990. (not (org-region-active-p))
  17991. (string-match "|" (buffer-substring (point-at-bol) (point)))
  17992. (looking-at ".*?|"))
  17993. (let ((pos (point))
  17994. (noalign (looking-at "[^|\n\r]* |"))
  17995. (c org-table-may-need-update))
  17996. (backward-delete-char N)
  17997. (unless overwrite-mode
  17998. (skip-chars-forward "^|")
  17999. (insert " ")
  18000. (goto-char (1- pos)))
  18001. ;; noalign: if there were two spaces at the end, this field
  18002. ;; does not determine the width of the column.
  18003. (when noalign (setq org-table-may-need-update c)))
  18004. (backward-delete-char N)
  18005. (org-fix-tags-on-the-fly))))
  18006. (defun org-delete-char (N)
  18007. "Like `delete-char', but insert whitespace at field end in tables.
  18008. When deleting characters, in tables this function will insert whitespace in
  18009. front of the next \"|\" separator, to keep the table aligned. The table will
  18010. still be marked for re-alignment if the field did fill the entire column,
  18011. because, in this case the deletion might narrow the column."
  18012. (interactive "p")
  18013. (save-match-data
  18014. (org-check-before-invisible-edit 'delete)
  18015. (if (and (org-at-table-p)
  18016. (not (bolp))
  18017. (not (= (char-after) ?|))
  18018. (eq N 1))
  18019. (if (looking-at ".*?|")
  18020. (let ((pos (point))
  18021. (noalign (looking-at "[^|\n\r]* |"))
  18022. (c org-table-may-need-update))
  18023. (replace-match
  18024. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18025. (goto-char pos)
  18026. ;; noalign: if there were two spaces at the end, this field
  18027. ;; does not determine the width of the column.
  18028. (when noalign (setq org-table-may-need-update c)))
  18029. (delete-char N))
  18030. (delete-char N)
  18031. (org-fix-tags-on-the-fly))))
  18032. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18033. (put 'org-self-insert-command 'delete-selection
  18034. (lambda ()
  18035. (not (run-hook-with-args-until-success
  18036. 'self-insert-uses-region-functions))))
  18037. (put 'orgtbl-self-insert-command 'delete-selection
  18038. (lambda ()
  18039. (not (run-hook-with-args-until-success
  18040. 'self-insert-uses-region-functions))))
  18041. (put 'org-delete-char 'delete-selection 'supersede)
  18042. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18043. (put 'org-yank 'delete-selection 'yank)
  18044. ;; Make `flyspell-mode' delay after some commands
  18045. (put 'org-self-insert-command 'flyspell-delayed t)
  18046. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18047. (put 'org-delete-char 'flyspell-delayed t)
  18048. (put 'org-delete-backward-char 'flyspell-delayed t)
  18049. ;; Make pabbrev-mode expand after Org mode commands
  18050. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18051. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18052. (defun org-transpose-words ()
  18053. "Transpose words for Org.
  18054. This uses the `org-mode-transpose-word-syntax-table' syntax
  18055. table, which interprets characters in `org-emphasis-alist' as
  18056. word constituents."
  18057. (interactive)
  18058. (with-syntax-table org-mode-transpose-word-syntax-table
  18059. (call-interactively 'transpose-words)))
  18060. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18061. (defvar org-ctrl-c-ctrl-c-hook nil
  18062. "Hook for functions attaching themselves to `C-c C-c'.
  18063. This can be used to add additional functionality to the C-c C-c
  18064. key which executes context-dependent commands. This hook is run
  18065. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18066. run after the last test.
  18067. Each function will be called with no arguments. The function
  18068. must check if the context is appropriate for it to act. If yes,
  18069. it should do its thing and then return a non-nil value. If the
  18070. context is wrong, just do nothing and return nil.")
  18071. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18072. "Hook for functions attaching themselves to `C-c C-c'.
  18073. This can be used to add additional functionality to the C-c C-c
  18074. key which executes context-dependent commands. This hook is run
  18075. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18076. before the first test.
  18077. Each function will be called with no arguments. The function
  18078. must check if the context is appropriate for it to act. If yes,
  18079. it should do its thing and then return a non-nil value. If the
  18080. context is wrong, just do nothing and return nil.")
  18081. (defvar org-tab-first-hook nil
  18082. "Hook for functions to attach themselves to TAB.
  18083. See `org-ctrl-c-ctrl-c-hook' for more information.
  18084. This hook runs as the first action when TAB is pressed, even before
  18085. `org-cycle' messes around with the `outline-regexp' to cater for
  18086. inline tasks and plain list item folding.
  18087. If any function in this hook returns t, any other actions that
  18088. would have been caused by TAB (such as table field motion or visibility
  18089. cycling) will not occur.")
  18090. (defvar org-tab-after-check-for-table-hook nil
  18091. "Hook for functions to attach themselves to TAB.
  18092. See `org-ctrl-c-ctrl-c-hook' for more information.
  18093. This hook runs after it has been established that the cursor is not in a
  18094. table, but before checking if the cursor is in a headline or if global cycling
  18095. should be done.
  18096. If any function in this hook returns t, not other actions like visibility
  18097. cycling will be done.")
  18098. (defvar org-tab-after-check-for-cycling-hook nil
  18099. "Hook for functions to attach themselves to TAB.
  18100. See `org-ctrl-c-ctrl-c-hook' for more information.
  18101. This hook runs after it has been established that not table field motion and
  18102. not visibility should be done because of current context. This is probably
  18103. the place where a package like yasnippets can hook in.")
  18104. (defvar org-tab-before-tab-emulation-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 every other options for TAB have been exhausted, but
  18108. before indentation and \t insertion takes place.")
  18109. (defvar org-metaleft-hook nil
  18110. "Hook for functions attaching themselves to `M-left'.
  18111. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18112. (defvar org-metaright-hook nil
  18113. "Hook for functions attaching themselves to `M-right'.
  18114. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18115. (defvar org-metaup-hook nil
  18116. "Hook for functions attaching themselves to `M-up'.
  18117. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18118. (defvar org-metadown-hook nil
  18119. "Hook for functions attaching themselves to `M-down'.
  18120. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18121. (defvar org-shiftmetaleft-hook nil
  18122. "Hook for functions attaching themselves to `M-S-left'.
  18123. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18124. (defvar org-shiftmetaright-hook nil
  18125. "Hook for functions attaching themselves to `M-S-right'.
  18126. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18127. (defvar org-shiftmetaup-hook nil
  18128. "Hook for functions attaching themselves to `M-S-up'.
  18129. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18130. (defvar org-shiftmetadown-hook nil
  18131. "Hook for functions attaching themselves to `M-S-down'.
  18132. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18133. (defvar org-metareturn-hook nil
  18134. "Hook for functions attaching themselves to `M-RET'.
  18135. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18136. (defvar org-shiftup-hook nil
  18137. "Hook for functions attaching themselves to `S-up'.
  18138. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18139. (defvar org-shiftup-final-hook nil
  18140. "Hook for functions attaching themselves to `S-up'.
  18141. This one runs after all other options except shift-select have been excluded.
  18142. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18143. (defvar org-shiftdown-hook nil
  18144. "Hook for functions attaching themselves to `S-down'.
  18145. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18146. (defvar org-shiftdown-final-hook nil
  18147. "Hook for functions attaching themselves to `S-down'.
  18148. This one runs after all other options except shift-select have been excluded.
  18149. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18150. (defvar org-shiftleft-hook nil
  18151. "Hook for functions attaching themselves to `S-left'.
  18152. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18153. (defvar org-shiftleft-final-hook nil
  18154. "Hook for functions attaching themselves to `S-left'.
  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-shiftright-hook nil
  18158. "Hook for functions attaching themselves to `S-right'.
  18159. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18160. (defvar org-shiftright-final-hook nil
  18161. "Hook for functions attaching themselves to `S-right'.
  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. (defun org-modifier-cursor-error ()
  18165. "Throw an error, a modified cursor command was applied in wrong context."
  18166. (user-error "This command is active in special context like tables, headlines or items"))
  18167. (defun org-shiftselect-error ()
  18168. "Throw an error because Shift-Cursor command was applied in wrong context."
  18169. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18170. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18171. (user-error "This command works only in special context like headlines or timestamps")))
  18172. (defun org-call-for-shift-select (cmd)
  18173. (let ((this-command-keys-shift-translated t))
  18174. (call-interactively cmd)))
  18175. (defun org-shifttab (&optional arg)
  18176. "Global visibility cycling or move to previous table field.
  18177. Call `org-table-previous-field' within a table.
  18178. When ARG is nil, cycle globally through visibility states.
  18179. When ARG is a numeric prefix, show contents of this level."
  18180. (interactive "P")
  18181. (cond
  18182. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18183. ((integerp arg)
  18184. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18185. (message "Content view to level: %d" arg)
  18186. (org-content (prefix-numeric-value arg2))
  18187. (org-cycle-show-empty-lines t)
  18188. (setq org-cycle-global-status 'overview)))
  18189. (t (call-interactively 'org-global-cycle))))
  18190. (defun org-shiftmetaleft ()
  18191. "Promote subtree or delete table column.
  18192. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18193. `org-table-delete-column', depending on context. See the
  18194. individual commands for more information."
  18195. (interactive)
  18196. (cond
  18197. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18198. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18199. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18200. ((if (not (org-region-active-p)) (org-at-item-p)
  18201. (save-excursion (goto-char (region-beginning))
  18202. (org-at-item-p)))
  18203. (call-interactively 'org-outdent-item-tree))
  18204. (t (org-modifier-cursor-error))))
  18205. (defun org-shiftmetaright ()
  18206. "Demote subtree or insert table column.
  18207. Calls `org-demote-subtree', `org-indent-item-tree', or
  18208. `org-table-insert-column', depending on context. See the
  18209. individual commands for more information."
  18210. (interactive)
  18211. (cond
  18212. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18213. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18214. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18215. ((if (not (org-region-active-p)) (org-at-item-p)
  18216. (save-excursion (goto-char (region-beginning))
  18217. (org-at-item-p)))
  18218. (call-interactively 'org-indent-item-tree))
  18219. (t (org-modifier-cursor-error))))
  18220. (defun org-shiftmetaup (&optional _arg)
  18221. "Drag the line at point up.
  18222. In a table, kill the current row.
  18223. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18224. but also adjust the previous clocked item in the clock history.
  18225. Everywhere else, drag the line at point up."
  18226. (interactive "P")
  18227. (cond
  18228. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18229. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18230. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18231. (call-interactively 'org-timestamp-up)))
  18232. (t (call-interactively 'org-drag-line-backward))))
  18233. (defun org-shiftmetadown (&optional _arg)
  18234. "Drag the line at point down.
  18235. In a table, insert an empty row at the current line.
  18236. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18237. but also adjust the previous clocked item in the clock history.
  18238. Everywhere else, drag the line at point down."
  18239. (interactive "P")
  18240. (cond
  18241. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18242. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18243. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18244. (call-interactively 'org-timestamp-down)))
  18245. (t (call-interactively 'org-drag-line-forward))))
  18246. (defsubst org-hidden-tree-error ()
  18247. (user-error
  18248. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18249. (defun org-metaleft (&optional _arg)
  18250. "Promote heading, list item at point or move table column left.
  18251. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18252. depending on context. With no specific context, calls the Emacs
  18253. default `backward-word'. See the individual commands for more
  18254. information.
  18255. This function runs the hook `org-metaleft-hook' as a first step,
  18256. and returns at first non-nil value."
  18257. (interactive "P")
  18258. (cond
  18259. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18260. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18261. ((org-with-limited-levels
  18262. (or (org-at-heading-p)
  18263. (and (org-region-active-p)
  18264. (save-excursion
  18265. (goto-char (region-beginning))
  18266. (org-at-heading-p)))))
  18267. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18268. (call-interactively 'org-do-promote))
  18269. ;; At an inline task.
  18270. ((org-at-heading-p)
  18271. (call-interactively 'org-inlinetask-promote))
  18272. ((or (org-at-item-p)
  18273. (and (org-region-active-p)
  18274. (save-excursion
  18275. (goto-char (region-beginning))
  18276. (org-at-item-p))))
  18277. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18278. (call-interactively 'org-outdent-item))
  18279. (t (call-interactively 'backward-word))))
  18280. (defun org-metaright (&optional _arg)
  18281. "Demote heading, list item at point or move table column right.
  18282. In front of a drawer or a block keyword, indent it correctly.
  18283. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18284. `org-indent-drawer' or `org-indent-block' depending on context.
  18285. With no specific context, calls the Emacs default `forward-word'.
  18286. See the individual commands for more information.
  18287. This function runs the hook `org-metaright-hook' as a first step,
  18288. and returns at first non-nil value."
  18289. (interactive "P")
  18290. (cond
  18291. ((run-hook-with-args-until-success 'org-metaright-hook))
  18292. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18293. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18294. ((org-at-block-p) (call-interactively 'org-indent-block))
  18295. ((org-with-limited-levels
  18296. (or (org-at-heading-p)
  18297. (and (org-region-active-p)
  18298. (save-excursion
  18299. (goto-char (region-beginning))
  18300. (org-at-heading-p)))))
  18301. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18302. (call-interactively 'org-do-demote))
  18303. ;; At an inline task.
  18304. ((org-at-heading-p)
  18305. (call-interactively 'org-inlinetask-demote))
  18306. ((or (org-at-item-p)
  18307. (and (org-region-active-p)
  18308. (save-excursion
  18309. (goto-char (region-beginning))
  18310. (org-at-item-p))))
  18311. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18312. (call-interactively 'org-indent-item))
  18313. (t (call-interactively 'forward-word))))
  18314. (defun org-check-for-hidden (what)
  18315. "Check if there are hidden headlines/items in the current visual line.
  18316. WHAT can be either `headlines' or `items'. If the current line is
  18317. an outline or item heading and it has a folded subtree below it,
  18318. this function returns t, nil otherwise."
  18319. (let ((re (cond
  18320. ((eq what 'headlines) org-outline-regexp-bol)
  18321. ((eq what 'items) (org-item-beginning-re))
  18322. (t (error "This should not happen"))))
  18323. beg end)
  18324. (save-excursion
  18325. (catch 'exit
  18326. (unless (org-region-active-p)
  18327. (setq beg (point-at-bol))
  18328. (beginning-of-line 2)
  18329. (while (and (not (eobp)) ;; this is like `next-line'
  18330. (get-char-property (1- (point)) 'invisible))
  18331. (beginning-of-line 2))
  18332. (setq end (point))
  18333. (goto-char beg)
  18334. (goto-char (point-at-eol))
  18335. (setq end (max end (point)))
  18336. (while (re-search-forward re end t)
  18337. (when (get-char-property (match-beginning 0) 'invisible)
  18338. (throw 'exit t))))
  18339. nil))))
  18340. (defun org-metaup (&optional _arg)
  18341. "Move subtree up or move table row up.
  18342. Calls `org-move-subtree-up' or `org-table-move-row' or
  18343. `org-move-item-up', depending on context. See the individual commands
  18344. for more information."
  18345. (interactive "P")
  18346. (cond
  18347. ((run-hook-with-args-until-success 'org-metaup-hook))
  18348. ((org-region-active-p)
  18349. (let* ((a (min (region-beginning) (region-end)))
  18350. (b (1- (max (region-beginning) (region-end))))
  18351. (c (save-excursion (goto-char a)
  18352. (move-beginning-of-line 0)))
  18353. (d (save-excursion (goto-char a)
  18354. (move-end-of-line 0) (point))))
  18355. (transpose-regions a b c d)
  18356. (goto-char c)))
  18357. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18358. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18359. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18360. (t (org-drag-element-backward))))
  18361. (defun org-metadown (&optional _arg)
  18362. "Move subtree down or move table row down.
  18363. Calls `org-move-subtree-down' or `org-table-move-row' or
  18364. `org-move-item-down', depending on context. See the individual
  18365. commands for more information."
  18366. (interactive "P")
  18367. (cond
  18368. ((run-hook-with-args-until-success 'org-metadown-hook))
  18369. ((org-region-active-p)
  18370. (let* ((a (min (region-beginning) (region-end)))
  18371. (b (max (region-beginning) (region-end)))
  18372. (c (save-excursion (goto-char b)
  18373. (move-beginning-of-line 1)))
  18374. (d (save-excursion (goto-char b)
  18375. (move-end-of-line 1) (1+ (point)))))
  18376. (transpose-regions a b c d)
  18377. (goto-char d)))
  18378. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18379. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18380. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18381. (t (org-drag-element-forward))))
  18382. (defun org-shiftup (&optional arg)
  18383. "Increase item in timestamp or increase priority of current headline.
  18384. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18385. depending on context. See the individual commands for more information."
  18386. (interactive "P")
  18387. (cond
  18388. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18389. ((and org-support-shift-select (org-region-active-p))
  18390. (org-call-for-shift-select 'previous-line))
  18391. ((org-at-timestamp-p 'lax)
  18392. (call-interactively (if org-edit-timestamp-down-means-later
  18393. 'org-timestamp-down 'org-timestamp-up)))
  18394. ((and (not (eq org-support-shift-select 'always))
  18395. org-enable-priority-commands
  18396. (org-at-heading-p))
  18397. (call-interactively 'org-priority-up))
  18398. ((and (not org-support-shift-select) (org-at-item-p))
  18399. (call-interactively 'org-previous-item))
  18400. ((org-clocktable-try-shift 'up arg))
  18401. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18402. (org-support-shift-select
  18403. (org-call-for-shift-select 'previous-line))
  18404. (t (org-shiftselect-error))))
  18405. (defun org-shiftdown (&optional arg)
  18406. "Decrease item in timestamp or decrease priority of current headline.
  18407. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18408. depending on context. See the individual commands for more information."
  18409. (interactive "P")
  18410. (cond
  18411. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18412. ((and org-support-shift-select (org-region-active-p))
  18413. (org-call-for-shift-select 'next-line))
  18414. ((org-at-timestamp-p 'lax)
  18415. (call-interactively (if org-edit-timestamp-down-means-later
  18416. 'org-timestamp-up 'org-timestamp-down)))
  18417. ((and (not (eq org-support-shift-select 'always))
  18418. org-enable-priority-commands
  18419. (org-at-heading-p))
  18420. (call-interactively 'org-priority-down))
  18421. ((and (not org-support-shift-select) (org-at-item-p))
  18422. (call-interactively 'org-next-item))
  18423. ((org-clocktable-try-shift 'down arg))
  18424. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18425. (org-support-shift-select
  18426. (org-call-for-shift-select 'next-line))
  18427. (t (org-shiftselect-error))))
  18428. (defun org-shiftright (&optional arg)
  18429. "Cycle the thing at point or in the current line, depending on context.
  18430. Depending on context, this does one of the following:
  18431. - switch a timestamp at point one day into the future
  18432. - on a headline, switch to the next TODO keyword.
  18433. - on an item, switch entire list to the next bullet type
  18434. - on a property line, switch to the next allowed value
  18435. - on a clocktable definition line, move time block into the future"
  18436. (interactive "P")
  18437. (cond
  18438. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18439. ((and org-support-shift-select (org-region-active-p))
  18440. (org-call-for-shift-select 'forward-char))
  18441. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18442. ((and (not (eq org-support-shift-select 'always))
  18443. (org-at-heading-p))
  18444. (let ((org-inhibit-logging
  18445. (not org-treat-S-cursor-todo-selection-as-state-change))
  18446. (org-inhibit-blocking
  18447. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18448. (org-call-with-arg 'org-todo 'right)))
  18449. ((or (and org-support-shift-select
  18450. (not (eq org-support-shift-select 'always))
  18451. (org-at-item-bullet-p))
  18452. (and (not org-support-shift-select) (org-at-item-p)))
  18453. (org-call-with-arg 'org-cycle-list-bullet nil))
  18454. ((and (not (eq org-support-shift-select 'always))
  18455. (org-at-property-p))
  18456. (call-interactively 'org-property-next-allowed-value))
  18457. ((org-clocktable-try-shift 'right arg))
  18458. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18459. (org-support-shift-select
  18460. (org-call-for-shift-select 'forward-char))
  18461. (t (org-shiftselect-error))))
  18462. (defun org-shiftleft (&optional arg)
  18463. "Cycle the thing at point or in the current line, depending on context.
  18464. Depending on context, this does one of the following:
  18465. - switch a timestamp at point one day into the past
  18466. - on a headline, switch to the previous TODO keyword.
  18467. - on an item, switch entire list to the previous bullet type
  18468. - on a property line, switch to the previous allowed value
  18469. - on a clocktable definition line, move time block into the past"
  18470. (interactive "P")
  18471. (cond
  18472. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18473. ((and org-support-shift-select (org-region-active-p))
  18474. (org-call-for-shift-select 'backward-char))
  18475. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18476. ((and (not (eq org-support-shift-select 'always))
  18477. (org-at-heading-p))
  18478. (let ((org-inhibit-logging
  18479. (not org-treat-S-cursor-todo-selection-as-state-change))
  18480. (org-inhibit-blocking
  18481. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18482. (org-call-with-arg 'org-todo 'left)))
  18483. ((or (and org-support-shift-select
  18484. (not (eq org-support-shift-select 'always))
  18485. (org-at-item-bullet-p))
  18486. (and (not org-support-shift-select) (org-at-item-p)))
  18487. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18488. ((and (not (eq org-support-shift-select 'always))
  18489. (org-at-property-p))
  18490. (call-interactively 'org-property-previous-allowed-value))
  18491. ((org-clocktable-try-shift 'left arg))
  18492. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18493. (org-support-shift-select
  18494. (org-call-for-shift-select 'backward-char))
  18495. (t (org-shiftselect-error))))
  18496. (defun org-shiftcontrolright ()
  18497. "Switch to next TODO set."
  18498. (interactive)
  18499. (cond
  18500. ((and org-support-shift-select (org-region-active-p))
  18501. (org-call-for-shift-select 'forward-word))
  18502. ((and (not (eq org-support-shift-select 'always))
  18503. (org-at-heading-p))
  18504. (org-call-with-arg 'org-todo 'nextset))
  18505. (org-support-shift-select
  18506. (org-call-for-shift-select 'forward-word))
  18507. (t (org-shiftselect-error))))
  18508. (defun org-shiftcontrolleft ()
  18509. "Switch to previous TODO set."
  18510. (interactive)
  18511. (cond
  18512. ((and org-support-shift-select (org-region-active-p))
  18513. (org-call-for-shift-select 'backward-word))
  18514. ((and (not (eq org-support-shift-select 'always))
  18515. (org-at-heading-p))
  18516. (org-call-with-arg 'org-todo 'previousset))
  18517. (org-support-shift-select
  18518. (org-call-for-shift-select 'backward-word))
  18519. (t (org-shiftselect-error))))
  18520. (defun org-shiftcontrolup (&optional n)
  18521. "Change timestamps synchronously up in CLOCK log lines.
  18522. Optional argument N tells to change by that many units."
  18523. (interactive "P")
  18524. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18525. (let (org-support-shift-select)
  18526. (org-clock-timestamps-up n))
  18527. (user-error "Not at a clock log")))
  18528. (defun org-shiftcontroldown (&optional n)
  18529. "Change timestamps synchronously down in CLOCK log lines.
  18530. Optional argument N tells to change by that many units."
  18531. (interactive "P")
  18532. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18533. (let (org-support-shift-select)
  18534. (org-clock-timestamps-down n))
  18535. (user-error "Not at a clock log")))
  18536. (defun org-increase-number-at-point (&optional inc)
  18537. "Increment the number at point.
  18538. With an optional prefix numeric argument INC, increment using
  18539. this numeric value."
  18540. (interactive "p")
  18541. (if (not (number-at-point))
  18542. (user-error "Not on a number")
  18543. (unless inc (setq inc 1))
  18544. (let ((pos (point))
  18545. (beg (skip-chars-backward "-+^/*0-9eE."))
  18546. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18547. (setq nap (buffer-substring-no-properties
  18548. (+ pos beg) (+ pos beg end)))
  18549. (delete-region (+ pos beg) (+ pos beg end))
  18550. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18551. (when (org-at-table-p)
  18552. (org-table-align)
  18553. (org-table-end-of-field 1))))
  18554. (defun org-decrease-number-at-point (&optional inc)
  18555. "Decrement the number at point.
  18556. With an optional prefix numeric argument INC, decrement using
  18557. this numeric value."
  18558. (interactive "p")
  18559. (org-increase-number-at-point (- (or inc 1))))
  18560. (defun org-ctrl-c-ret ()
  18561. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18562. (interactive)
  18563. (cond
  18564. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18565. (t (call-interactively 'org-insert-heading))))
  18566. (defun org-find-visible ()
  18567. (let ((s (point)))
  18568. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18569. (get-char-property s 'invisible)))
  18570. s))
  18571. (defun org-find-invisible ()
  18572. (let ((s (point)))
  18573. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18574. (not (get-char-property s 'invisible))))
  18575. s))
  18576. (defun org-copy-visible (beg end)
  18577. "Copy the visible parts of the region."
  18578. (interactive "r")
  18579. (let ((result ""))
  18580. (while (/= beg end)
  18581. (when (get-char-property beg 'invisible)
  18582. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18583. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18584. (setq result (concat result (buffer-substring beg next)))
  18585. (setq beg next)))
  18586. (kill-new result)))
  18587. (defun org-copy-special ()
  18588. "Copy region in table or copy current subtree.
  18589. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18590. context. See the individual commands for more information."
  18591. (interactive)
  18592. (call-interactively
  18593. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18594. (defun org-cut-special ()
  18595. "Cut region in table or cut current subtree.
  18596. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18597. context. See the individual commands for more information."
  18598. (interactive)
  18599. (call-interactively
  18600. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18601. (defun org-paste-special (arg)
  18602. "Paste rectangular region into table, or past subtree relative to level.
  18603. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18604. See the individual commands for more information."
  18605. (interactive "P")
  18606. (if (org-at-table-p)
  18607. (org-table-paste-rectangle)
  18608. (org-paste-subtree arg)))
  18609. (defun org-edit-special (&optional arg)
  18610. "Call a special editor for the element at point.
  18611. When at a table, call the formula editor with `org-table-edit-formulas'.
  18612. When in a source code block, call `org-edit-src-code'.
  18613. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18614. When in an export block, call `org-edit-export-block'.
  18615. When in a LaTeX environment, call `org-edit-latex-environment'.
  18616. When at an #+INCLUDE keyword, visit the included file.
  18617. When at a footnote reference, call `org-edit-footnote-reference'
  18618. On a link, call `ffap' to visit the link at point.
  18619. Otherwise, return a user error."
  18620. (interactive "P")
  18621. (let ((element (org-element-at-point)))
  18622. (barf-if-buffer-read-only)
  18623. (pcase (org-element-type element)
  18624. (`src-block
  18625. (if (not arg) (org-edit-src-code)
  18626. (let* ((info (org-babel-get-src-block-info))
  18627. (lang (nth 0 info))
  18628. (params (nth 2 info))
  18629. (session (cdr (assq :session params))))
  18630. (if (not session) (org-edit-src-code)
  18631. ;; At a src-block with a session and function called with
  18632. ;; an ARG: switch to the buffer related to the inferior
  18633. ;; process.
  18634. (switch-to-buffer
  18635. (funcall (intern (concat "org-babel-prep-session:" lang))
  18636. session params))))))
  18637. (`keyword
  18638. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18639. (org-open-link-from-string
  18640. (format "[[%s]]"
  18641. (expand-file-name
  18642. (let ((value (org-element-property :value element)))
  18643. (cond ((org-file-url-p value)
  18644. (user-error "The file is specified as a URL, cannot be edited"))
  18645. ((not (org-string-nw-p value))
  18646. (user-error "No file to edit"))
  18647. ((string-match "\\`\"\\(.*?\\)\"" value)
  18648. (match-string 1 value))
  18649. ((string-match "\\`[^ \t\"]\\S-*" value)
  18650. (match-string 0 value))
  18651. (t (user-error "No valid file specified")))))))
  18652. (user-error "No special environment to edit here")))
  18653. (`table
  18654. (if (eq (org-element-property :type element) 'table.el)
  18655. (org-edit-table.el)
  18656. (call-interactively 'org-table-edit-formulas)))
  18657. ;; Only Org tables contain `table-row' type elements.
  18658. (`table-row (call-interactively 'org-table-edit-formulas))
  18659. (`example-block (org-edit-src-code))
  18660. (`export-block (org-edit-export-block))
  18661. (`fixed-width (org-edit-fixed-width-region))
  18662. (`latex-environment (org-edit-latex-environment))
  18663. (_
  18664. ;; No notable element at point. Though, we may be at a link or
  18665. ;; a footnote reference, which are objects. Thus, scan deeper.
  18666. (let ((context (org-element-context element)))
  18667. (pcase (org-element-type context)
  18668. (`footnote-reference (org-edit-footnote-reference))
  18669. (`inline-src-block (org-edit-inline-src-code))
  18670. (`link (call-interactively #'ffap))
  18671. (_ (user-error "No special environment to edit here"))))))))
  18672. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18673. (defun org-ctrl-c-ctrl-c (&optional arg)
  18674. "Set tags in headline, or update according to changed information at point.
  18675. This command does many different things, depending on context:
  18676. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18677. this is what we do.
  18678. - If the cursor is on a statistics cookie, update it.
  18679. - If the cursor is in a headline, prompt for tags and insert them
  18680. into the current line, aligned to `org-tags-column'. When called
  18681. with prefix arg, realign all tags in the current buffer.
  18682. - If the cursor is in one of the special #+KEYWORD lines, this
  18683. triggers scanning the buffer for these lines and updating the
  18684. information.
  18685. - If the cursor is inside a table, realign the table. This command
  18686. works even if the automatic table editor has been turned off.
  18687. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18688. the entire table.
  18689. - If the cursor is at a footnote reference or definition, jump to
  18690. the corresponding definition or references, respectively.
  18691. - If the cursor is a the beginning of a dynamic block, update it.
  18692. - If the current buffer is a capture buffer, close note and file it.
  18693. - If the cursor is on a <<<target>>>, update radio targets and
  18694. corresponding links in this buffer.
  18695. - If the cursor is on a numbered item in a plain list, renumber the
  18696. ordered list.
  18697. - If the cursor is on a checkbox, toggle it.
  18698. - If the cursor is on a code block, evaluate it. The variable
  18699. `org-confirm-babel-evaluate' can be used to control prompting
  18700. before code block evaluation, by default every code block
  18701. evaluation requires confirmation. Code block evaluation can be
  18702. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18703. (interactive "P")
  18704. (cond
  18705. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18706. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18707. (org-remove-occur-highlights)
  18708. (message "Temporary highlights/overlays removed from current buffer"))
  18709. ((and (local-variable-p 'org-finish-function)
  18710. (fboundp org-finish-function))
  18711. (funcall org-finish-function))
  18712. ((org-babel-hash-at-point))
  18713. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18714. (t
  18715. (let* ((context
  18716. (org-element-lineage
  18717. (org-element-context)
  18718. ;; Limit to supported contexts.
  18719. '(babel-call clock dynamic-block footnote-definition
  18720. footnote-reference inline-babel-call inline-src-block
  18721. inlinetask item keyword node-property paragraph
  18722. plain-list planning property-drawer radio-target
  18723. src-block statistics-cookie table table-cell table-row
  18724. timestamp)
  18725. t))
  18726. (type (org-element-type context)))
  18727. ;; For convenience: at the first line of a paragraph on the same
  18728. ;; line as an item, apply function on that item instead.
  18729. (when (eq type 'paragraph)
  18730. (let ((parent (org-element-property :parent context)))
  18731. (when (and (eq (org-element-type parent) 'item)
  18732. (= (line-beginning-position)
  18733. (org-element-property :begin parent)))
  18734. (setq context parent)
  18735. (setq type 'item))))
  18736. ;; Act according to type of element or object at point.
  18737. ;;
  18738. ;; Do nothing on a blank line, except if it is contained in
  18739. ;; a src block. Hence, we first check if point is in such
  18740. ;; a block and then if it is at a blank line.
  18741. (pcase type
  18742. ((or `inline-src-block `src-block)
  18743. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18744. (org-babel-eval-wipe-error-buffer)
  18745. (org-babel-execute-src-block
  18746. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18747. ((guard (org-match-line "[ \t]*$"))
  18748. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18749. (user-error
  18750. (substitute-command-keys
  18751. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18752. ((or `babel-call `inline-babel-call)
  18753. (let ((info (org-babel-lob-get-info context)))
  18754. (when info (org-babel-execute-src-block nil info))))
  18755. (`clock (org-clock-update-time-maybe))
  18756. (`dynamic-block
  18757. (save-excursion
  18758. (goto-char (org-element-property :post-affiliated context))
  18759. (org-update-dblock)))
  18760. (`footnote-definition
  18761. (goto-char (org-element-property :post-affiliated context))
  18762. (call-interactively 'org-footnote-action))
  18763. (`footnote-reference (call-interactively #'org-footnote-action))
  18764. ((or `headline `inlinetask)
  18765. (save-excursion (goto-char (org-element-property :begin context))
  18766. (call-interactively #'org-set-tags)))
  18767. (`item
  18768. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18769. ;; unconditionally, whereas `C-u' will toggle its presence.
  18770. ;; Without a universal argument, if the item has a checkbox,
  18771. ;; toggle it. Otherwise repair the list.
  18772. (let* ((box (org-element-property :checkbox context))
  18773. (struct (org-element-property :structure context))
  18774. (old-struct (copy-tree struct))
  18775. (parents (org-list-parents-alist struct))
  18776. (prevs (org-list-prevs-alist struct))
  18777. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18778. (org-list-set-checkbox
  18779. (org-element-property :begin context) struct
  18780. (cond ((equal arg '(16)) "[-]")
  18781. ((and (not box) (equal arg '(4))) "[ ]")
  18782. ((or (not box) (equal arg '(4))) nil)
  18783. ((eq box 'on) "[ ]")
  18784. (t "[X]")))
  18785. ;; Mimic `org-list-write-struct' but with grabbing a return
  18786. ;; value from `org-list-struct-fix-box'.
  18787. (org-list-struct-fix-ind struct parents 2)
  18788. (org-list-struct-fix-item-end struct)
  18789. (org-list-struct-fix-bul struct prevs)
  18790. (org-list-struct-fix-ind struct parents)
  18791. (let ((block-item
  18792. (org-list-struct-fix-box struct parents prevs orderedp)))
  18793. (if (and box (equal struct old-struct))
  18794. (if (equal arg '(16))
  18795. (message "Checkboxes already reset")
  18796. (user-error "Cannot toggle this checkbox: %s"
  18797. (if (eq box 'on)
  18798. "all subitems checked"
  18799. "unchecked subitems")))
  18800. (org-list-struct-apply-struct struct old-struct)
  18801. (org-update-checkbox-count-maybe))
  18802. (when block-item
  18803. (message "Checkboxes were removed due to empty box at line %d"
  18804. (org-current-line block-item))))))
  18805. (`keyword
  18806. (let ((org-inhibit-startup-visibility-stuff t)
  18807. (org-startup-align-all-tables nil))
  18808. (when (boundp 'org-table-coordinate-overlays)
  18809. (mapc #'delete-overlay org-table-coordinate-overlays)
  18810. (setq org-table-coordinate-overlays nil))
  18811. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18812. (message "Local setup has been refreshed"))
  18813. (`plain-list
  18814. ;; At a plain list, with a double C-u argument, set
  18815. ;; checkboxes of each item to "[-]", whereas a single one
  18816. ;; will toggle their presence according to the state of the
  18817. ;; first item in the list. Without an argument, repair the
  18818. ;; list.
  18819. (let* ((begin (org-element-property :contents-begin context))
  18820. (beginm (move-marker (make-marker) begin))
  18821. (struct (org-element-property :structure context))
  18822. (old-struct (copy-tree struct))
  18823. (first-box (save-excursion
  18824. (goto-char begin)
  18825. (looking-at org-list-full-item-re)
  18826. (match-string-no-properties 3)))
  18827. (new-box (cond ((equal arg '(16)) "[-]")
  18828. ((equal arg '(4)) (unless first-box "[ ]"))
  18829. ((equal first-box "[X]") "[ ]")
  18830. (t "[X]"))))
  18831. (cond
  18832. (arg
  18833. (dolist (pos
  18834. (org-list-get-all-items
  18835. begin struct (org-list-prevs-alist struct)))
  18836. (org-list-set-checkbox pos struct new-box)))
  18837. ((and first-box (eq (point) begin))
  18838. ;; For convenience, when point is at bol on the first
  18839. ;; item of the list and no argument is provided, simply
  18840. ;; toggle checkbox of that item, if any.
  18841. (org-list-set-checkbox begin struct new-box)))
  18842. (org-list-write-struct
  18843. struct (org-list-parents-alist struct) old-struct)
  18844. (org-update-checkbox-count-maybe)
  18845. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  18846. ((or `property-drawer `node-property)
  18847. (call-interactively #'org-property-action))
  18848. (`radio-target
  18849. (call-interactively #'org-update-radio-target-regexp))
  18850. (`statistics-cookie
  18851. (call-interactively #'org-update-statistics-cookies))
  18852. ((or `table `table-cell `table-row)
  18853. ;; At a table, recalculate every field and align it. Also
  18854. ;; send the table if necessary. If the table has
  18855. ;; a `table.el' type, just give up. At a table row or cell,
  18856. ;; maybe recalculate line but always align table.
  18857. (if (eq (org-element-property :type context) 'table.el)
  18858. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18859. Use `\\[org-edit-special]' to edit table.el tables"))
  18860. (if (or (eq type 'table)
  18861. ;; Check if point is at a TBLFM line.
  18862. (and (eq type 'table-row)
  18863. (= (point) (org-element-property :end context))))
  18864. (save-excursion
  18865. (if (org-at-TBLFM-p)
  18866. (progn (require 'org-table)
  18867. (org-table-calc-current-TBLFM))
  18868. (goto-char (org-element-property :contents-begin context))
  18869. (org-call-with-arg 'org-table-recalculate (or arg t))
  18870. (orgtbl-send-table 'maybe)))
  18871. (org-table-maybe-eval-formula)
  18872. (cond (arg (call-interactively #'org-table-recalculate))
  18873. ((org-table-maybe-recalculate-line))
  18874. (t (org-table-align))))))
  18875. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18876. (org-timestamp-change 0 'day))
  18877. ((and `nil (guard (org-at-heading-p)))
  18878. ;; When point is on an unsupported object type, we can miss
  18879. ;; the fact that it also is at a heading. Handle it here.
  18880. (call-interactively #'org-set-tags))
  18881. ((guard
  18882. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18883. (_
  18884. (user-error
  18885. (substitute-command-keys
  18886. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18887. (defun org-mode-restart ()
  18888. (interactive)
  18889. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18890. (funcall major-mode)
  18891. (hack-local-variables)
  18892. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18893. (org-indent-mode -1))
  18894. (org-reset-file-cache))
  18895. (message "%s restarted" major-mode))
  18896. (defun org-kill-note-or-show-branches ()
  18897. "Abort storing current note, or call `outline-show-branches'."
  18898. (interactive)
  18899. (if (not org-finish-function)
  18900. (progn
  18901. (outline-hide-subtree)
  18902. (call-interactively 'outline-show-branches))
  18903. (let ((org-note-abort t))
  18904. (funcall org-finish-function))))
  18905. (defun org-delete-indentation (&optional arg)
  18906. "Join current line to previous and fix whitespace at join.
  18907. If previous line is a headline add to headline title. Otherwise
  18908. the function calls `delete-indentation'.
  18909. With a non-nil optional argument, join it to the following one."
  18910. (interactive "*P")
  18911. (if (save-excursion
  18912. (beginning-of-line (if arg 1 0))
  18913. (let ((case-fold-search nil))
  18914. (looking-at org-complex-heading-regexp)))
  18915. ;; At headline.
  18916. (let ((tags-column (when (match-beginning 5)
  18917. (save-excursion (goto-char (match-beginning 5))
  18918. (current-column))))
  18919. (string (concat " " (progn (when arg (forward-line 1))
  18920. (org-trim (delete-and-extract-region
  18921. (line-beginning-position)
  18922. (line-end-position)))))))
  18923. (unless (bobp) (delete-region (point) (1- (point))))
  18924. (goto-char (or (match-end 4)
  18925. (match-beginning 5)
  18926. (match-end 0)))
  18927. (skip-chars-backward " \t")
  18928. (save-excursion (insert string))
  18929. ;; Adjust alignment of tags.
  18930. (cond
  18931. ((not tags-column)) ;no tags
  18932. (org-auto-align-tags (org-set-tags nil t))
  18933. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18934. (delete-indentation arg)))
  18935. (defun org-open-line (n)
  18936. "Insert a new row in tables, call `open-line' elsewhere.
  18937. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18938. As a special case, when a document starts with a table, allow to
  18939. call `open-line' on the very first character."
  18940. (interactive "*p")
  18941. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18942. (org-table-insert-row)
  18943. (open-line n)))
  18944. (defun org-return (&optional indent)
  18945. "Goto next table row or insert a newline.
  18946. Calls `org-table-next-row' or `newline', depending on context.
  18947. When optional INDENT argument is non-nil, call
  18948. `newline-and-indent' instead of `newline'.
  18949. When `org-return-follows-link' is non-nil and point is on
  18950. a timestamp or a link, call `org-open-at-point'. However, it
  18951. will not happen if point is in a table or on a \"dead\"
  18952. object (e.g., within a comment). In these case, you need to use
  18953. `org-open-at-point' directly."
  18954. (interactive)
  18955. (let ((context (if org-return-follows-link (org-element-context)
  18956. (org-element-at-point))))
  18957. (cond
  18958. ;; In a table, call `org-table-next-row'. However, before first
  18959. ;; column or after last one, split the table.
  18960. ((or (and (eq (org-element-type context) 'table)
  18961. (>= (point) (org-element-property :contents-begin context))
  18962. (< (point) (org-element-property :contents-end context)))
  18963. (org-element-lineage context '(table-row table-cell) t))
  18964. (if (or (looking-at-p "[ \t]*$")
  18965. (save-excursion (skip-chars-backward " \t") (bolp)))
  18966. (insert "\n")
  18967. (org-table-justify-field-maybe)
  18968. (call-interactively #'org-table-next-row)))
  18969. ;; On a link or a timestamp, call `org-open-at-point' if
  18970. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18971. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18972. ((and org-return-follows-link
  18973. (or (org-in-regexp org-ts-regexp-both nil t)
  18974. (org-in-regexp org-tsr-regexp-both nil t)
  18975. (org-in-regexp org-any-link-re nil t)))
  18976. (call-interactively #'org-open-at-point))
  18977. ;; Insert newline in heading, but preserve tags.
  18978. ((and (not (bolp))
  18979. (save-excursion (beginning-of-line)
  18980. (let ((case-fold-search nil))
  18981. (looking-at org-complex-heading-regexp))))
  18982. ;; At headline. Split line. However, if point is on keyword,
  18983. ;; priority cookie or tags, do not break any of them: add
  18984. ;; a newline after the headline instead.
  18985. (let ((tags-column (and (match-beginning 5)
  18986. (save-excursion (goto-char (match-beginning 5))
  18987. (current-column))))
  18988. (string
  18989. (when (and (match-end 4) (org-point-in-group (point) 4))
  18990. (delete-and-extract-region (point) (match-end 4)))))
  18991. ;; Adjust tag alignment.
  18992. (cond
  18993. ((not (and tags-column string)))
  18994. (org-auto-align-tags (org-set-tags nil t))
  18995. (t (org--align-tags-here tags-column))) ;preserve tags column
  18996. (end-of-line)
  18997. (org-show-entry)
  18998. (if indent (newline-and-indent) (newline))
  18999. (when string (save-excursion (insert (org-trim string))))))
  19000. ;; In a list, make sure indenting keeps trailing text within.
  19001. ((and indent
  19002. (not (eolp))
  19003. (org-element-lineage context '(item)))
  19004. (let ((trailing-data
  19005. (delete-and-extract-region (point) (line-end-position))))
  19006. (newline-and-indent)
  19007. (save-excursion (insert trailing-data))))
  19008. (t (if indent (newline-and-indent) (newline))))))
  19009. (defun org-return-indent ()
  19010. "Goto next table row or insert a newline and indent.
  19011. Calls `org-table-next-row' or `newline-and-indent', depending on
  19012. context. See the individual commands for more information."
  19013. (interactive)
  19014. (org-return t))
  19015. (defun org-ctrl-c-tab (&optional _arg)
  19016. "Toggle columns width in a table, or show children.
  19017. Call `org-table-toggle-column-width' if point is in a table.
  19018. Otherwise, call `org-show-children'."
  19019. (interactive "p")
  19020. (call-interactively
  19021. (if (org-at-table-p) #'org-table-toggle-column-width
  19022. #'org-show-children)))
  19023. (defun org-ctrl-c-star ()
  19024. "Compute table, or change heading status of lines.
  19025. Calls `org-table-recalculate' or `org-toggle-heading',
  19026. depending on context."
  19027. (interactive)
  19028. (cond
  19029. ((org-at-table-p)
  19030. (call-interactively 'org-table-recalculate))
  19031. (t
  19032. ;; Convert all lines in region to list items
  19033. (call-interactively 'org-toggle-heading))))
  19034. (defun org-ctrl-c-minus ()
  19035. "Insert separator line in table or modify bullet status of line.
  19036. Also turns a plain line or a region of lines into list items.
  19037. Calls `org-table-insert-hline', `org-toggle-item', or
  19038. `org-cycle-list-bullet', depending on context."
  19039. (interactive)
  19040. (cond
  19041. ((org-at-table-p)
  19042. (call-interactively 'org-table-insert-hline))
  19043. ((org-region-active-p)
  19044. (call-interactively 'org-toggle-item))
  19045. ((org-in-item-p)
  19046. (call-interactively 'org-cycle-list-bullet))
  19047. (t
  19048. (call-interactively 'org-toggle-item))))
  19049. (defun org-toggle-heading (&optional nstars)
  19050. "Convert headings to normal text, or items or text to headings.
  19051. If there is no active region, only convert the current line.
  19052. With a `\\[universal-argument]' prefix, convert the whole list at
  19053. point into heading.
  19054. In a region:
  19055. - If the first non blank line is a headline, remove the stars
  19056. from all headlines in the region.
  19057. - If it is a normal line, turn each and every normal line (i.e.,
  19058. not an heading or an item) in the region into headings. If you
  19059. want to convert only the first line of this region, use one
  19060. universal prefix argument.
  19061. - If it is a plain list item, turn all plain list items into headings.
  19062. When converting a line into a heading, the number of stars is chosen
  19063. such that the lines become children of the current entry. However,
  19064. when a numeric prefix argument is given, its value determines the
  19065. number of stars to add."
  19066. (interactive "P")
  19067. (let ((skip-blanks
  19068. (function
  19069. ;; Return beginning of first non-blank line, starting from
  19070. ;; line at POS.
  19071. (lambda (pos)
  19072. (save-excursion
  19073. (goto-char pos)
  19074. (while (org-at-comment-p) (forward-line))
  19075. (skip-chars-forward " \r\t\n")
  19076. (point-at-bol)))))
  19077. beg end toggled)
  19078. ;; Determine boundaries of changes. If a universal prefix has
  19079. ;; been given, put the list in a region. If region ends at a bol,
  19080. ;; do not consider the last line to be in the region.
  19081. (when (and current-prefix-arg (org-at-item-p))
  19082. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19083. (org-mark-element))
  19084. (if (org-region-active-p)
  19085. (setq beg (funcall skip-blanks (region-beginning))
  19086. end (copy-marker (save-excursion
  19087. (goto-char (region-end))
  19088. (if (bolp) (point) (point-at-eol)))))
  19089. (setq beg (funcall skip-blanks (point-at-bol))
  19090. end (copy-marker (point-at-eol))))
  19091. ;; Ensure inline tasks don't count as headings.
  19092. (org-with-limited-levels
  19093. (save-excursion
  19094. (goto-char beg)
  19095. (cond
  19096. ;; Case 1. Started at an heading: de-star headings.
  19097. ((org-at-heading-p)
  19098. (while (< (point) end)
  19099. (when (org-at-heading-p t)
  19100. (looking-at org-outline-regexp) (replace-match "")
  19101. (setq toggled t))
  19102. (forward-line)))
  19103. ;; Case 2. Started at an item: change items into headlines.
  19104. ;; One star will be added by `org-list-to-subtree'.
  19105. ((org-at-item-p)
  19106. (while (< (point) end)
  19107. (when (org-at-item-p)
  19108. ;; Pay attention to cases when region ends before list.
  19109. (let* ((struct (org-list-struct))
  19110. (list-end
  19111. (min (org-list-get-bottom-point struct) (1+ end))))
  19112. (save-restriction
  19113. (narrow-to-region (point) list-end)
  19114. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19115. (setq toggled t))
  19116. (forward-line)))
  19117. ;; Case 3. Started at normal text: make every line an heading,
  19118. ;; skipping headlines and items.
  19119. (t (let* ((stars
  19120. (make-string
  19121. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19122. (add-stars
  19123. (cond (nstars "") ; stars from prefix only
  19124. ((equal stars "") "*") ; before first heading
  19125. (org-odd-levels-only "**") ; inside heading, odd
  19126. (t "*"))) ; inside heading, oddeven
  19127. (rpl (concat stars add-stars " "))
  19128. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19129. (while (< (point) (if (equal nstars '(4)) lend end))
  19130. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19131. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19132. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19133. (forward-line)))))))
  19134. (unless toggled (message "Cannot toggle heading from here"))))
  19135. (defun org-meta-return (&optional arg)
  19136. "Insert a new heading or wrap a region in a table.
  19137. Calls `org-insert-heading', `org-insert-item' or
  19138. `org-table-wrap-region', depending on context. When called with
  19139. an argument, unconditionally call `org-insert-heading'."
  19140. (interactive "P")
  19141. (org-check-before-invisible-edit 'insert)
  19142. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19143. (call-interactively (cond (arg #'org-insert-heading)
  19144. ((org-at-table-p) #'org-table-wrap-region)
  19145. ((org-in-item-p) #'org-insert-item)
  19146. (t #'org-insert-heading)))))
  19147. ;;; Menu entries
  19148. (defsubst org-in-subtree-not-table-p ()
  19149. "Are we in a subtree and not in a table?"
  19150. (and (not (org-before-first-heading-p))
  19151. (not (org-at-table-p))))
  19152. ;; Define the Org mode menus
  19153. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19154. '("Tbl"
  19155. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19156. ["Next Field" org-cycle (org-at-table-p)]
  19157. ["Previous Field" org-shifttab (org-at-table-p)]
  19158. ["Next Row" org-return (org-at-table-p)]
  19159. "--"
  19160. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19161. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19162. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19163. "--"
  19164. ("Column"
  19165. ["Move Column Left" org-metaleft (org-at-table-p)]
  19166. ["Move Column Right" org-metaright (org-at-table-p)]
  19167. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19168. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  19169. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  19170. ("Row"
  19171. ["Move Row Up" org-metaup (org-at-table-p)]
  19172. ["Move Row Down" org-metadown (org-at-table-p)]
  19173. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19174. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19175. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19176. "--"
  19177. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19178. ("Rectangle"
  19179. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19180. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19181. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19182. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19183. "--"
  19184. ("Calculate"
  19185. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19186. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19187. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19188. "--"
  19189. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19190. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19191. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19192. "--"
  19193. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19194. "--"
  19195. ["Sum Column/Rectangle" org-table-sum
  19196. (or (org-at-table-p) (org-region-active-p))]
  19197. ["Which Column?" org-table-current-column (org-at-table-p)])
  19198. ["Debug Formulas"
  19199. org-table-toggle-formula-debugger
  19200. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19201. ["Show Col/Row Numbers"
  19202. org-table-toggle-coordinate-overlays
  19203. :style toggle
  19204. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19205. "--"
  19206. ["Create" org-table-create (not (org-at-table-p))]
  19207. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19208. ["Import from File" org-table-import (not (org-at-table-p))]
  19209. ["Export to File" org-table-export (org-at-table-p)]
  19210. "--"
  19211. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19212. "--"
  19213. ("Plot"
  19214. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19215. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19216. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19217. '("Org"
  19218. ("Show/Hide"
  19219. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19220. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19221. ["Sparse Tree..." org-sparse-tree t]
  19222. ["Reveal Context" org-reveal t]
  19223. ["Show All" outline-show-all t]
  19224. "--"
  19225. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19226. "--"
  19227. ["New Heading" org-insert-heading t]
  19228. ("Navigate Headings"
  19229. ["Up" outline-up-heading t]
  19230. ["Next" outline-next-visible-heading t]
  19231. ["Previous" outline-previous-visible-heading t]
  19232. ["Next Same Level" outline-forward-same-level t]
  19233. ["Previous Same Level" outline-backward-same-level t]
  19234. "--"
  19235. ["Jump" org-goto t])
  19236. ("Edit Structure"
  19237. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19238. "--"
  19239. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19240. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19241. "--"
  19242. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19243. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19244. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19245. "--"
  19246. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19247. "--"
  19248. ["Copy visible text" org-copy-visible t]
  19249. "--"
  19250. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19251. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19252. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19253. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19254. "--"
  19255. ["Sort Region/Children" org-sort t]
  19256. "--"
  19257. ["Convert to odd levels" org-convert-to-odd-levels t]
  19258. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19259. ("Editing"
  19260. ["Emphasis..." org-emphasize t]
  19261. ["Edit Source Example" org-edit-special t]
  19262. "--"
  19263. ["Footnote new/jump" org-footnote-action t]
  19264. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19265. ("Archive"
  19266. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19267. "--"
  19268. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19269. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19270. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19271. )
  19272. "--"
  19273. ("Hyperlinks"
  19274. ["Store Link (Global)" org-store-link t]
  19275. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19276. ["Insert Link" org-insert-link t]
  19277. ["Follow Link" org-open-at-point t]
  19278. "--"
  19279. ["Next link" org-next-link t]
  19280. ["Previous link" org-previous-link t]
  19281. "--"
  19282. ["Descriptive Links"
  19283. org-toggle-link-display
  19284. :style radio
  19285. :selected org-descriptive-links
  19286. ]
  19287. ["Literal Links"
  19288. org-toggle-link-display
  19289. :style radio
  19290. :selected (not org-descriptive-links)])
  19291. "--"
  19292. ("TODO Lists"
  19293. ["TODO/DONE/-" org-todo t]
  19294. ("Select keyword"
  19295. ["Next keyword" org-shiftright (org-at-heading-p)]
  19296. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19297. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19298. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19299. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19300. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19301. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19302. "--"
  19303. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19304. :selected org-enforce-todo-dependencies :style toggle :active t]
  19305. "Settings for tree at point"
  19306. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19307. :selected (org-entry-get nil "ORDERED")
  19308. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19309. ["Do Children parallel" org-toggle-ordered-property :style radio
  19310. :selected (not (org-entry-get nil "ORDERED"))
  19311. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19312. "--"
  19313. ["Set Priority" org-priority t]
  19314. ["Priority Up" org-shiftup t]
  19315. ["Priority Down" org-shiftdown t]
  19316. "--"
  19317. ["Get news from all feeds" org-feed-update-all t]
  19318. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19319. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19320. ("TAGS and Properties"
  19321. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19322. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19323. "--"
  19324. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19325. ["Column view of properties" org-columns t]
  19326. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19327. ("Dates and Scheduling"
  19328. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19329. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19330. ("Change Date"
  19331. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19332. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19333. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19334. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19335. ["Compute Time Range" org-evaluate-time-range t]
  19336. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19337. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19338. "--"
  19339. ["Custom time format" org-toggle-time-stamp-overlays
  19340. :style radio :selected org-display-custom-times]
  19341. "--"
  19342. ["Goto Calendar" org-goto-calendar t]
  19343. ["Date from Calendar" org-date-from-calendar t]
  19344. "--"
  19345. ["Start/Restart Timer" org-timer-start t]
  19346. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19347. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19348. ["Insert Timer String" org-timer t]
  19349. ["Insert Timer Item" org-timer-item t])
  19350. ("Logging work"
  19351. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19352. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19353. ["Clock out" org-clock-out t]
  19354. ["Clock cancel" org-clock-cancel t]
  19355. "--"
  19356. ["Mark as default task" org-clock-mark-default-task t]
  19357. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19358. ["Goto running clock" org-clock-goto t]
  19359. "--"
  19360. ["Display times" org-clock-display t]
  19361. ["Create clock table" org-clock-report t]
  19362. "--"
  19363. ["Record DONE time"
  19364. (progn (setq org-log-done (not org-log-done))
  19365. (message "Switching to %s will %s record a timestamp"
  19366. (car org-done-keywords)
  19367. (if org-log-done "automatically" "not")))
  19368. :style toggle :selected org-log-done])
  19369. "--"
  19370. ["Agenda Command..." org-agenda t]
  19371. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19372. ("File List for Agenda")
  19373. ("Special views current file"
  19374. ["TODO Tree" org-show-todo-tree t]
  19375. ["Check Deadlines" org-check-deadlines t]
  19376. ["Tags/Property tree" org-match-sparse-tree t])
  19377. "--"
  19378. ["Export/Publish..." org-export-dispatch t]
  19379. ("LaTeX"
  19380. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19381. :selected org-cdlatex-mode]
  19382. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19383. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19384. ["Modify math symbol" org-cdlatex-math-modify
  19385. (org-inside-LaTeX-fragment-p)]
  19386. ["Insert citation" org-reftex-citation t])
  19387. "--"
  19388. ("MobileOrg"
  19389. ["Push Files and Views" org-mobile-push t]
  19390. ["Get Captured and Flagged" org-mobile-pull t]
  19391. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19392. "--"
  19393. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19394. "--"
  19395. ("Documentation"
  19396. ["Show Version" org-version t]
  19397. ["Info Documentation" org-info t])
  19398. ("Customize"
  19399. ["Browse Org Group" org-customize t]
  19400. "--"
  19401. ["Expand This Menu" org-create-customize-menu
  19402. (fboundp 'customize-menu-create)])
  19403. ["Send bug report" org-submit-bug-report t]
  19404. "--"
  19405. ("Refresh/Reload"
  19406. ["Refresh setup current buffer" org-mode-restart t]
  19407. ["Reload Org (after update)" org-reload t]
  19408. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19409. ))
  19410. (defun org-info (&optional node)
  19411. "Read documentation for Org in the info system.
  19412. With optional NODE, go directly to that node."
  19413. (interactive)
  19414. (info (format "(org)%s" (or node ""))))
  19415. ;;;###autoload
  19416. (defun org-submit-bug-report ()
  19417. "Submit a bug report on Org via mail.
  19418. Don't hesitate to report any problems or inaccurate documentation.
  19419. If you don't have setup sending mail from (X)Emacs, please copy the
  19420. output buffer into your mail program, as it gives us important
  19421. information about your Org version and configuration."
  19422. (interactive)
  19423. (require 'reporter)
  19424. (defvar reporter-prompt-for-summary-p)
  19425. (org-load-modules-maybe)
  19426. (org-require-autoloaded-modules)
  19427. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19428. (reporter-submit-bug-report
  19429. "emacs-orgmode@gnu.org"
  19430. (org-version nil 'full)
  19431. (let (list)
  19432. (save-window-excursion
  19433. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19434. (delete-other-windows)
  19435. (erase-buffer)
  19436. (insert "You are about to submit a bug report to the Org mailing list.
  19437. We would like to add your full Org and Outline configuration to the
  19438. bug report. This greatly simplifies the work of the maintainer and
  19439. other experts on the mailing list.
  19440. HOWEVER, some variables you have customized may contain private
  19441. information. The names of customers, colleagues, or friends, might
  19442. appear in the form of file names, tags, todo states, or search strings.
  19443. If you answer yes to the prompt, you might want to check and remove
  19444. such private information before sending the email.")
  19445. (add-text-properties (point-min) (point-max) '(face org-warning))
  19446. (when (yes-or-no-p "Include your Org configuration ")
  19447. (mapatoms
  19448. (lambda (v)
  19449. (and (boundp v)
  19450. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19451. (or (and (symbol-value v)
  19452. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19453. (and
  19454. (get v 'custom-type) (get v 'standard-value)
  19455. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19456. (push v list)))))
  19457. (kill-buffer (get-buffer "*Warn about privacy*"))
  19458. list))
  19459. nil nil
  19460. "Remember to cover the basics, that is, what you expected to happen and
  19461. what in fact did happen. You don't know how to make a good report? See
  19462. http://orgmode.org/manual/Feedback.html#Feedback
  19463. Your bug report will be posted to the Org mailing list.
  19464. ------------------------------------------------------------------------")
  19465. (save-excursion
  19466. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19467. (replace-match "\\1Bug: \\3 [\\2]")))))
  19468. (defun org-install-agenda-files-menu ()
  19469. (let ((bl (buffer-list)))
  19470. (save-excursion
  19471. (while bl
  19472. (set-buffer (pop bl))
  19473. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19474. (when (derived-mode-p 'org-mode)
  19475. (easy-menu-change
  19476. '("Org") "File List for Agenda"
  19477. (append
  19478. (list
  19479. ["Edit File List" (org-edit-agenda-file-list) t]
  19480. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19481. ["Remove Current File from List" org-remove-file t]
  19482. ["Cycle through agenda files" org-cycle-agenda-files t]
  19483. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19484. "--")
  19485. (mapcar 'org-file-menu-entry
  19486. ;; Prevent initialization from failing.
  19487. (ignore-errors (org-agenda-files t)))))))))
  19488. ;;;; Documentation
  19489. (defun org-require-autoloaded-modules ()
  19490. (interactive)
  19491. (mapc #'require
  19492. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19493. org-table org-timer)))
  19494. ;;;###autoload
  19495. (defun org-reload (&optional uncompiled)
  19496. "Reload all org lisp files.
  19497. With prefix arg UNCOMPILED, load the uncompiled versions."
  19498. (interactive "P")
  19499. (require 'loadhist)
  19500. (let* ((org-dir (org-find-library-dir "org"))
  19501. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19502. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19503. (remove-re (format "\\`%s\\'"
  19504. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19505. (feats (delete-dups
  19506. (mapcar 'file-name-sans-extension
  19507. (mapcar 'file-name-nondirectory
  19508. (delq nil
  19509. (mapcar 'feature-file
  19510. features))))))
  19511. (lfeat (append
  19512. (sort
  19513. (setq feats
  19514. (delq nil (mapcar
  19515. (lambda (f)
  19516. (if (and (string-match feature-re f)
  19517. (not (string-match remove-re f)))
  19518. f nil))
  19519. feats)))
  19520. 'string-lessp)
  19521. (list "org-version" "org")))
  19522. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19523. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19524. load-uncore load-misses)
  19525. (setq load-misses
  19526. (delq 't
  19527. (mapcar (lambda (f)
  19528. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19529. (and (string= org-dir contrib-dir)
  19530. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19531. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19532. (add-to-list 'load-uncore f 'append)
  19533. 't)
  19534. f))
  19535. lfeat)))
  19536. (when load-uncore
  19537. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19538. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19539. (if load-misses
  19540. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19541. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19542. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19543. ;;;###autoload
  19544. (defun org-customize ()
  19545. "Call the customize function with org as argument."
  19546. (interactive)
  19547. (org-load-modules-maybe)
  19548. (org-require-autoloaded-modules)
  19549. (customize-browse 'org))
  19550. (defun org-create-customize-menu ()
  19551. "Create a full customization menu for Org mode, insert it into the menu."
  19552. (interactive)
  19553. (org-load-modules-maybe)
  19554. (org-require-autoloaded-modules)
  19555. (if (fboundp 'customize-menu-create)
  19556. (progn
  19557. (easy-menu-change
  19558. '("Org") "Customize"
  19559. `(["Browse Org group" org-customize t]
  19560. "--"
  19561. ,(customize-menu-create 'org)
  19562. ["Set" Custom-set t]
  19563. ["Save" Custom-save t]
  19564. ["Reset to Current" Custom-reset-current t]
  19565. ["Reset to Saved" Custom-reset-saved t]
  19566. ["Reset to Standard Settings" Custom-reset-standard t]))
  19567. (message "\"Org\"-menu now contains full customization menu"))
  19568. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19569. ;;;; Miscellaneous stuff
  19570. ;;; Generally useful functions
  19571. (defun org-link-display-format (s)
  19572. "Replace links in string S with their description.
  19573. If there is no description, use the link target."
  19574. (save-match-data
  19575. (replace-regexp-in-string
  19576. org-bracket-link-analytic-regexp
  19577. (lambda (m)
  19578. (if (match-end 5) (match-string 5 m)
  19579. (concat (match-string 1 m) (match-string 3 m))))
  19580. s nil t)))
  19581. (defun org-toggle-link-display ()
  19582. "Toggle the literal or descriptive display of links."
  19583. (interactive)
  19584. (if org-descriptive-links
  19585. (progn (org-remove-from-invisibility-spec '(org-link))
  19586. (org-restart-font-lock)
  19587. (setq org-descriptive-links nil))
  19588. (progn (add-to-invisibility-spec '(org-link))
  19589. (org-restart-font-lock)
  19590. (setq org-descriptive-links t))))
  19591. (defun org-in-clocktable-p ()
  19592. "Check if the cursor is in a clocktable."
  19593. (let ((pos (point)) start)
  19594. (save-excursion
  19595. (end-of-line 1)
  19596. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19597. (setq start (match-beginning 0))
  19598. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19599. (>= (match-end 0) pos)
  19600. start))))
  19601. (defun org-in-verbatim-emphasis ()
  19602. (save-match-data
  19603. (and (org-in-regexp org-verbatim-re 2)
  19604. (>= (point) (match-beginning 3))
  19605. (<= (point) (match-end 4)))))
  19606. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19607. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19608. (if (and marker (marker-buffer marker)
  19609. (buffer-live-p (marker-buffer marker)))
  19610. (progn
  19611. (pop-to-buffer-same-window (marker-buffer marker))
  19612. (when (or (> marker (point-max)) (< marker (point-min)))
  19613. (widen))
  19614. (goto-char marker)
  19615. (org-show-context 'org-goto))
  19616. (if bookmark
  19617. (bookmark-jump bookmark)
  19618. (error "Cannot find location"))))
  19619. (defun org-quote-csv-field (s)
  19620. "Quote field for inclusion in CSV material."
  19621. (if (string-match "[\",]" s)
  19622. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19623. s))
  19624. (defun org-force-self-insert (N)
  19625. "Needed to enforce self-insert under remapping."
  19626. (interactive "p")
  19627. (self-insert-command N))
  19628. (defun org-get-indentation (&optional line)
  19629. "Get the indentation of the current line, interpreting tabs.
  19630. When LINE is given, assume it represents a line and compute its indentation."
  19631. (if line
  19632. (when (string-match "^ *" (org-remove-tabs line))
  19633. (match-end 0))
  19634. (save-excursion
  19635. (beginning-of-line 1)
  19636. (skip-chars-forward " \t")
  19637. (current-column))))
  19638. (defun org-get-string-indentation (s)
  19639. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19640. (let ((n -1) (i 0) (w tab-width) c)
  19641. (catch 'exit
  19642. (while (< (setq n (1+ n)) (length s))
  19643. (setq c (aref s n))
  19644. (cond ((= c ?\ ) (setq i (1+ i)))
  19645. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19646. (t (throw 'exit t)))))
  19647. i))
  19648. (defun org-fix-indentation (line ind)
  19649. "Fix indentation in LINE.
  19650. IND is a cons cell with target and minimum indentation.
  19651. If the current indentation in LINE is smaller than the minimum,
  19652. leave it alone. If it is larger than ind, set it to the target."
  19653. (let* ((l (org-remove-tabs line))
  19654. (i (org-get-indentation l))
  19655. (i1 (car ind)) (i2 (cdr ind)))
  19656. (when (>= i i2) (setq l (substring line i2)))
  19657. (if (> i1 0)
  19658. (concat (make-string i1 ?\ ) l)
  19659. l)))
  19660. (defun org-fill-template (template alist)
  19661. "Find each %key of ALIST in TEMPLATE and replace it."
  19662. (let ((case-fold-search nil))
  19663. (dolist (entry (sort (copy-sequence alist)
  19664. (lambda (a b) (< (length (car a)) (length (car b))))))
  19665. (setq template
  19666. (replace-regexp-in-string
  19667. (concat "%" (regexp-quote (car entry)))
  19668. (or (cdr entry) "") template t t)))
  19669. template))
  19670. (defun org-quote-vert (s)
  19671. "Replace \"|\" with \"\\vert\"."
  19672. (while (string-match "|" s)
  19673. (setq s (replace-match "\\vert" t t s)))
  19674. s)
  19675. (defun org-uuidgen-p (s)
  19676. "Is S an ID created by UUIDGEN?"
  19677. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19678. (defun org-in-src-block-p (&optional inside)
  19679. "Whether point is in a code source block.
  19680. When INSIDE is non-nil, don't consider we are within a src block
  19681. when point is at #+BEGIN_SRC or #+END_SRC."
  19682. (let ((case-fold-search t))
  19683. (or (and (eq (get-char-property (point) 'src-block) t))
  19684. (and (not inside)
  19685. (save-match-data
  19686. (save-excursion
  19687. (beginning-of-line)
  19688. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19689. (defun org-context ()
  19690. "Return a list of contexts of the current cursor position.
  19691. If several contexts apply, all are returned.
  19692. Each context entry is a list with a symbol naming the context, and
  19693. two positions indicating start and end of the context. Possible
  19694. contexts are:
  19695. :headline anywhere in a headline
  19696. :headline-stars on the leading stars in a headline
  19697. :todo-keyword on a TODO keyword (including DONE) in a headline
  19698. :tags on the TAGS in a headline
  19699. :priority on the priority cookie in a headline
  19700. :item on the first line of a plain list item
  19701. :item-bullet on the bullet/number of a plain list item
  19702. :checkbox on the checkbox in a plain list item
  19703. :table in an Org table
  19704. :table-special on a special filed in a table
  19705. :table-table in a table.el table
  19706. :clocktable in a clocktable
  19707. :src-block in a source block
  19708. :link on a hyperlink
  19709. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19710. :target on a <<target>>
  19711. :radio-target on a <<<radio-target>>>
  19712. :latex-fragment on a LaTeX fragment
  19713. :latex-preview on a LaTeX fragment with overlaid preview image
  19714. This function expects the position to be visible because it uses font-lock
  19715. faces as a help to recognize the following contexts: :table-special, :link,
  19716. and :keyword."
  19717. (let* ((f (get-text-property (point) 'face))
  19718. (faces (if (listp f) f (list f)))
  19719. (case-fold-search t)
  19720. (p (point)) clist o)
  19721. ;; First the large context
  19722. (cond
  19723. ((org-at-heading-p t)
  19724. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19725. (when (progn
  19726. (beginning-of-line 1)
  19727. (looking-at org-todo-line-tags-regexp))
  19728. (push (org-point-in-group p 1 :headline-stars) clist)
  19729. (push (org-point-in-group p 2 :todo-keyword) clist)
  19730. (push (org-point-in-group p 4 :tags) clist))
  19731. (goto-char p)
  19732. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19733. (when (looking-at "\\[#[A-Z0-9]\\]")
  19734. (push (org-point-in-group p 0 :priority) clist)))
  19735. ((org-at-item-p)
  19736. (push (org-point-in-group p 2 :item-bullet) clist)
  19737. (push (list :item (point-at-bol)
  19738. (save-excursion (org-end-of-item) (point)))
  19739. clist)
  19740. (and (org-at-item-checkbox-p)
  19741. (push (org-point-in-group p 0 :checkbox) clist)))
  19742. ((org-at-table-p)
  19743. (push (list :table (org-table-begin) (org-table-end)) clist)
  19744. (when (memq 'org-formula faces)
  19745. (push (list :table-special
  19746. (previous-single-property-change p 'face)
  19747. (next-single-property-change p 'face)) clist)))
  19748. ((org-at-table-p 'any)
  19749. (push (list :table-table) clist)))
  19750. (goto-char p)
  19751. (let ((case-fold-search t))
  19752. ;; New the "medium" contexts: clocktables, source blocks
  19753. (cond ((org-in-clocktable-p)
  19754. (push (list :clocktable
  19755. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19756. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19757. (match-beginning 1))
  19758. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19759. (match-end 0))) clist))
  19760. ((org-in-src-block-p)
  19761. (push (list :src-block
  19762. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19763. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19764. (match-beginning 1))
  19765. (and (search-forward "#+END_SRC" nil t)
  19766. (match-beginning 0))) clist))))
  19767. (goto-char p)
  19768. ;; Now the small context
  19769. (cond
  19770. ((org-at-timestamp-p)
  19771. (push (org-point-in-group p 0 :timestamp) clist))
  19772. ((memq 'org-link faces)
  19773. (push (list :link
  19774. (previous-single-property-change p 'face)
  19775. (next-single-property-change p 'face)) clist))
  19776. ((memq 'org-special-keyword faces)
  19777. (push (list :keyword
  19778. (previous-single-property-change p 'face)
  19779. (next-single-property-change p 'face)) clist))
  19780. ((org-at-target-p)
  19781. (push (org-point-in-group p 0 :target) clist)
  19782. (goto-char (1- (match-beginning 0)))
  19783. (when (looking-at org-radio-target-regexp)
  19784. (push (org-point-in-group p 0 :radio-target) clist))
  19785. (goto-char p))
  19786. ((setq o (cl-some
  19787. (lambda (o)
  19788. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19789. o))
  19790. (overlays-at (point))))
  19791. (push (list :latex-fragment
  19792. (overlay-start o) (overlay-end o)) clist)
  19793. (push (list :latex-preview
  19794. (overlay-start o) (overlay-end o)) clist))
  19795. ((org-inside-LaTeX-fragment-p)
  19796. ;; FIXME: positions wrong.
  19797. (push (list :latex-fragment (point) (point)) clist)))
  19798. (setq clist (nreverse (delq nil clist)))
  19799. clist))
  19800. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19801. "Non-nil when point is between matches of START-RE and END-RE.
  19802. Also return a non-nil value when point is on one of the matches.
  19803. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19804. buffer positions. Default values are the positions of headlines
  19805. surrounding the point.
  19806. The functions returns a cons cell whose car (resp. cdr) is the
  19807. position before START-RE (resp. after END-RE)."
  19808. (save-match-data
  19809. (let ((pos (point))
  19810. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19811. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19812. beg end)
  19813. (save-excursion
  19814. ;; Point is on a block when on START-RE or if START-RE can be
  19815. ;; found before it...
  19816. (and (or (org-in-regexp start-re)
  19817. (re-search-backward start-re limit-up t))
  19818. (setq beg (match-beginning 0))
  19819. ;; ... and END-RE after it...
  19820. (goto-char (match-end 0))
  19821. (re-search-forward end-re limit-down t)
  19822. (> (setq end (match-end 0)) pos)
  19823. ;; ... without another START-RE in-between.
  19824. (goto-char (match-beginning 0))
  19825. (not (re-search-backward start-re (1+ beg) t))
  19826. ;; Return value.
  19827. (cons beg end))))))
  19828. (defun org-in-block-p (names)
  19829. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19830. NAMES is a list of strings containing names of blocks.
  19831. Return first block name matched, or nil. Beware that in case of
  19832. nested blocks, the returned name may not belong to the closest
  19833. block from point."
  19834. (save-match-data
  19835. (catch 'exit
  19836. (let ((case-fold-search t)
  19837. (lim-up (save-excursion (outline-previous-heading)))
  19838. (lim-down (save-excursion (outline-next-heading))))
  19839. (dolist (name names)
  19840. (let ((n (regexp-quote name)))
  19841. (when (org-between-regexps-p
  19842. (concat "^[ \t]*#\\+begin_" n)
  19843. (concat "^[ \t]*#\\+end_" n)
  19844. lim-up lim-down)
  19845. (throw 'exit n)))))
  19846. nil)))
  19847. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19848. "Call `multi-occur' with buffers for all agenda files."
  19849. (interactive "sOrg-files matching: ")
  19850. (let* ((files (org-agenda-files))
  19851. (tnames (mapcar #'file-truename files))
  19852. (extra org-agenda-text-search-extra-files))
  19853. (when (eq (car extra) 'agenda-archives)
  19854. (setq extra (cdr extra))
  19855. (setq files (org-add-archive-files files)))
  19856. (dolist (f extra)
  19857. (unless (member (file-truename f) tnames)
  19858. (unless (member f files) (setq files (append files (list f))))
  19859. (setq tnames (append tnames (list (file-truename f))))))
  19860. (multi-occur
  19861. (mapcar (lambda (x)
  19862. (with-current-buffer
  19863. ;; FIXME: Why not just (find-file-noselect x)?
  19864. ;; Is it to avoid the "revert buffer" prompt?
  19865. (or (get-file-buffer x) (find-file-noselect x))
  19866. (widen)
  19867. (current-buffer)))
  19868. files)
  19869. regexp)))
  19870. (add-hook 'occur-mode-find-occurrence-hook
  19871. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19872. (defun org-occur-link-in-agenda-files ()
  19873. "Create a link and search for it in the agendas.
  19874. The link is not stored in `org-stored-links', it is just created
  19875. for the search purpose."
  19876. (interactive)
  19877. (let ((link (condition-case nil
  19878. (org-store-link nil)
  19879. (error "Unable to create a link to here"))))
  19880. (org-occur-in-agenda-files (regexp-quote link))))
  19881. (defun org-back-over-empty-lines ()
  19882. "Move backwards over whitespace, to the beginning of the first empty line.
  19883. Returns the number of empty lines passed."
  19884. (let ((pos (point)))
  19885. (if (cdr (assq 'heading org-blank-before-new-entry))
  19886. (skip-chars-backward " \t\n\r")
  19887. (unless (eobp)
  19888. (forward-line -1)))
  19889. (beginning-of-line 2)
  19890. (goto-char (min (point) pos))
  19891. (count-lines (point) pos)))
  19892. (defun org-switch-to-buffer-other-window (&rest args)
  19893. "Switch to buffer in a second window on the current frame.
  19894. In particular, do not allow pop-up frames.
  19895. Returns the newly created buffer."
  19896. (org-no-popups
  19897. (apply 'switch-to-buffer-other-window args)))
  19898. (defun org-replace-escapes (string table)
  19899. "Replace %-escapes in STRING with values in TABLE.
  19900. TABLE is an association list with keys like \"%a\" and string values.
  19901. The sequences in STRING may contain normal field width and padding information,
  19902. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19903. so values can contain further %-escapes if they are define later in TABLE."
  19904. (let ((tbl (copy-alist table))
  19905. (case-fold-search nil)
  19906. (pchg 0)
  19907. re rpl)
  19908. (dolist (e tbl)
  19909. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19910. (when (and (cdr e) (string-match re (cdr e)))
  19911. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19912. (safe "SREF"))
  19913. (add-text-properties 0 3 (list 'sref sref) safe)
  19914. (setcdr e (replace-match safe t t (cdr e)))))
  19915. (while (string-match re string)
  19916. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19917. (cdr e)))
  19918. (setq string (replace-match rpl t t string))))
  19919. (while (setq pchg (next-property-change pchg string))
  19920. (let ((sref (get-text-property pchg 'sref string)))
  19921. (when (and sref (string-match "SREF" string pchg))
  19922. (setq string (replace-match sref t t string)))))
  19923. string))
  19924. ;;; TODO: Only called once, from ox-odt which should probably use
  19925. ;;; org-export-inline-image-p or something.
  19926. (defun org-file-image-p (file)
  19927. "Return non-nil if FILE is an image."
  19928. (save-match-data
  19929. (string-match (image-file-name-regexp) file)))
  19930. (defun org-get-cursor-date (&optional with-time)
  19931. "Return the date at cursor in as a time.
  19932. This works in the calendar and in the agenda, anywhere else it just
  19933. returns the current time.
  19934. If WITH-TIME is non-nil, returns the time of the event at point (in
  19935. the agenda) or the current time of the day."
  19936. (let (date day defd tp hod mod)
  19937. (when with-time
  19938. (setq tp (get-text-property (point) 'time))
  19939. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19940. (setq hod (string-to-number (match-string 1 tp))
  19941. mod (string-to-number (match-string 2 tp))))
  19942. (or tp (let ((now (decode-time)))
  19943. (setq hod (nth 2 now)
  19944. mod (nth 1 now)))))
  19945. (cond
  19946. ((eq major-mode 'calendar-mode)
  19947. (setq date (calendar-cursor-to-date)
  19948. defd (encode-time 0 (or mod 0) (or hod 0)
  19949. (nth 1 date) (nth 0 date) (nth 2 date))))
  19950. ((eq major-mode 'org-agenda-mode)
  19951. (setq day (get-text-property (point) 'day))
  19952. (when day
  19953. (setq date (calendar-gregorian-from-absolute day)
  19954. defd (encode-time 0 (or mod 0) (or hod 0)
  19955. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19956. (or defd (current-time))))
  19957. (defun org-mark-subtree (&optional up)
  19958. "Mark the current subtree.
  19959. This puts point at the start of the current subtree, and mark at
  19960. the end. If a numeric prefix UP is given, move up into the
  19961. hierarchy of headlines by UP levels before marking the subtree."
  19962. (interactive "P")
  19963. (org-with-limited-levels
  19964. (cond ((org-at-heading-p) (beginning-of-line))
  19965. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19966. (t (outline-previous-visible-heading 1))))
  19967. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19968. (if (called-interactively-p 'any)
  19969. (call-interactively 'org-mark-element)
  19970. (org-mark-element)))
  19971. (defun org-file-newer-than-p (file time)
  19972. "Non-nil if FILE is newer than TIME.
  19973. FILE is a filename, as a string, TIME is a list of integers, as
  19974. returned by, e.g., `current-time'."
  19975. (and (file-exists-p file)
  19976. ;; Only compare times up to whole seconds as some file-systems
  19977. ;; (e.g. HFS+) do not retain any finer granularity. As
  19978. ;; a consequence, make sure we return non-nil when the two
  19979. ;; times are equal.
  19980. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  19981. (cl-subseq time 0 2)))))
  19982. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  19983. "Compile a SOURCE file using PROCESS.
  19984. PROCESS is either a function or a list of shell commands, as
  19985. strings. EXT is a file extension, without the leading dot, as
  19986. a string. It is used to check if the process actually succeeded.
  19987. PROCESS must create a file with the same base name and directory
  19988. as SOURCE, but ending with EXT. The function then returns its
  19989. filename. Otherwise, it raises an error. The error message can
  19990. then be refined by providing string ERR-MSG, which is appended to
  19991. the standard message.
  19992. If PROCESS is a function, it is called with a single argument:
  19993. the SOURCE file.
  19994. If it is a list of commands, each of them is called using
  19995. `shell-command'. By default, in each command, %b, %f, %F, %o and
  19996. %O are replaced with, respectively, SOURCE base name, name, full
  19997. name, directory and absolute output file name. It is possible,
  19998. however, to use more place-holders by specifying them in optional
  19999. argument SPEC, as an alist following the pattern
  20000. (CHARACTER . REPLACEMENT-STRING).
  20001. When PROCESS is a list of commands, optional argument LOG-BUF can
  20002. be set to a buffer or a buffer name. `shell-command' then uses
  20003. it for output."
  20004. (let* ((base-name (file-name-base source))
  20005. (full-name (file-truename source))
  20006. (out-dir (or (file-name-directory source) "./"))
  20007. (output (expand-file-name (concat base-name "." ext) out-dir))
  20008. (time (current-time))
  20009. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20010. (save-window-excursion
  20011. (pcase process
  20012. ((pred functionp) (funcall process (shell-quote-argument source)))
  20013. ((pred consp)
  20014. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20015. (spec (append spec
  20016. `((?b . ,(shell-quote-argument base-name))
  20017. (?f . ,(shell-quote-argument source))
  20018. (?F . ,(shell-quote-argument full-name))
  20019. (?o . ,(shell-quote-argument out-dir))
  20020. (?O . ,(shell-quote-argument output))))))
  20021. (dolist (command process)
  20022. (shell-command (format-spec command spec) log-buf))
  20023. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20024. (_ (error "No valid command to process %S%s" source err-msg))))
  20025. ;; Check for process failure. Output file is expected to be
  20026. ;; located in the same directory as SOURCE.
  20027. (unless (org-file-newer-than-p output time)
  20028. (error (format "File %S wasn't produced%s" output err-msg)))
  20029. output))
  20030. ;;; Indentation
  20031. (defvar org-element-greater-elements)
  20032. (defun org--get-expected-indentation (element contentsp)
  20033. "Expected indentation column for current line, according to ELEMENT.
  20034. ELEMENT is an element containing point. CONTENTSP is non-nil
  20035. when indentation is to be computed according to contents of
  20036. ELEMENT."
  20037. (let ((type (org-element-type element))
  20038. (start (org-element-property :begin element))
  20039. (post-affiliated (org-element-property :post-affiliated element)))
  20040. (org-with-wide-buffer
  20041. (cond
  20042. (contentsp
  20043. (cl-case type
  20044. ((diary-sexp footnote-definition) 0)
  20045. ((headline inlinetask nil)
  20046. (if (not org-adapt-indentation) 0
  20047. (let ((level (org-current-level)))
  20048. (if level (1+ level) 0))))
  20049. ((item plain-list) (org-list-item-body-column post-affiliated))
  20050. (t
  20051. (goto-char start)
  20052. (org-get-indentation))))
  20053. ((memq type '(headline inlinetask nil))
  20054. (if (org-match-line "[ \t]*$")
  20055. (org--get-expected-indentation element t)
  20056. 0))
  20057. ((memq type '(diary-sexp footnote-definition)) 0)
  20058. ;; First paragraph of a footnote definition or an item.
  20059. ;; Indent like parent.
  20060. ((< (line-beginning-position) start)
  20061. (org--get-expected-indentation
  20062. (org-element-property :parent element) t))
  20063. ;; At first line: indent according to previous sibling, if any,
  20064. ;; ignoring footnote definitions and inline tasks, or parent's
  20065. ;; contents.
  20066. ((= (line-beginning-position) start)
  20067. (catch 'exit
  20068. (while t
  20069. (if (= (point-min) start) (throw 'exit 0)
  20070. (goto-char (1- start))
  20071. (let* ((previous (org-element-at-point))
  20072. (parent previous))
  20073. (while (and parent (<= (org-element-property :end parent) start))
  20074. (setq previous parent
  20075. parent (org-element-property :parent parent)))
  20076. (cond
  20077. ((not previous) (throw 'exit 0))
  20078. ((> (org-element-property :end previous) start)
  20079. (throw 'exit (org--get-expected-indentation previous t)))
  20080. ((memq (org-element-type previous)
  20081. '(footnote-definition inlinetask))
  20082. (setq start (org-element-property :begin previous)))
  20083. (t (goto-char (org-element-property :begin previous))
  20084. (throw 'exit
  20085. (if (bolp) (org-get-indentation)
  20086. ;; At first paragraph in an item or
  20087. ;; a footnote definition.
  20088. (org--get-expected-indentation
  20089. (org-element-property :parent previous) t))))))))))
  20090. ;; Otherwise, move to the first non-blank line above.
  20091. (t
  20092. (beginning-of-line)
  20093. (let ((pos (point)))
  20094. (skip-chars-backward " \r\t\n")
  20095. (cond
  20096. ;; Two blank lines end a footnote definition or a plain
  20097. ;; list. When we indent an empty line after them, the
  20098. ;; containing list or footnote definition is over, so it
  20099. ;; qualifies as a previous sibling. Therefore, we indent
  20100. ;; like its first line.
  20101. ((and (memq type '(footnote-definition plain-list))
  20102. (> (count-lines (point) pos) 2))
  20103. (goto-char start)
  20104. (org-get-indentation))
  20105. ;; Line above is the first one of a paragraph at the
  20106. ;; beginning of an item or a footnote definition. Indent
  20107. ;; like parent.
  20108. ((< (line-beginning-position) start)
  20109. (org--get-expected-indentation
  20110. (org-element-property :parent element) t))
  20111. ;; Line above is the beginning of an element, i.e., point
  20112. ;; was originally on the blank lines between element's start
  20113. ;; and contents.
  20114. ((= (line-beginning-position) post-affiliated)
  20115. (org--get-expected-indentation element t))
  20116. ;; POS is after contents in a greater element. Indent like
  20117. ;; the beginning of the element.
  20118. ((and (memq type org-element-greater-elements)
  20119. (let ((cend (org-element-property :contents-end element)))
  20120. (and cend (<= cend pos))))
  20121. ;; As a special case, if point is at the end of a footnote
  20122. ;; definition or an item, indent like the very last element
  20123. ;; within. If that last element is an item, indent like
  20124. ;; its contents.
  20125. (if (memq type '(footnote-definition item plain-list))
  20126. (let ((last (org-element-at-point)))
  20127. (goto-char pos)
  20128. (org--get-expected-indentation
  20129. last (eq (org-element-type last) 'item)))
  20130. (goto-char start)
  20131. (org-get-indentation)))
  20132. ;; In any other case, indent like the current line.
  20133. (t (org-get-indentation)))))))))
  20134. (defun org--align-node-property ()
  20135. "Align node property at point.
  20136. Alignment is done according to `org-property-format', which see."
  20137. (when (save-excursion
  20138. (beginning-of-line)
  20139. (looking-at org-property-re))
  20140. (replace-match
  20141. (concat (match-string 4)
  20142. (org-trim
  20143. (format org-property-format (match-string 1) (match-string 3))))
  20144. t t)))
  20145. (defun org-indent-line ()
  20146. "Indent line depending on context.
  20147. Indentation is done according to the following rules:
  20148. - Footnote definitions, diary sexps, headlines and inline tasks
  20149. have to start at column 0.
  20150. - On the very first line of an element, consider, in order, the
  20151. next rules until one matches:
  20152. 1. If there's a sibling element before, ignoring footnote
  20153. definitions and inline tasks, indent like its first line.
  20154. 2. If element has a parent, indent like its contents. More
  20155. precisely, if parent is an item, indent after the
  20156. description part, if any, or the bullet (see
  20157. `org-list-description-max-indent'). Else, indent like
  20158. parent's first line.
  20159. 3. Otherwise, indent relatively to current level, if
  20160. `org-adapt-indentation' is non-nil, or to left margin.
  20161. - On a blank line at the end of an element, indent according to
  20162. the type of the element. More precisely
  20163. 1. If element is a plain list, an item, or a footnote
  20164. definition, indent like the very last element within.
  20165. 2. If element is a paragraph, indent like its last non blank
  20166. line.
  20167. 3. Otherwise, indent like its very first line.
  20168. - In the code part of a source block, use language major mode
  20169. to indent current line if `org-src-tab-acts-natively' is
  20170. non-nil. If it is nil, do nothing.
  20171. - Otherwise, indent like the first non-blank line above.
  20172. The function doesn't indent an item as it could break the whole
  20173. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20174. `\\[org-shiftmetaright]'.
  20175. Also align node properties according to `org-property-format'."
  20176. (interactive)
  20177. (cond
  20178. (orgstruct-is-++
  20179. (let ((indent-line-function
  20180. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20181. (indent-according-to-mode)))
  20182. ((org-at-heading-p) 'noindent)
  20183. (t
  20184. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20185. (type (org-element-type element)))
  20186. (cond ((and (memq type '(plain-list item))
  20187. (= (line-beginning-position)
  20188. (org-element-property :post-affiliated element)))
  20189. 'noindent)
  20190. ((and (eq type 'latex-environment)
  20191. (>= (point) (org-element-property :post-affiliated element))
  20192. (< (point) (org-with-wide-buffer
  20193. (goto-char (org-element-property :end element))
  20194. (skip-chars-backward " \r\t\n")
  20195. (line-beginning-position 2))))
  20196. 'noindent)
  20197. ((and (eq type 'src-block)
  20198. org-src-tab-acts-natively
  20199. (> (line-beginning-position)
  20200. (org-element-property :post-affiliated element))
  20201. (< (line-beginning-position)
  20202. (org-with-wide-buffer
  20203. (goto-char (org-element-property :end element))
  20204. (skip-chars-backward " \r\t\n")
  20205. (line-beginning-position))))
  20206. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20207. (t
  20208. (let ((column (org--get-expected-indentation element nil)))
  20209. ;; Preserve current column.
  20210. (if (<= (current-column) (current-indentation))
  20211. (indent-line-to column)
  20212. (save-excursion (indent-line-to column))))
  20213. ;; Align node property. Also preserve current column.
  20214. (when (eq type 'node-property)
  20215. (let ((column (current-column)))
  20216. (org--align-node-property)
  20217. (org-move-to-column column)))))))))
  20218. (defun org-indent-region (start end)
  20219. "Indent each non-blank line in the region.
  20220. Called from a program, START and END specify the region to
  20221. indent. The function will not indent contents of example blocks,
  20222. verse blocks and export blocks as leading white spaces are
  20223. assumed to be significant there."
  20224. (interactive "r")
  20225. (save-excursion
  20226. (goto-char start)
  20227. (skip-chars-forward " \r\t\n")
  20228. (unless (eobp) (beginning-of-line))
  20229. (let ((indent-to
  20230. (lambda (ind pos)
  20231. ;; Set IND as indentation for all lines between point and
  20232. ;; POS. Blank lines are ignored. Leave point after POS
  20233. ;; once done.
  20234. (let ((limit (copy-marker pos)))
  20235. (while (< (point) limit)
  20236. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20237. (forward-line))
  20238. (set-marker limit nil))))
  20239. (end (copy-marker end)))
  20240. (while (< (point) end)
  20241. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20242. (let* ((element (org-element-at-point))
  20243. (type (org-element-type element))
  20244. (element-end (copy-marker (org-element-property :end element)))
  20245. (ind (org--get-expected-indentation element nil)))
  20246. (cond
  20247. ;; Element indented as a single block. Example blocks
  20248. ;; preserving indentation are a special case since the
  20249. ;; "contents" must not be indented whereas the block
  20250. ;; boundaries can.
  20251. ((or (memq type '(export-block latex-environment))
  20252. (and (eq type 'example-block)
  20253. (not
  20254. (or org-src-preserve-indentation
  20255. (org-element-property :preserve-indent element)))))
  20256. (let ((offset (- ind (org-get-indentation))))
  20257. (unless (zerop offset)
  20258. (indent-rigidly (org-element-property :begin element)
  20259. (org-element-property :end element)
  20260. offset)))
  20261. (goto-char element-end))
  20262. ;; Elements indented line wise. Be sure to exclude
  20263. ;; example blocks (preserving indentation) and source
  20264. ;; blocks from this category as they are treated
  20265. ;; specially later.
  20266. ((or (memq type '(paragraph table table-row))
  20267. (not (or (org-element-property :contents-begin element)
  20268. (memq type '(example-block src-block)))))
  20269. (when (eq type 'node-property)
  20270. (org--align-node-property)
  20271. (beginning-of-line))
  20272. (funcall indent-to ind (min element-end end)))
  20273. ;; Elements consisting of three parts: before the
  20274. ;; contents, the contents, and after the contents. The
  20275. ;; contents are treated specially, according to the
  20276. ;; element type, or not indented at all. Other parts are
  20277. ;; indented as a single block.
  20278. (t
  20279. (let* ((post (copy-marker
  20280. (org-element-property :post-affiliated element)))
  20281. (cbeg
  20282. (copy-marker
  20283. (cond
  20284. ((not (org-element-property :contents-begin element))
  20285. ;; Fake contents for source blocks.
  20286. (org-with-wide-buffer
  20287. (goto-char post)
  20288. (line-beginning-position 2)))
  20289. ((memq type '(footnote-definition item plain-list))
  20290. ;; Contents in these elements could start on
  20291. ;; the same line as the beginning of the
  20292. ;; element. Make sure we start indenting
  20293. ;; from the second line.
  20294. (org-with-wide-buffer
  20295. (goto-char post)
  20296. (end-of-line)
  20297. (skip-chars-forward " \r\t\n")
  20298. (if (eobp) (point) (line-beginning-position))))
  20299. (t (org-element-property :contents-begin element)))))
  20300. (cend (copy-marker
  20301. (or (org-element-property :contents-end element)
  20302. ;; Fake contents for source blocks.
  20303. (org-with-wide-buffer
  20304. (goto-char element-end)
  20305. (skip-chars-backward " \r\t\n")
  20306. (line-beginning-position)))
  20307. t)))
  20308. ;; Do not change items indentation individually as it
  20309. ;; might break the list as a whole. On the other
  20310. ;; hand, when at a plain list, indent it as a whole.
  20311. (cond ((eq type 'plain-list)
  20312. (let ((offset (- ind (org-get-indentation))))
  20313. (unless (zerop offset)
  20314. (indent-rigidly (org-element-property :begin element)
  20315. (org-element-property :end element)
  20316. offset))
  20317. (goto-char cbeg)))
  20318. ((eq type 'item) (goto-char cbeg))
  20319. (t (funcall indent-to ind (min cbeg end))))
  20320. (when (< (point) end)
  20321. (cl-case type
  20322. ((example-block verse-block))
  20323. (src-block
  20324. ;; In a source block, indent source code
  20325. ;; according to language major mode, but only if
  20326. ;; `org-src-tab-acts-natively' is non-nil.
  20327. (when (and (< (point) end) org-src-tab-acts-natively)
  20328. (ignore-errors
  20329. (org-babel-do-in-edit-buffer
  20330. (indent-region (point-min) (point-max))))))
  20331. (t (org-indent-region (point) (min cend end))))
  20332. (goto-char (min cend end))
  20333. (when (< (point) end)
  20334. (funcall indent-to ind (min element-end end))))
  20335. (set-marker post nil)
  20336. (set-marker cbeg nil)
  20337. (set-marker cend nil))))
  20338. (set-marker element-end nil))))
  20339. (set-marker end nil))))
  20340. (defun org-indent-drawer ()
  20341. "Indent the drawer at point."
  20342. (interactive)
  20343. (unless (save-excursion
  20344. (beginning-of-line)
  20345. (looking-at-p org-drawer-regexp))
  20346. (user-error "Not at a drawer"))
  20347. (let ((element (org-element-at-point)))
  20348. (unless (memq (org-element-type element) '(drawer property-drawer))
  20349. (user-error "Not at a drawer"))
  20350. (org-with-wide-buffer
  20351. (org-indent-region (org-element-property :begin element)
  20352. (org-element-property :end element))))
  20353. (message "Drawer at point indented"))
  20354. (defun org-indent-block ()
  20355. "Indent the block at point."
  20356. (interactive)
  20357. (unless (save-excursion
  20358. (beginning-of-line)
  20359. (let ((case-fold-search t))
  20360. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20361. (user-error "Not at a block"))
  20362. (let ((element (org-element-at-point)))
  20363. (unless (memq (org-element-type element)
  20364. '(comment-block center-block dynamic-block example-block
  20365. export-block quote-block special-block
  20366. src-block verse-block))
  20367. (user-error "Not at a block"))
  20368. (org-with-wide-buffer
  20369. (org-indent-region (org-element-property :begin element)
  20370. (org-element-property :end element))))
  20371. (message "Block at point indented"))
  20372. ;;; Filling
  20373. ;; We use our own fill-paragraph and auto-fill functions.
  20374. ;; `org-fill-paragraph' relies on adaptive filling and context
  20375. ;; checking. Appropriate `fill-prefix' is computed with
  20376. ;; `org-adaptive-fill-function'.
  20377. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20378. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20379. ;; `org-adaptive-fill-function' value. Internally,
  20380. ;; `org-comment-line-break-function' breaks the line.
  20381. ;; `org-setup-filling' installs filling and auto-filling related
  20382. ;; variables during `org-mode' initialization.
  20383. (defun org-setup-filling ()
  20384. (require 'org-element)
  20385. ;; Prevent auto-fill from inserting unwanted new items.
  20386. (when (boundp 'fill-nobreak-predicate)
  20387. (setq-local
  20388. fill-nobreak-predicate
  20389. (org-uniquify
  20390. (append fill-nobreak-predicate
  20391. '(org-fill-line-break-nobreak-p
  20392. org-fill-n-macro-as-item-nobreak-p
  20393. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20394. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20395. (setq-local paragraph-start paragraph-ending)
  20396. (setq-local paragraph-separate paragraph-ending))
  20397. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20398. (setq-local auto-fill-inhibit-regexp nil)
  20399. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20400. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20401. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20402. (defun org-fill-line-break-nobreak-p ()
  20403. "Non-nil when a new line at point would create an Org line break."
  20404. (save-excursion
  20405. (skip-chars-backward "[ \t]")
  20406. (skip-chars-backward "\\\\")
  20407. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20408. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20409. "Non-nil when a new line at point would split a timestamp."
  20410. (and (org-at-timestamp-p 'lax)
  20411. (not (looking-at org-ts-regexp-both))))
  20412. (defun org-fill-n-macro-as-item-nobreak-p ()
  20413. "Non-nil when a new line at point would create a new list."
  20414. ;; During export, a "n" macro followed by a dot or a closing
  20415. ;; parenthesis can end up being parsed as a new list item.
  20416. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20417. (declare-function message-in-body-p "message" ())
  20418. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20419. (defun org-adaptive-fill-function ()
  20420. "Compute a fill prefix for the current line.
  20421. Return fill prefix, as a string, or nil if current line isn't
  20422. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20423. matches in paragraphs or comments, use it."
  20424. (catch 'exit
  20425. (when (derived-mode-p 'message-mode)
  20426. (save-excursion
  20427. (beginning-of-line)
  20428. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20429. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20430. ((looking-at message-cite-prefix-regexp)
  20431. (throw 'exit (match-string-no-properties 0)))
  20432. ((looking-at org-outline-regexp)
  20433. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20434. (org-with-wide-buffer
  20435. (unless (org-at-heading-p)
  20436. (let* ((p (line-beginning-position))
  20437. (element (save-excursion
  20438. (beginning-of-line)
  20439. (org-element-at-point)))
  20440. (type (org-element-type element))
  20441. (post-affiliated (org-element-property :post-affiliated element)))
  20442. (unless (< p post-affiliated)
  20443. (cl-case type
  20444. (comment
  20445. (save-excursion
  20446. (beginning-of-line)
  20447. (looking-at "[ \t]*")
  20448. (concat (match-string 0) "# ")))
  20449. (footnote-definition "")
  20450. ((item plain-list)
  20451. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20452. (paragraph
  20453. ;; Fill prefix is usually the same as the current line,
  20454. ;; unless the paragraph is at the beginning of an item.
  20455. (let ((parent (org-element-property :parent element)))
  20456. (save-excursion
  20457. (beginning-of-line)
  20458. (cond ((eq (org-element-type parent) 'item)
  20459. (make-string (org-list-item-body-column
  20460. (org-element-property :begin parent))
  20461. ?\s))
  20462. ((and adaptive-fill-regexp
  20463. ;; Locally disable
  20464. ;; `adaptive-fill-function' to let
  20465. ;; `fill-context-prefix' handle
  20466. ;; `adaptive-fill-regexp' variable.
  20467. (let (adaptive-fill-function)
  20468. (fill-context-prefix
  20469. post-affiliated
  20470. (org-element-property :end element)))))
  20471. ((looking-at "[ \t]+") (match-string 0))
  20472. (t "")))))
  20473. (comment-block
  20474. ;; Only fill contents if P is within block boundaries.
  20475. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20476. (forward-line)
  20477. (point)))
  20478. (cend (save-excursion
  20479. (goto-char (org-element-property :end element))
  20480. (skip-chars-backward " \r\t\n")
  20481. (line-beginning-position))))
  20482. (when (and (>= p cbeg) (< p cend))
  20483. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20484. (match-string 0)
  20485. "")))))))))))
  20486. (declare-function message-goto-body "message" ())
  20487. (defvar message-cite-prefix-regexp) ; From message.el
  20488. (defun org-fill-element (&optional justify)
  20489. "Fill element at point, when applicable.
  20490. This function only applies to comment blocks, comments, example
  20491. blocks and paragraphs. Also, as a special case, re-align table
  20492. when point is at one.
  20493. If JUSTIFY is non-nil (interactively, with prefix argument),
  20494. justify as well. If `sentence-end-double-space' is non-nil, then
  20495. period followed by one space does not end a sentence, so don't
  20496. break a line there. The variable `fill-column' controls the
  20497. width for filling.
  20498. For convenience, when point is at a plain list, an item or
  20499. a footnote definition, try to fill the first paragraph within."
  20500. (with-syntax-table org-mode-transpose-word-syntax-table
  20501. ;; Move to end of line in order to get the first paragraph within
  20502. ;; a plain list or a footnote definition.
  20503. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20504. ;; First check if point is in a blank line at the beginning of
  20505. ;; the buffer. In that case, ignore filling.
  20506. (cl-case (org-element-type element)
  20507. ;; Use major mode filling function is src blocks.
  20508. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20509. ;; Align Org tables, leave table.el tables as-is.
  20510. (table-row (org-table-align) t)
  20511. (table
  20512. (when (eq (org-element-property :type element) 'org)
  20513. (save-excursion
  20514. (goto-char (org-element-property :post-affiliated element))
  20515. (org-table-align)))
  20516. t)
  20517. (paragraph
  20518. ;; Paragraphs may contain `line-break' type objects.
  20519. (let ((beg (max (point-min)
  20520. (org-element-property :contents-begin element)))
  20521. (end (min (point-max)
  20522. (org-element-property :contents-end element))))
  20523. ;; Do nothing if point is at an affiliated keyword.
  20524. (if (< (line-end-position) beg) t
  20525. (when (derived-mode-p 'message-mode)
  20526. ;; In `message-mode', do not fill following citation
  20527. ;; in current paragraph nor text before message body.
  20528. (let ((body-start (save-excursion (message-goto-body))))
  20529. (when body-start (setq beg (max body-start beg))))
  20530. (when (save-excursion
  20531. (re-search-forward
  20532. (concat "^" message-cite-prefix-regexp) end t))
  20533. (setq end (match-beginning 0))))
  20534. ;; Fill paragraph, taking line breaks into account.
  20535. (save-excursion
  20536. (goto-char beg)
  20537. (let ((cuts (list beg)))
  20538. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20539. (when (eq 'line-break
  20540. (org-element-type
  20541. (save-excursion (backward-char)
  20542. (org-element-context))))
  20543. (push (point) cuts)))
  20544. (dolist (c (delq end cuts))
  20545. (fill-region-as-paragraph c end justify)
  20546. (setq end c))))
  20547. t)))
  20548. ;; Contents of `comment-block' type elements should be
  20549. ;; filled as plain text, but only if point is within block
  20550. ;; markers.
  20551. (comment-block
  20552. (let* ((case-fold-search t)
  20553. (beg (save-excursion
  20554. (goto-char (org-element-property :begin element))
  20555. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20556. (forward-line)
  20557. (point)))
  20558. (end (save-excursion
  20559. (goto-char (org-element-property :end element))
  20560. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20561. (line-beginning-position))))
  20562. (if (or (< (point) beg) (> (point) end)) t
  20563. (fill-region-as-paragraph
  20564. (save-excursion (end-of-line)
  20565. (re-search-backward "^[ \t]*$" beg 'move)
  20566. (line-beginning-position))
  20567. (save-excursion (beginning-of-line)
  20568. (re-search-forward "^[ \t]*$" end 'move)
  20569. (line-beginning-position))
  20570. justify))))
  20571. ;; Fill comments.
  20572. (comment
  20573. (let ((begin (org-element-property :post-affiliated element))
  20574. (end (org-element-property :end element)))
  20575. (when (and (>= (point) begin) (<= (point) end))
  20576. (let ((begin (save-excursion
  20577. (end-of-line)
  20578. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20579. (progn (forward-line) (point))
  20580. begin)))
  20581. (end (save-excursion
  20582. (end-of-line)
  20583. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20584. (1- (line-beginning-position))
  20585. (skip-chars-backward " \r\t\n")
  20586. (line-end-position)))))
  20587. ;; Do not fill comments when at a blank line.
  20588. (when (> end begin)
  20589. (let ((fill-prefix
  20590. (save-excursion
  20591. (beginning-of-line)
  20592. (looking-at "[ \t]*#")
  20593. (let ((comment-prefix (match-string 0)))
  20594. (goto-char (match-end 0))
  20595. (if (looking-at adaptive-fill-regexp)
  20596. (concat comment-prefix (match-string 0))
  20597. (concat comment-prefix " "))))))
  20598. (save-excursion
  20599. (fill-region-as-paragraph begin end justify))))))
  20600. t))
  20601. ;; Ignore every other element.
  20602. (otherwise t)))))
  20603. (defun org-fill-paragraph (&optional justify region)
  20604. "Fill element at point, when applicable.
  20605. This function only applies to comment blocks, comments, example
  20606. blocks and paragraphs. Also, as a special case, re-align table
  20607. when point is at one.
  20608. For convenience, when point is at a plain list, an item or
  20609. a footnote definition, try to fill the first paragraph within.
  20610. If JUSTIFY is non-nil (interactively, with prefix argument),
  20611. justify as well. If `sentence-end-double-space' is non-nil, then
  20612. period followed by one space does not end a sentence, so don't
  20613. break a line there. The variable `fill-column' controls the
  20614. width for filling.
  20615. The REGION argument is non-nil if called interactively; in that
  20616. case, if Transient Mark mode is enabled and the mark is active,
  20617. fill each of the elements in the active region, instead of just
  20618. filling the current element."
  20619. (interactive (progn
  20620. (barf-if-buffer-read-only)
  20621. (list (if current-prefix-arg 'full) t)))
  20622. (cond
  20623. ((and (derived-mode-p 'message-mode)
  20624. (or (not (message-in-body-p))
  20625. (save-excursion (move-beginning-of-line 1)
  20626. (looking-at message-cite-prefix-regexp))))
  20627. ;; First ensure filling is correct in message-mode.
  20628. (let ((fill-paragraph-function
  20629. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  20630. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  20631. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  20632. (paragraph-separate
  20633. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  20634. (fill-paragraph nil)))
  20635. ((and region transient-mark-mode mark-active
  20636. (not (eq (region-beginning) (region-end))))
  20637. (let ((origin (point-marker))
  20638. (start (region-beginning)))
  20639. (unwind-protect
  20640. (progn
  20641. (goto-char (region-end))
  20642. (while (> (point) start)
  20643. (org-backward-paragraph)
  20644. (org-fill-element justify)))
  20645. (goto-char origin)
  20646. (set-marker origin nil))))
  20647. (t (org-fill-element justify))))
  20648. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  20649. (defun org-auto-fill-function ()
  20650. "Auto-fill function."
  20651. ;; Check if auto-filling is meaningful.
  20652. (let ((fc (current-fill-column)))
  20653. (when (and fc (> (current-column) fc))
  20654. (let* ((fill-prefix (org-adaptive-fill-function))
  20655. ;; Enforce empty fill prefix, if required. Otherwise, it
  20656. ;; will be computed again.
  20657. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20658. (when fill-prefix (do-auto-fill))))))
  20659. (defun org-comment-line-break-function (&optional soft)
  20660. "Break line at point and indent, continuing comment if within one.
  20661. The inserted newline is marked hard if variable
  20662. `use-hard-newlines' is true, unless optional argument SOFT is
  20663. non-nil."
  20664. (if soft (insert-and-inherit ?\n) (newline 1))
  20665. (save-excursion (forward-char -1) (delete-horizontal-space))
  20666. (delete-horizontal-space)
  20667. (indent-to-left-margin)
  20668. (insert-before-markers-and-inherit fill-prefix))
  20669. ;;; Fixed Width Areas
  20670. (defun org-toggle-fixed-width ()
  20671. "Toggle fixed-width markup.
  20672. Add or remove fixed-width markup on current line, whenever it
  20673. makes sense. Return an error otherwise.
  20674. If a region is active and if it contains only fixed-width areas
  20675. or blank lines, remove all fixed-width markup in it. If the
  20676. region contains anything else, convert all non-fixed-width lines
  20677. to fixed-width ones.
  20678. Blank lines at the end of the region are ignored unless the
  20679. region only contains such lines."
  20680. (interactive)
  20681. (if (not (org-region-active-p))
  20682. ;; No region:
  20683. ;;
  20684. ;; Remove fixed width marker only in a fixed-with element.
  20685. ;;
  20686. ;; Add fixed width maker in paragraphs, in blank lines after
  20687. ;; elements or at the beginning of a headline or an inlinetask,
  20688. ;; and before any one-line elements (e.g., a clock).
  20689. (progn
  20690. (beginning-of-line)
  20691. (let* ((element (org-element-at-point))
  20692. (type (org-element-type element)))
  20693. (cond
  20694. ((and (eq type 'fixed-width)
  20695. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20696. (replace-match
  20697. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20698. ((and (memq type '(babel-call clock comment diary-sexp headline
  20699. horizontal-rule keyword paragraph
  20700. planning))
  20701. (<= (org-element-property :post-affiliated element) (point)))
  20702. (skip-chars-forward " \t")
  20703. (insert ": "))
  20704. ((and (looking-at-p "[ \t]*$")
  20705. (or (eq type 'inlinetask)
  20706. (save-excursion
  20707. (skip-chars-forward " \r\t\n")
  20708. (<= (org-element-property :end element) (point)))))
  20709. (delete-region (point) (line-end-position))
  20710. (org-indent-line)
  20711. (insert ": "))
  20712. (t (user-error "Cannot insert a fixed-width line here")))))
  20713. ;; Region active.
  20714. (let* ((begin (save-excursion
  20715. (goto-char (region-beginning))
  20716. (line-beginning-position)))
  20717. (end (copy-marker
  20718. (save-excursion
  20719. (goto-char (region-end))
  20720. (unless (eolp) (beginning-of-line))
  20721. (if (save-excursion (re-search-backward "\\S-" begin t))
  20722. (progn (skip-chars-backward " \r\t\n") (point))
  20723. (point)))))
  20724. (all-fixed-width-p
  20725. (catch 'not-all-p
  20726. (save-excursion
  20727. (goto-char begin)
  20728. (skip-chars-forward " \r\t\n")
  20729. (when (eobp) (throw 'not-all-p nil))
  20730. (while (< (point) end)
  20731. (let ((element (org-element-at-point)))
  20732. (if (eq (org-element-type element) 'fixed-width)
  20733. (goto-char (org-element-property :end element))
  20734. (throw 'not-all-p nil))))
  20735. t))))
  20736. (if all-fixed-width-p
  20737. (save-excursion
  20738. (goto-char begin)
  20739. (while (< (point) end)
  20740. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20741. (replace-match
  20742. "" nil nil nil
  20743. (if (= (line-end-position) (match-end 0)) 0 1)))
  20744. (forward-line)))
  20745. (let ((min-ind (point-max)))
  20746. ;; Find minimum indentation across all lines.
  20747. (save-excursion
  20748. (goto-char begin)
  20749. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20750. (setq min-ind 0)
  20751. (catch 'zerop
  20752. (while (< (point) end)
  20753. (unless (looking-at-p "[ \t]*$")
  20754. (let ((ind (org-get-indentation)))
  20755. (setq min-ind (min min-ind ind))
  20756. (when (zerop ind) (throw 'zerop t))))
  20757. (forward-line)))))
  20758. ;; Loop over all lines and add fixed-width markup everywhere
  20759. ;; but in fixed-width lines.
  20760. (save-excursion
  20761. (goto-char begin)
  20762. (while (< (point) end)
  20763. (cond
  20764. ((org-at-heading-p)
  20765. (insert ": ")
  20766. (forward-line)
  20767. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20768. (insert ":")
  20769. (forward-line)))
  20770. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20771. (let* ((element (org-element-at-point))
  20772. (element-end (org-element-property :end element)))
  20773. (if (eq (org-element-type element) 'fixed-width)
  20774. (progn (goto-char element-end)
  20775. (skip-chars-backward " \r\t\n")
  20776. (forward-line))
  20777. (let ((limit (min end element-end)))
  20778. (while (< (point) limit)
  20779. (org-move-to-column min-ind t)
  20780. (insert ": ")
  20781. (forward-line))))))
  20782. (t
  20783. (org-move-to-column min-ind t)
  20784. (insert ": ")
  20785. (forward-line)))))))
  20786. (set-marker end nil))))
  20787. ;;; Comments
  20788. ;; Org comments syntax is quite complex. It requires the entire line
  20789. ;; to be just a comment. Also, even with the right syntax at the
  20790. ;; beginning of line, some elements (e.g., verse-block or
  20791. ;; example-block) don't accept comments. Usual Emacs comment commands
  20792. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20793. ;; Org still relies on `comment-dwim', but cannot trust
  20794. ;; `comment-only-p'. So, `comment-region-function' and
  20795. ;; `uncomment-region-function' both point
  20796. ;; to`org-comment-or-uncomment-region'. Eventually,
  20797. ;; `org-insert-comment' takes care of insertion of comments at the
  20798. ;; beginning of line.
  20799. ;; `org-setup-comments-handling' install comments related variables
  20800. ;; during `org-mode' initialization.
  20801. (defun org-setup-comments-handling ()
  20802. (interactive)
  20803. (setq-local comment-use-syntax nil)
  20804. (setq-local comment-start "# ")
  20805. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20806. (setq-local comment-insert-comment-function 'org-insert-comment)
  20807. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20808. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20809. (defun org-insert-comment ()
  20810. "Insert an empty comment above current line.
  20811. If the line is empty, insert comment at its beginning. When
  20812. point is within a source block, comment according to the related
  20813. major mode."
  20814. (if (let ((element (org-element-at-point)))
  20815. (and (eq (org-element-type element) 'src-block)
  20816. (< (save-excursion
  20817. (goto-char (org-element-property :post-affiliated element))
  20818. (line-end-position))
  20819. (point))
  20820. (> (save-excursion
  20821. (goto-char (org-element-property :end element))
  20822. (skip-chars-backward " \r\t\n")
  20823. (line-beginning-position))
  20824. (point))))
  20825. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20826. (beginning-of-line)
  20827. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20828. (open-line 1))
  20829. (org-indent-line)
  20830. (insert "# ")))
  20831. (defvar comment-empty-lines) ; From newcomment.el.
  20832. (defun org-comment-or-uncomment-region (beg end &rest _)
  20833. "Comment or uncomment each non-blank line in the region.
  20834. Uncomment each non-blank line between BEG and END if it only
  20835. contains commented lines. Otherwise, comment them. If region is
  20836. strictly within a source block, use appropriate comment syntax."
  20837. (if (let ((element (org-element-at-point)))
  20838. (and (eq (org-element-type element) 'src-block)
  20839. (< (save-excursion
  20840. (goto-char (org-element-property :post-affiliated element))
  20841. (line-end-position))
  20842. beg)
  20843. (>= (save-excursion
  20844. (goto-char (org-element-property :end element))
  20845. (skip-chars-backward " \r\t\n")
  20846. (line-beginning-position))
  20847. end)))
  20848. ;; Translate region boundaries for the Org buffer to the source
  20849. ;; buffer.
  20850. (let ((offset (- end beg)))
  20851. (save-excursion
  20852. (goto-char beg)
  20853. (org-babel-do-in-edit-buffer
  20854. (comment-or-uncomment-region (point) (+ offset (point))))))
  20855. (save-restriction
  20856. ;; Restrict region
  20857. (narrow-to-region (save-excursion (goto-char beg)
  20858. (skip-chars-forward " \r\t\n" end)
  20859. (line-beginning-position))
  20860. (save-excursion (goto-char end)
  20861. (skip-chars-backward " \r\t\n" beg)
  20862. (line-end-position)))
  20863. (let ((uncommentp
  20864. ;; UNCOMMENTP is non-nil when every non blank line between
  20865. ;; BEG and END is a comment.
  20866. (save-excursion
  20867. (goto-char (point-min))
  20868. (while (and (not (eobp))
  20869. (let ((element (org-element-at-point)))
  20870. (and (eq (org-element-type element) 'comment)
  20871. (goto-char (min (point-max)
  20872. (org-element-property
  20873. :end element)))))))
  20874. (eobp))))
  20875. (if uncommentp
  20876. ;; Only blank lines and comments in region: uncomment it.
  20877. (save-excursion
  20878. (goto-char (point-min))
  20879. (while (not (eobp))
  20880. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20881. (replace-match "" nil nil nil 1))
  20882. (forward-line)))
  20883. ;; Comment each line in region.
  20884. (let ((min-indent (point-max)))
  20885. ;; First find the minimum indentation across all lines.
  20886. (save-excursion
  20887. (goto-char (point-min))
  20888. (while (and (not (eobp)) (not (zerop min-indent)))
  20889. (unless (looking-at "[ \t]*$")
  20890. (setq min-indent (min min-indent (current-indentation))))
  20891. (forward-line)))
  20892. ;; Then loop over all lines.
  20893. (save-excursion
  20894. (goto-char (point-min))
  20895. (while (not (eobp))
  20896. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20897. ;; Don't get fooled by invisible text (e.g. link path)
  20898. ;; when moving to column MIN-INDENT.
  20899. (let ((buffer-invisibility-spec nil))
  20900. (org-move-to-column min-indent t))
  20901. (insert comment-start))
  20902. (forward-line)))))))))
  20903. (defun org-comment-dwim (_arg)
  20904. "Call the comment command you mean.
  20905. Call `org-toggle-comment' if on a heading, otherwise call
  20906. `comment-dwim', within a source edit buffer if needed."
  20907. (interactive "*P")
  20908. (cond ((org-at-heading-p)
  20909. (call-interactively #'org-toggle-comment))
  20910. ((org-in-src-block-p)
  20911. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20912. (t (call-interactively #'comment-dwim))))
  20913. ;;; Timestamps API
  20914. ;; This section contains tools to operate on timestamp objects, as
  20915. ;; returned by, e.g. `org-element-context'.
  20916. (defun org-timestamp--to-internal-time (timestamp &optional end)
  20917. "Encode TIMESTAMP object into Emacs internal time.
  20918. Use end of date range or time range when END is non-nil."
  20919. (apply #'encode-time
  20920. (cons 0
  20921. (mapcar
  20922. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20923. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20924. '(:minute-start :hour-start :day-start :month-start
  20925. :year-start))))))
  20926. (defun org-timestamp-has-time-p (timestamp)
  20927. "Non-nil when TIMESTAMP has a time specified."
  20928. (org-element-property :hour-start timestamp))
  20929. (defun org-timestamp-format (timestamp format &optional end utc)
  20930. "Format a TIMESTAMP object into a string.
  20931. FORMAT is a format specifier to be passed to
  20932. `format-time-string'.
  20933. When optional argument END is non-nil, use end of date-range or
  20934. time-range, if possible.
  20935. When optional argument UTC is non-nil, time will be expressed as
  20936. Universal Time."
  20937. (format-time-string
  20938. format (org-timestamp--to-internal-time timestamp end)
  20939. (and utc t)))
  20940. (defun org-timestamp-split-range (timestamp &optional end)
  20941. "Extract a TIMESTAMP object from a date or time range.
  20942. END, when non-nil, means extract the end of the range.
  20943. Otherwise, extract its start.
  20944. Return a new timestamp object."
  20945. (let ((type (org-element-property :type timestamp)))
  20946. (if (memq type '(active inactive diary)) timestamp
  20947. (let ((split-ts (org-element-copy timestamp)))
  20948. ;; Set new type.
  20949. (org-element-put-property
  20950. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20951. ;; Copy start properties over end properties if END is
  20952. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20953. (let ((p-alist '((:minute-start . :minute-end)
  20954. (:hour-start . :hour-end)
  20955. (:day-start . :day-end)
  20956. (:month-start . :month-end)
  20957. (:year-start . :year-end))))
  20958. (dolist (p-cell p-alist)
  20959. (org-element-put-property
  20960. split-ts
  20961. (funcall (if end #'car #'cdr) p-cell)
  20962. (org-element-property
  20963. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20964. ;; Eventually refresh `:raw-value'.
  20965. (org-element-put-property split-ts :raw-value nil)
  20966. (org-element-put-property
  20967. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20968. (defun org-timestamp-translate (timestamp &optional boundary)
  20969. "Translate TIMESTAMP object to custom format.
  20970. Format string is defined in `org-time-stamp-custom-formats',
  20971. which see.
  20972. When optional argument BOUNDARY is non-nil, it is either the
  20973. symbol `start' or `end'. In this case, only translate the
  20974. starting or ending part of TIMESTAMP if it is a date or time
  20975. range. Otherwise, translate both parts.
  20976. Return timestamp as-is if `org-display-custom-times' is nil or if
  20977. it has a `diary' type."
  20978. (let ((type (org-element-property :type timestamp)))
  20979. (if (or (not org-display-custom-times) (eq type 'diary))
  20980. (org-element-interpret-data timestamp)
  20981. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20982. org-time-stamp-custom-formats)))
  20983. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20984. (concat (org-timestamp-format timestamp fmt)
  20985. "--"
  20986. (org-timestamp-format timestamp fmt t))
  20987. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20988. ;;; Other stuff.
  20989. (defvar reftex-docstruct-symbol)
  20990. (defvar org--rds)
  20991. (defun org-reftex-citation ()
  20992. "Use reftex-citation to insert a citation into the buffer.
  20993. This looks for a line like
  20994. #+BIBLIOGRAPHY: foo plain option:-d
  20995. and derives from it that foo.bib is the bibliography file relevant
  20996. for this document. It then installs the necessary environment for RefTeX
  20997. to work in this buffer and calls `reftex-citation' to insert a citation
  20998. into the buffer.
  20999. Export of such citations to both LaTeX and HTML is handled by the contributed
  21000. package ox-bibtex by Taru Karttunen."
  21001. (interactive)
  21002. (let ((reftex-docstruct-symbol 'org--rds)
  21003. org--rds bib)
  21004. (org-with-wide-buffer
  21005. (let ((case-fold-search t)
  21006. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21007. (if (not (save-excursion
  21008. (or (re-search-forward re nil t)
  21009. (re-search-backward re nil t))))
  21010. (user-error "No bibliography defined in file")
  21011. (setq bib (concat (match-string 1) ".bib")
  21012. org--rds (list (list 'bib bib))))))
  21013. (call-interactively 'reftex-citation)))
  21014. ;;;; Functions extending outline functionality
  21015. (defun org-beginning-of-line (&optional n)
  21016. "Go to the beginning of the current visible line.
  21017. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21018. tags on the first attempt, and only move to after the tags when
  21019. the cursor is already beyond the end of the headline.
  21020. With argument N not nil or 1, move forward N - 1 lines first."
  21021. (interactive "^p")
  21022. (let ((origin (point))
  21023. (special (pcase org-special-ctrl-a/e
  21024. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21025. deactivate-mark)
  21026. ;; First move to a visible line.
  21027. (if (bound-and-true-p visual-line-mode)
  21028. (beginning-of-visual-line n)
  21029. (move-beginning-of-line n)
  21030. ;; `move-beginning-of-line' may leave point after invisible
  21031. ;; characters if line starts with such of these (e.g., with
  21032. ;; a link at column 0). Really move to the beginning of the
  21033. ;; current visible line.
  21034. (beginning-of-line))
  21035. (cond
  21036. ;; No special behavior. Point is already at the beginning of
  21037. ;; a line, logical or visual.
  21038. ((not special))
  21039. ;; `beginning-of-visual-line' left point before logical beginning
  21040. ;; of line: point is at the beginning of a visual line. Bail
  21041. ;; out.
  21042. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21043. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21044. ;; At a headline, special position is before the title, but
  21045. ;; after any TODO keyword or priority cookie.
  21046. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21047. (line-end-position)))
  21048. (bol (point)))
  21049. (if (eq special 'reversed)
  21050. (when (and (= origin bol) (eq last-command this-command))
  21051. (goto-char refpos))
  21052. (when (or (> origin refpos) (= origin bol))
  21053. (goto-char refpos)))))
  21054. ((and (looking-at org-list-full-item-re)
  21055. (memq (org-element-type (save-match-data (org-element-at-point)))
  21056. '(item plain-list)))
  21057. ;; Set special position at first white space character after
  21058. ;; bullet, and check-box, if any.
  21059. (let ((after-bullet
  21060. (let ((box (match-end 3)))
  21061. (cond ((not box) (match-end 1))
  21062. ((eq (char-after box) ?\s) (1+ box))
  21063. (t box)))))
  21064. (if (eq special 'reversed)
  21065. (when (and (= (point) origin) (eq last-command this-command))
  21066. (goto-char after-bullet))
  21067. (when (or (> origin after-bullet) (= (point) origin))
  21068. (goto-char after-bullet)))))
  21069. ;; No special context. Point is already at beginning of line.
  21070. (t nil))))
  21071. (defun org-end-of-line (&optional n)
  21072. "Go to the end of the line, but before ellipsis, if any.
  21073. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21074. tags on the first attempt, and only move to after the tags when
  21075. the cursor is already beyond the end of the headline.
  21076. With argument N not nil or 1, move forward N - 1 lines first."
  21077. (interactive "^p")
  21078. (let ((origin (point))
  21079. (special (pcase org-special-ctrl-a/e
  21080. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21081. deactivate-mark)
  21082. ;; First move to a visible line.
  21083. (if (bound-and-true-p visual-line-mode)
  21084. (beginning-of-visual-line n)
  21085. (move-beginning-of-line n))
  21086. (cond
  21087. ;; At a headline, with tags.
  21088. ((and special
  21089. (save-excursion
  21090. (beginning-of-line)
  21091. (let ((case-fold-search nil))
  21092. (looking-at org-complex-heading-regexp)))
  21093. (match-end 5))
  21094. (let ((tags (save-excursion
  21095. (goto-char (match-beginning 5))
  21096. (skip-chars-backward " \t")
  21097. (point)))
  21098. (visual-end (and (bound-and-true-p visual-line-mode)
  21099. (save-excursion
  21100. (end-of-visual-line)
  21101. (point)))))
  21102. ;; If `end-of-visual-line' brings us before end of line or
  21103. ;; even tags, i.e., the headline spans over multiple visual
  21104. ;; lines, move there.
  21105. (cond ((and visual-end
  21106. (< visual-end tags)
  21107. (<= origin visual-end))
  21108. (goto-char visual-end))
  21109. ((eq special 'reversed)
  21110. (if (and (= origin (line-end-position))
  21111. (eq this-command last-command))
  21112. (goto-char tags)
  21113. (end-of-line)))
  21114. (t
  21115. (if (or (< origin tags) (= origin (line-end-position)))
  21116. (goto-char tags)
  21117. (end-of-line))))))
  21118. ((bound-and-true-p visual-line-mode)
  21119. (let ((bol (line-beginning-position)))
  21120. (end-of-visual-line)
  21121. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21122. ;; end of a line, backtrack and use `end-of-line' instead.
  21123. (when (/= bol (line-beginning-position))
  21124. (goto-char bol)
  21125. (end-of-line))))
  21126. (t (end-of-line)))))
  21127. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21128. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21129. (defun org-backward-sentence (&optional _arg)
  21130. "Go to beginning of sentence, or beginning of table field.
  21131. This will call `backward-sentence' or `org-table-beginning-of-field',
  21132. depending on context."
  21133. (interactive)
  21134. (let* ((element (org-element-at-point))
  21135. (contents-begin (org-element-property :contents-begin element))
  21136. (table (org-element-lineage element '(table) t)))
  21137. (if (and table
  21138. (> (point) contents-begin)
  21139. (<= (point) (org-element-property :contents-end table)))
  21140. (call-interactively #'org-table-beginning-of-field)
  21141. (save-restriction
  21142. (when (and contents-begin
  21143. (< (point-min) contents-begin)
  21144. (> (point) contents-begin))
  21145. (narrow-to-region contents-begin
  21146. (org-element-property :contents-end element)))
  21147. (call-interactively #'backward-sentence)))))
  21148. (defun org-forward-sentence (&optional _arg)
  21149. "Go to end of sentence, or end of table field.
  21150. This will call `forward-sentence' or `org-table-end-of-field',
  21151. depending on context."
  21152. (interactive)
  21153. (if (and (org-at-heading-p)
  21154. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21155. (save-restriction
  21156. (narrow-to-region (line-beginning-position) (line-end-position))
  21157. (call-interactively #'forward-sentence))
  21158. (let* ((element (org-element-at-point))
  21159. (contents-end (org-element-property :contents-end element))
  21160. (table (org-element-lineage element '(table) t)))
  21161. (if (and table
  21162. (>= (point) (org-element-property :contents-begin table))
  21163. (< (point) contents-end))
  21164. (call-interactively #'org-table-end-of-field)
  21165. (save-restriction
  21166. (when (and contents-end
  21167. (> (point-max) contents-end)
  21168. ;; Skip blank lines between elements.
  21169. (< (org-element-property :end element)
  21170. (save-excursion (goto-char contents-end)
  21171. (skip-chars-forward " \r\t\n"))))
  21172. (narrow-to-region (org-element-property :contents-begin element)
  21173. contents-end))
  21174. ;; End of heading is considered as the end of a sentence.
  21175. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  21176. (call-interactively #'forward-sentence)))))))
  21177. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21178. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21179. (defun org-kill-line (&optional _arg)
  21180. "Kill line, to tags or end of line."
  21181. (interactive)
  21182. (cond
  21183. ((or (not org-special-ctrl-k)
  21184. (bolp)
  21185. (not (org-at-heading-p)))
  21186. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21187. org-ctrl-k-protect-subtree
  21188. (or (eq org-ctrl-k-protect-subtree 'error)
  21189. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21190. (user-error "C-k aborted as it would kill a hidden subtree"))
  21191. (call-interactively
  21192. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21193. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21194. (kill-region (point) (match-beginning 1))
  21195. (org-set-tags nil t))
  21196. (t (kill-region (point) (point-at-eol)))))
  21197. (define-key org-mode-map "\C-k" 'org-kill-line)
  21198. (defun org-yank (&optional arg)
  21199. "Yank. If the kill is a subtree, treat it specially.
  21200. This command will look at the current kill and check if is a single
  21201. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21202. cursor is at the beginning of a line or after the stars of a currently
  21203. empty headline, then the yank is handled specially. How exactly depends
  21204. on the value of the following variables.
  21205. `org-yank-folded-subtrees'
  21206. By default, this variable is non-nil, which results in
  21207. subtree(s) being folded after insertion, except if doing so
  21208. would swallow text after the yanked text.
  21209. `org-yank-adjusted-subtrees'
  21210. When non-nil (the default value is nil), the subtree will be
  21211. promoted or demoted in order to fit into the local outline tree
  21212. structure, which means that the level will be adjusted so that it
  21213. becomes the smaller one of the two *visible* surrounding headings.
  21214. Any prefix to this command will cause `yank' to be called directly with
  21215. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21216. will just
  21217. plainly yank the text as it is.
  21218. \[1] The test checks if the first non-white line is a heading
  21219. and if there are no other headings with fewer stars."
  21220. (interactive "P")
  21221. (org-yank-generic 'yank arg))
  21222. (defun org-yank-generic (command arg)
  21223. "Perform some yank-like command.
  21224. This function implements the behavior described in the `org-yank'
  21225. documentation. However, it has been generalized to work for any
  21226. interactive command with similar behavior."
  21227. ;; pretend to be command COMMAND
  21228. (setq this-command command)
  21229. (if arg
  21230. (call-interactively command)
  21231. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21232. (and (org-kill-is-subtree-p)
  21233. (or (bolp)
  21234. (and (looking-at "[ \t]*$")
  21235. (string-match
  21236. "\\`\\*+\\'"
  21237. (buffer-substring (point-at-bol) (point)))))))
  21238. swallowp)
  21239. (cond
  21240. ((and subtreep org-yank-folded-subtrees)
  21241. (let ((beg (point))
  21242. end)
  21243. (if (and subtreep org-yank-adjusted-subtrees)
  21244. (org-paste-subtree nil nil 'for-yank)
  21245. (call-interactively command))
  21246. (setq end (point))
  21247. (goto-char beg)
  21248. (when (and (bolp) subtreep
  21249. (not (setq swallowp
  21250. (org-yank-folding-would-swallow-text beg end))))
  21251. (org-with-limited-levels
  21252. (or (looking-at org-outline-regexp)
  21253. (re-search-forward org-outline-regexp-bol end t))
  21254. (while (and (< (point) end) (looking-at org-outline-regexp))
  21255. (outline-hide-subtree)
  21256. (org-cycle-show-empty-lines 'folded)
  21257. (condition-case nil
  21258. (outline-forward-same-level 1)
  21259. (error (goto-char end))))))
  21260. (when swallowp
  21261. (message
  21262. "Inserted text not folded because that would swallow text"))
  21263. (goto-char end)
  21264. (skip-chars-forward " \t\n\r")
  21265. (beginning-of-line 1)
  21266. (push-mark beg 'nomsg)))
  21267. ((and subtreep org-yank-adjusted-subtrees)
  21268. (let ((beg (point-at-bol)))
  21269. (org-paste-subtree nil nil 'for-yank)
  21270. (push-mark beg 'nomsg)))
  21271. (t
  21272. (call-interactively command))))))
  21273. (defun org-yank-folding-would-swallow-text (beg end)
  21274. "Would hide-subtree at BEG swallow any text after END?"
  21275. (let (level)
  21276. (org-with-limited-levels
  21277. (save-excursion
  21278. (goto-char beg)
  21279. (when (or (looking-at org-outline-regexp)
  21280. (re-search-forward org-outline-regexp-bol end t))
  21281. (setq level (org-outline-level)))
  21282. (goto-char end)
  21283. (skip-chars-forward " \t\r\n\v\f")
  21284. (not (or (eobp)
  21285. (and (bolp) (looking-at-p org-outline-regexp)
  21286. (<= (org-outline-level) level))))))))
  21287. (define-key org-mode-map "\C-y" 'org-yank)
  21288. (defun org-back-to-heading (&optional invisible-ok)
  21289. "Call `outline-back-to-heading', but provide a better error message."
  21290. (condition-case nil
  21291. (outline-back-to-heading invisible-ok)
  21292. (error (error "Before first headline at position %d in buffer %s"
  21293. (point) (current-buffer)))))
  21294. (defun org-before-first-heading-p ()
  21295. "Before first heading?"
  21296. (save-excursion
  21297. (end-of-line)
  21298. (null (re-search-backward org-outline-regexp-bol nil t))))
  21299. (defun org-at-heading-p (&optional ignored)
  21300. (outline-on-heading-p t))
  21301. (defun org-in-commented-heading-p (&optional no-inheritance)
  21302. "Non-nil if point is under a commented heading.
  21303. This function also checks ancestors of the current headline,
  21304. unless optional argument NO-INHERITANCE is non-nil."
  21305. (cond
  21306. ((org-before-first-heading-p) nil)
  21307. ((let ((headline (nth 4 (org-heading-components))))
  21308. (and headline
  21309. (let ((case-fold-search nil))
  21310. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21311. headline)))))
  21312. (no-inheritance nil)
  21313. (t
  21314. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21315. (defun org-at-comment-p nil
  21316. "Is cursor in a commented line?"
  21317. (save-excursion
  21318. (save-match-data
  21319. (beginning-of-line)
  21320. (looking-at "^[ \t]*# "))))
  21321. (defun org-at-drawer-p nil
  21322. "Is cursor at a drawer keyword?"
  21323. (save-excursion
  21324. (move-beginning-of-line 1)
  21325. (looking-at org-drawer-regexp)))
  21326. (defun org-at-block-p nil
  21327. "Is cursor at a block keyword?"
  21328. (save-excursion
  21329. (move-beginning-of-line 1)
  21330. (looking-at org-block-regexp)))
  21331. (defun org-point-at-end-of-empty-headline ()
  21332. "If point is at the end of an empty headline, return t, else nil.
  21333. If the heading only contains a TODO keyword, it is still still considered
  21334. empty."
  21335. (let ((case-fold-search nil))
  21336. (and (looking-at "[ \t]*$")
  21337. org-todo-line-regexp
  21338. (save-excursion
  21339. (beginning-of-line)
  21340. (looking-at org-todo-line-regexp)
  21341. (string= (match-string 3) "")))))
  21342. (defun org-at-heading-or-item-p ()
  21343. (or (org-at-heading-p) (org-at-item-p)))
  21344. (defun org-at-target-p ()
  21345. (or (org-in-regexp org-radio-target-regexp)
  21346. (org-in-regexp org-target-regexp)))
  21347. ;; Compatibility alias with Org versions < 7.8.03
  21348. (defalias 'org-on-target-p 'org-at-target-p)
  21349. (defun org-up-heading-all (arg)
  21350. "Move to the heading line of which the present line is a subheading.
  21351. This function considers both visible and invisible heading lines.
  21352. With argument, move up ARG levels."
  21353. (outline-up-heading arg t))
  21354. (defun org-up-heading-safe ()
  21355. "Move to the heading line of which the present line is a subheading.
  21356. This version will not throw an error. It will return the level of the
  21357. headline found, or nil if no higher level is found.
  21358. Also, this function will be a lot faster than `outline-up-heading',
  21359. because it relies on stars being the outline starters. This can really
  21360. make a significant difference in outlines with very many siblings."
  21361. (when (ignore-errors (org-back-to-heading t))
  21362. (let ((level-up (1- (funcall outline-level))))
  21363. (and (> level-up 0)
  21364. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21365. (funcall outline-level)))))
  21366. (defun org-first-sibling-p ()
  21367. "Is this heading the first child of its parents?"
  21368. (interactive)
  21369. (let ((re org-outline-regexp-bol)
  21370. level l)
  21371. (unless (org-at-heading-p t)
  21372. (user-error "Not at a heading"))
  21373. (setq level (funcall outline-level))
  21374. (save-excursion
  21375. (if (not (re-search-backward re nil t))
  21376. t
  21377. (setq l (funcall outline-level))
  21378. (< l level)))))
  21379. (defun org-goto-sibling (&optional previous)
  21380. "Goto the next sibling, even if it is invisible.
  21381. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21382. when a sibling was found. When none is found, return nil and don't
  21383. move point."
  21384. (let ((fun (if previous 're-search-backward 're-search-forward))
  21385. (pos (point))
  21386. (re org-outline-regexp-bol)
  21387. level l)
  21388. (when (ignore-errors (org-back-to-heading t))
  21389. (setq level (funcall outline-level))
  21390. (catch 'exit
  21391. (or previous (forward-char 1))
  21392. (while (funcall fun re nil t)
  21393. (setq l (funcall outline-level))
  21394. (when (< l level) (goto-char pos) (throw 'exit nil))
  21395. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21396. (goto-char pos)
  21397. nil))))
  21398. (defun org-show-siblings ()
  21399. "Show all siblings of the current headline."
  21400. (save-excursion
  21401. (while (org-goto-sibling) (org-flag-heading nil)))
  21402. (save-excursion
  21403. (while (org-goto-sibling 'previous)
  21404. (org-flag-heading nil))))
  21405. (defun org-goto-first-child ()
  21406. "Goto the first child, even if it is invisible.
  21407. Return t when a child was found. Otherwise don't move point and
  21408. return nil."
  21409. (let (level (pos (point)) (re org-outline-regexp-bol))
  21410. (when (ignore-errors (org-back-to-heading t))
  21411. (setq level (outline-level))
  21412. (forward-char 1)
  21413. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21414. (progn (goto-char (match-beginning 0)) t)
  21415. (goto-char pos) nil))))
  21416. (defun org-show-hidden-entry ()
  21417. "Show an entry where even the heading is hidden."
  21418. (save-excursion
  21419. (org-show-entry)))
  21420. (defun org-flag-heading (flag &optional entry)
  21421. "Flag the current heading. FLAG non-nil means make invisible.
  21422. When ENTRY is non-nil, show the entire entry."
  21423. (save-excursion
  21424. (org-back-to-heading t)
  21425. ;; Check if we should show the entire entry
  21426. (if entry
  21427. (progn
  21428. (org-show-entry)
  21429. (save-excursion
  21430. (and (outline-next-heading)
  21431. (org-flag-heading nil))))
  21432. (outline-flag-region (max (point-min) (1- (point)))
  21433. (save-excursion (outline-end-of-heading) (point))
  21434. flag))))
  21435. (defun org-get-next-sibling ()
  21436. "Move to next heading of the same level, and return point.
  21437. If there is no such heading, return nil.
  21438. This is like outline-next-sibling, but invisible headings are ok."
  21439. (let ((level (funcall outline-level)))
  21440. (outline-next-heading)
  21441. (while (and (not (eobp)) (> (funcall outline-level) level))
  21442. (outline-next-heading))
  21443. (unless (or (eobp) (< (funcall outline-level) level))
  21444. (point))))
  21445. (defun org-get-last-sibling ()
  21446. "Move to previous heading of the same level, and return point.
  21447. If there is no such heading, return nil."
  21448. (let ((opoint (point))
  21449. (level (funcall outline-level)))
  21450. (outline-previous-heading)
  21451. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21452. (while (and (> (funcall outline-level) level)
  21453. (not (bobp)))
  21454. (outline-previous-heading))
  21455. (unless (< (funcall outline-level) level)
  21456. (point)))))
  21457. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21458. "Goto to the end of a subtree."
  21459. ;; This contains an exact copy of the original function, but it uses
  21460. ;; `org-back-to-heading', to make it work also in invisible
  21461. ;; trees. And is uses an invisible-ok argument.
  21462. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21463. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21464. ;; with many children and grandchildren etc, this can be much faster
  21465. ;; than the outline version.
  21466. (org-back-to-heading invisible-ok)
  21467. (let ((first t)
  21468. (level (funcall outline-level)))
  21469. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21470. ;; A true heading (not a plain list item), in Org
  21471. ;; This means we can easily find the end by looking
  21472. ;; only for the right number of stars. Using a regexp to do
  21473. ;; this is so much faster than using a Lisp loop.
  21474. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21475. (forward-char 1)
  21476. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21477. ;; something else, do it the slow way
  21478. (while (and (not (eobp))
  21479. (or first (> (funcall outline-level) level)))
  21480. (setq first nil)
  21481. (outline-next-heading)))
  21482. (unless to-heading
  21483. (when (memq (preceding-char) '(?\n ?\^M))
  21484. ;; Go to end of line before heading
  21485. (forward-char -1)
  21486. (when (memq (preceding-char) '(?\n ?\^M))
  21487. ;; leave blank line before heading
  21488. (forward-char -1)))))
  21489. (point))
  21490. (defun org-end-of-meta-data (&optional full)
  21491. "Skip planning line and properties drawer in current entry.
  21492. When optional argument FULL is non-nil, also skip empty lines,
  21493. clocking lines and regular drawers at the beginning of the
  21494. entry."
  21495. (org-back-to-heading t)
  21496. (forward-line)
  21497. (when (looking-at-p org-planning-line-re) (forward-line))
  21498. (when (looking-at org-property-drawer-re)
  21499. (goto-char (match-end 0))
  21500. (forward-line))
  21501. (when (and full (not (org-at-heading-p)))
  21502. (catch 'exit
  21503. (let ((end (save-excursion (outline-next-heading) (point)))
  21504. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21505. (while (not (eobp))
  21506. (cond ((looking-at-p org-drawer-regexp)
  21507. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21508. (forward-line)
  21509. (throw 'exit t)))
  21510. ((looking-at-p re) (forward-line))
  21511. (t (throw 'exit t))))))))
  21512. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21513. "Move forward to the ARG'th subheading at same level as this one.
  21514. Stop at the first and last subheadings of a superior heading.
  21515. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21516. non-nil it will also look at invisible ones."
  21517. (interactive "p")
  21518. (let ((backward? (and arg (< arg 0))))
  21519. (if (org-before-first-heading-p)
  21520. (if backward? (goto-char (point-min)) (outline-next-heading))
  21521. (org-back-to-heading invisible-ok)
  21522. (unless backward? (end-of-line)) ;do not match current headline
  21523. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21524. (f (if backward? #'re-search-backward #'re-search-forward))
  21525. (count (if arg (abs arg) 1))
  21526. (result (point)))
  21527. (while (and (> count 0)
  21528. (funcall f org-outline-regexp-bol nil 'move))
  21529. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21530. (cond ((< l level) (setq count 0))
  21531. ((and (= l level)
  21532. (or invisible-ok
  21533. (not (org-invisible-p
  21534. (line-beginning-position)))))
  21535. (cl-decf count)
  21536. (when (= l level) (setq result (point)))))))
  21537. (goto-char result))
  21538. (beginning-of-line))))
  21539. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21540. "Move backward to the ARG'th subheading at same level as this one.
  21541. Stop at the first and last subheadings of a superior heading."
  21542. (interactive "p")
  21543. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21544. (defun org-next-visible-heading (arg)
  21545. "Move to the next visible heading.
  21546. This function wraps `outline-next-visible-heading' with
  21547. `org-with-limited-levels' in order to skip over inline tasks and
  21548. respect customization of `org-odd-levels-only'."
  21549. (interactive "p")
  21550. (org-with-limited-levels
  21551. (outline-next-visible-heading arg)))
  21552. (defun org-previous-visible-heading (arg)
  21553. "Move to the previous visible heading.
  21554. This function wraps `outline-previous-visible-heading' with
  21555. `org-with-limited-levels' in order to skip over inline tasks and
  21556. respect customization of `org-odd-levels-only'."
  21557. (interactive "p")
  21558. (org-with-limited-levels
  21559. (outline-previous-visible-heading arg)))
  21560. (defun org-next-block (arg &optional backward block-regexp)
  21561. "Jump to the next block.
  21562. With a prefix argument ARG, jump forward ARG many blocks.
  21563. When BACKWARD is non-nil, jump to the previous block.
  21564. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  21565. Match data is set according to this regexp when the function
  21566. returns.
  21567. Return point at beginning of the opening line of found block.
  21568. Throw an error if no block is found."
  21569. (interactive "p")
  21570. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  21571. (case-fold-search t)
  21572. (search-fn (if backward #'re-search-backward #'re-search-forward))
  21573. (count (or arg 1))
  21574. (origin (point))
  21575. last-element)
  21576. (if backward (beginning-of-line) (end-of-line))
  21577. (while (and (> count 0) (funcall search-fn re nil t))
  21578. (let ((element (save-excursion
  21579. (goto-char (match-beginning 0))
  21580. (save-match-data (org-element-at-point)))))
  21581. (when (and (memq (org-element-type element)
  21582. '(center-block comment-block dynamic-block
  21583. example-block export-block quote-block
  21584. special-block src-block verse-block))
  21585. (<= (match-beginning 0)
  21586. (org-element-property :post-affiliated element)))
  21587. (setq last-element element)
  21588. (cl-decf count))))
  21589. (if (= count 0)
  21590. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  21591. (save-match-data (org-show-context)))
  21592. (goto-char origin)
  21593. (user-error "No %s code blocks" (if backward "previous" "further")))))
  21594. (defun org-previous-block (arg &optional block-regexp)
  21595. "Jump to the previous block.
  21596. With a prefix argument ARG, jump backward ARG many source blocks.
  21597. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  21598. (interactive "p")
  21599. (org-next-block arg t block-regexp))
  21600. (defun org-forward-paragraph ()
  21601. "Move forward to beginning of next paragraph or equivalent.
  21602. The function moves point to the beginning of the next visible
  21603. structural element, which can be a paragraph, a table, a list
  21604. item, etc. It also provides some special moves for convenience:
  21605. - On an affiliated keyword, jump to the beginning of the
  21606. relative element.
  21607. - On an item or a footnote definition, move to the second
  21608. element inside, if any.
  21609. - On a table or a property drawer, jump after it.
  21610. - On a verse or source block, stop after blank lines."
  21611. (interactive)
  21612. (unless (eobp)
  21613. (let* ((deactivate-mark nil)
  21614. (element (org-element-at-point))
  21615. (type (org-element-type element))
  21616. (post-affiliated (org-element-property :post-affiliated element))
  21617. (contents-begin (org-element-property :contents-begin element))
  21618. (contents-end (org-element-property :contents-end element))
  21619. (end (let ((end (org-element-property :end element)) (parent element))
  21620. (while (and (setq parent (org-element-property :parent parent))
  21621. (= (org-element-property :contents-end parent) end))
  21622. (setq end (org-element-property :end parent)))
  21623. end)))
  21624. (cond ((not element)
  21625. (skip-chars-forward " \r\t\n")
  21626. (or (eobp) (beginning-of-line)))
  21627. ;; On affiliated keywords, move to element's beginning.
  21628. ((< (point) post-affiliated)
  21629. (goto-char post-affiliated))
  21630. ;; At a table row, move to the end of the table. Similarly,
  21631. ;; at a node property, move to the end of the property
  21632. ;; drawer.
  21633. ((memq type '(node-property table-row))
  21634. (goto-char (org-element-property
  21635. :end (org-element-property :parent element))))
  21636. ((memq type '(property-drawer table)) (goto-char end))
  21637. ;; Consider blank lines as separators in verse and source
  21638. ;; blocks to ease editing.
  21639. ((memq type '(src-block verse-block))
  21640. (when (eq type 'src-block)
  21641. (setq contents-end
  21642. (save-excursion (goto-char end)
  21643. (skip-chars-backward " \r\t\n")
  21644. (line-beginning-position))))
  21645. (beginning-of-line)
  21646. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21647. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21648. (goto-char end)
  21649. (skip-chars-forward " \r\t\n")
  21650. (if (= (point) contents-end) (goto-char end)
  21651. (beginning-of-line))))
  21652. ;; With no contents, just skip element.
  21653. ((not contents-begin) (goto-char end))
  21654. ;; If contents are invisible, skip the element altogether.
  21655. ((org-invisible-p (line-end-position))
  21656. (cl-case type
  21657. (headline
  21658. (org-with-limited-levels (outline-next-visible-heading 1)))
  21659. ;; At a plain list, make sure we move to the next item
  21660. ;; instead of skipping the whole list.
  21661. (plain-list (forward-char)
  21662. (org-forward-paragraph))
  21663. (otherwise (goto-char end))))
  21664. ((>= (point) contents-end) (goto-char end))
  21665. ((>= (point) contents-begin)
  21666. ;; This can only happen on paragraphs and plain lists.
  21667. (cl-case type
  21668. (paragraph (goto-char end))
  21669. ;; At a plain list, try to move to second element in
  21670. ;; first item, if possible.
  21671. (plain-list (end-of-line)
  21672. (org-forward-paragraph))))
  21673. ;; When contents start on the middle of a line (e.g. in
  21674. ;; items and footnote definitions), try to reach first
  21675. ;; element starting after current line.
  21676. ((> (line-end-position) contents-begin)
  21677. (end-of-line)
  21678. (org-forward-paragraph))
  21679. (t (goto-char contents-begin))))))
  21680. (defun org-backward-paragraph ()
  21681. "Move backward to start of previous paragraph or equivalent.
  21682. The function moves point to the beginning of the current
  21683. structural element, which can be a paragraph, a table, a list
  21684. item, etc., or to the beginning of the previous visible one if
  21685. point is already there. It also provides some special moves for
  21686. convenience:
  21687. - On an affiliated keyword, jump to the first one.
  21688. - On a table or a property drawer, move to its beginning.
  21689. - On comment, example, export, src and verse blocks, stop
  21690. before blank lines."
  21691. (interactive)
  21692. (unless (bobp)
  21693. (let* ((deactivate-mark nil)
  21694. (element (org-element-at-point))
  21695. (type (org-element-type element))
  21696. (contents-end (org-element-property :contents-end element))
  21697. (post-affiliated (org-element-property :post-affiliated element))
  21698. (begin (org-element-property :begin element))
  21699. (special? ;blocks handled specially
  21700. (memq type '(comment-block example-block export-block src-block
  21701. verse-block)))
  21702. (contents-begin
  21703. (if special?
  21704. ;; These types have no proper contents. Fake line
  21705. ;; below the block opening line as contents beginning.
  21706. (save-excursion (goto-char begin) (line-beginning-position 2))
  21707. (org-element-property :contents-begin element))))
  21708. (cond
  21709. ((not element) (goto-char (point-min)))
  21710. ((= (point) begin)
  21711. (backward-char)
  21712. (org-backward-paragraph))
  21713. ((<= (point) post-affiliated) (goto-char begin))
  21714. ;; Special behavior: on a table or a property drawer, move to
  21715. ;; its beginning.
  21716. ((memq type '(node-property table-row))
  21717. (goto-char (org-element-property
  21718. :post-affiliated (org-element-property :parent element))))
  21719. (special?
  21720. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21721. ;; Inside a verse block, see blank lines as paragraph
  21722. ;; separators.
  21723. (let ((origin (point)))
  21724. (skip-chars-backward " \r\t\n" contents-begin)
  21725. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21726. (skip-chars-forward " \r\t\n" origin)
  21727. (if (= (point) origin) (goto-char contents-begin)
  21728. (beginning-of-line))))))
  21729. ((eq type 'paragraph) (goto-char contents-begin)
  21730. ;; When at first paragraph in an item or a footnote definition,
  21731. ;; move directly to beginning of line.
  21732. (let ((parent-contents
  21733. (org-element-property
  21734. :contents-begin (org-element-property :parent element))))
  21735. (when (and parent-contents (= parent-contents contents-begin))
  21736. (beginning-of-line))))
  21737. ;; At the end of a greater element, move to the beginning of
  21738. ;; the last element within.
  21739. ((and contents-end (>= (point) contents-end))
  21740. (goto-char (1- contents-end))
  21741. (org-backward-paragraph))
  21742. (t (goto-char (or post-affiliated begin))))
  21743. ;; Ensure we never leave point invisible.
  21744. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21745. (defun org-forward-element ()
  21746. "Move forward by one element.
  21747. Move to the next element at the same level, when possible."
  21748. (interactive)
  21749. (cond ((eobp) (user-error "Cannot move further down"))
  21750. ((org-with-limited-levels (org-at-heading-p))
  21751. (let ((origin (point)))
  21752. (goto-char (org-end-of-subtree nil t))
  21753. (unless (org-with-limited-levels (org-at-heading-p))
  21754. (goto-char origin)
  21755. (user-error "Cannot move further down"))))
  21756. (t
  21757. (let* ((elem (org-element-at-point))
  21758. (end (org-element-property :end elem))
  21759. (parent (org-element-property :parent elem)))
  21760. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21761. (goto-char (org-element-property :end parent)))
  21762. ((integer-or-marker-p end) (goto-char end))
  21763. (t (message "No element at point")))))))
  21764. (defun org-backward-element ()
  21765. "Move backward by one element.
  21766. Move to the previous element at the same level, when possible."
  21767. (interactive)
  21768. (cond ((bobp) (user-error "Cannot move further up"))
  21769. ((org-with-limited-levels (org-at-heading-p))
  21770. ;; At a headline, move to the previous one, if any, or stay
  21771. ;; here.
  21772. (let ((origin (point)))
  21773. (org-with-limited-levels (org-backward-heading-same-level 1))
  21774. ;; When current headline has no sibling above, move to its
  21775. ;; parent.
  21776. (when (= (point) origin)
  21777. (or (org-with-limited-levels (org-up-heading-safe))
  21778. (progn (goto-char origin)
  21779. (user-error "Cannot move further up"))))))
  21780. (t
  21781. (let* ((elem (org-element-at-point))
  21782. (beg (org-element-property :begin elem)))
  21783. (cond
  21784. ;; Move to beginning of current element if point isn't
  21785. ;; there already.
  21786. ((null beg) (message "No element at point"))
  21787. ((/= (point) beg) (goto-char beg))
  21788. (t (goto-char beg)
  21789. (skip-chars-backward " \r\t\n")
  21790. (unless (bobp)
  21791. (let ((prev (org-element-at-point)))
  21792. (goto-char (org-element-property :begin prev))
  21793. (while (and (setq prev (org-element-property :parent prev))
  21794. (<= (org-element-property :end prev) beg))
  21795. (goto-char (org-element-property :begin prev)))))))))))
  21796. (defun org-up-element ()
  21797. "Move to upper element."
  21798. (interactive)
  21799. (if (org-with-limited-levels (org-at-heading-p))
  21800. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21801. (let* ((elem (org-element-at-point))
  21802. (parent (org-element-property :parent elem)))
  21803. (if parent (goto-char (org-element-property :begin parent))
  21804. (if (org-with-limited-levels (org-before-first-heading-p))
  21805. (user-error "No surrounding element")
  21806. (org-with-limited-levels (org-back-to-heading)))))))
  21807. (defun org-down-element ()
  21808. "Move to inner element."
  21809. (interactive)
  21810. (let ((element (org-element-at-point)))
  21811. (cond
  21812. ((memq (org-element-type element) '(plain-list table))
  21813. (goto-char (org-element-property :contents-begin element))
  21814. (forward-char))
  21815. ((memq (org-element-type element) org-element-greater-elements)
  21816. ;; If contents are hidden, first disclose them.
  21817. (when (org-invisible-p (line-end-position)) (org-cycle))
  21818. (goto-char (or (org-element-property :contents-begin element)
  21819. (user-error "No content for this element"))))
  21820. (t (user-error "No inner element")))))
  21821. (defun org-drag-element-backward ()
  21822. "Move backward element at point."
  21823. (interactive)
  21824. (let ((elem (or (org-element-at-point)
  21825. (user-error "No element at point"))))
  21826. (if (eq (org-element-type elem) 'headline)
  21827. ;; Preserve point when moving a whole tree, even if point was
  21828. ;; on blank lines below the headline.
  21829. (let ((offset (skip-chars-backward " \t\n")))
  21830. (unwind-protect (org-move-subtree-up)
  21831. (forward-char (- offset))))
  21832. (let ((prev-elem
  21833. (save-excursion
  21834. (goto-char (org-element-property :begin elem))
  21835. (skip-chars-backward " \r\t\n")
  21836. (unless (bobp)
  21837. (let* ((beg (org-element-property :begin elem))
  21838. (prev (org-element-at-point))
  21839. (up prev))
  21840. (while (and (setq up (org-element-property :parent up))
  21841. (<= (org-element-property :end up) beg))
  21842. (setq prev up))
  21843. prev)))))
  21844. ;; Error out if no previous element or previous element is
  21845. ;; a parent of the current one.
  21846. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21847. (user-error "Cannot drag element backward")
  21848. (let ((pos (point)))
  21849. (org-element-swap-A-B prev-elem elem)
  21850. (goto-char (+ (org-element-property :begin prev-elem)
  21851. (- pos (org-element-property :begin elem))))))))))
  21852. (defun org-drag-element-forward ()
  21853. "Move forward element at point."
  21854. (interactive)
  21855. (let* ((pos (point))
  21856. (elem (or (org-element-at-point)
  21857. (user-error "No element at point"))))
  21858. (when (= (point-max) (org-element-property :end elem))
  21859. (user-error "Cannot drag element forward"))
  21860. (goto-char (org-element-property :end elem))
  21861. (let ((next-elem (org-element-at-point)))
  21862. (when (or (org-element-nested-p elem next-elem)
  21863. (and (eq (org-element-type next-elem) 'headline)
  21864. (not (eq (org-element-type elem) 'headline))))
  21865. (goto-char pos)
  21866. (user-error "Cannot drag element forward"))
  21867. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21868. ;; body's length (without final blanks) and by the length of
  21869. ;; blanks between ELEM and NEXT-ELEM.
  21870. (let ((size-next (- (save-excursion
  21871. (goto-char (org-element-property :end next-elem))
  21872. (skip-chars-backward " \r\t\n")
  21873. (forward-line)
  21874. ;; Small correction if buffer doesn't end
  21875. ;; with a newline character.
  21876. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21877. (org-element-property :begin next-elem)))
  21878. (size-blank (- (org-element-property :end elem)
  21879. (save-excursion
  21880. (goto-char (org-element-property :end elem))
  21881. (skip-chars-backward " \r\t\n")
  21882. (forward-line)
  21883. (point)))))
  21884. (org-element-swap-A-B elem next-elem)
  21885. (goto-char (+ pos size-next size-blank))))))
  21886. (defun org-drag-line-forward (arg)
  21887. "Drag the line at point ARG lines forward."
  21888. (interactive "p")
  21889. (dotimes (_ (abs arg))
  21890. (let ((c (current-column)))
  21891. (if (< 0 arg)
  21892. (progn
  21893. (beginning-of-line 2)
  21894. (transpose-lines 1)
  21895. (beginning-of-line 0))
  21896. (transpose-lines 1)
  21897. (beginning-of-line -1))
  21898. (org-move-to-column c))))
  21899. (defun org-drag-line-backward (arg)
  21900. "Drag the line at point ARG lines backward."
  21901. (interactive "p")
  21902. (org-drag-line-forward (- arg)))
  21903. (defun org-mark-element ()
  21904. "Put point at beginning of this element, mark at end.
  21905. Interactively, if this command is repeated or (in Transient Mark
  21906. mode) if the mark is active, it marks the next element after the
  21907. ones already marked."
  21908. (interactive)
  21909. (let (deactivate-mark)
  21910. (if (and (called-interactively-p 'any)
  21911. (or (and (eq last-command this-command) (mark t))
  21912. (and transient-mark-mode mark-active)))
  21913. (set-mark
  21914. (save-excursion
  21915. (goto-char (mark))
  21916. (goto-char (org-element-property :end (org-element-at-point)))))
  21917. (let ((element (org-element-at-point)))
  21918. (end-of-line)
  21919. (push-mark (org-element-property :end element) t t)
  21920. (goto-char (org-element-property :begin element))))))
  21921. (defun org-narrow-to-element ()
  21922. "Narrow buffer to current element."
  21923. (interactive)
  21924. (let ((elem (org-element-at-point)))
  21925. (cond
  21926. ((eq (car elem) 'headline)
  21927. (narrow-to-region
  21928. (org-element-property :begin elem)
  21929. (org-element-property :end elem)))
  21930. ((memq (car elem) org-element-greater-elements)
  21931. (narrow-to-region
  21932. (org-element-property :contents-begin elem)
  21933. (org-element-property :contents-end elem)))
  21934. (t
  21935. (narrow-to-region
  21936. (org-element-property :begin elem)
  21937. (org-element-property :end elem))))))
  21938. (defun org-transpose-element ()
  21939. "Transpose current and previous elements, keeping blank lines between.
  21940. Point is moved after both elements."
  21941. (interactive)
  21942. (org-skip-whitespace)
  21943. (let ((end (org-element-property :end (org-element-at-point))))
  21944. (org-drag-element-backward)
  21945. (goto-char end)))
  21946. (defun org-unindent-buffer ()
  21947. "Un-indent the visible part of the buffer.
  21948. Relative indentation (between items, inside blocks, etc.) isn't
  21949. modified."
  21950. (interactive)
  21951. (unless (eq major-mode 'org-mode)
  21952. (user-error "Cannot un-indent a buffer not in Org mode"))
  21953. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21954. (unindent-tree
  21955. (lambda (contents)
  21956. (dolist (element (reverse contents))
  21957. (if (memq (org-element-type element) '(headline section))
  21958. (funcall unindent-tree (org-element-contents element))
  21959. (save-excursion
  21960. (save-restriction
  21961. (narrow-to-region
  21962. (org-element-property :begin element)
  21963. (org-element-property :end element))
  21964. (org-do-remove-indentation))))))))
  21965. (funcall unindent-tree (org-element-contents parse-tree))))
  21966. (defun org-show-children (&optional level)
  21967. "Show all direct subheadings of this heading.
  21968. Prefix arg LEVEL is how many levels below the current level
  21969. should be shown. Default is enough to cause the following
  21970. heading to appear."
  21971. (interactive "p")
  21972. ;; If `orgstruct-mode' is active, use the slower version.
  21973. (if orgstruct-mode (call-interactively #'outline-show-children)
  21974. (save-excursion
  21975. (org-back-to-heading t)
  21976. (let* ((current-level (funcall outline-level))
  21977. (max-level (org-get-valid-level
  21978. current-level
  21979. (if level (prefix-numeric-value level) 1)))
  21980. (end (save-excursion (org-end-of-subtree t t)))
  21981. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  21982. (past-first-child nil)
  21983. ;; Make sure to skip inlinetasks.
  21984. (re (format regexp-fmt
  21985. current-level
  21986. (cond
  21987. ((not (featurep 'org-inlinetask)) "")
  21988. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  21989. 3))
  21990. (t (1- org-inlinetask-min-level))))))
  21991. ;; Display parent heading.
  21992. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  21993. (forward-line)
  21994. ;; Display children. First child may be deeper than expected
  21995. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  21996. ;; MAX-LEVEL accordingly.
  21997. (while (re-search-forward re end t)
  21998. (unless past-first-child
  21999. (setq re (format regexp-fmt
  22000. current-level
  22001. (max (funcall outline-level) max-level)))
  22002. (setq past-first-child t))
  22003. (outline-flag-region
  22004. (line-end-position 0) (line-end-position) nil))))))
  22005. (defun org-show-subtree ()
  22006. "Show everything after this heading at deeper levels."
  22007. (interactive)
  22008. (outline-flag-region
  22009. (point)
  22010. (save-excursion
  22011. (org-end-of-subtree t t))
  22012. nil))
  22013. (defun org-show-entry ()
  22014. "Show the body directly following this heading.
  22015. Show the heading too, if it is currently invisible."
  22016. (interactive)
  22017. (save-excursion
  22018. (ignore-errors
  22019. (org-back-to-heading t)
  22020. (outline-flag-region
  22021. (max (point-min) (1- (point)))
  22022. (save-excursion
  22023. (if (re-search-forward
  22024. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22025. (match-beginning 1)
  22026. (point-max)))
  22027. nil)
  22028. (org-cycle-hide-drawers 'children))))
  22029. (defun org-make-options-regexp (kwds &optional extra)
  22030. "Make a regular expression for keyword lines.
  22031. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22032. when non-nil, is a regexp matching keywords names."
  22033. (concat "^[ \t]*#\\+\\("
  22034. (regexp-opt kwds)
  22035. (and extra (concat (and kwds "\\|") extra))
  22036. "\\):[ \t]*\\(.*\\)"))
  22037. ;;;; Finish up
  22038. (provide 'org)
  22039. (run-hooks 'org-load-hook)
  22040. ;;; org.el ends here